use arnold;
pragma yt.ForceInferSchema;

-- last table
$b2bTop = (
    SELECT AGGREGATE_LIST(Path) FROM (
        SELECT Path FROM FOLDER(`//home/webmaster/prod/b2b-top/weekly/report/all/owners`) WHERE Type == "table" ORDER BY Path DESC LIMIT 1
    )
);

$ownersWithBigFavicons = (
    SELECT Owner, MAX(fav32.ImageHash <> fav120.ImageHash or fav120.Url like '%.svg') as HasBigFavicon
    FROM `//home/favicon-robot/Base/_prod/support_table` as fav32
    INNER JOIN `//home/favicon-robot/Base/_prod/support_table` as fav120
    ON fav32.Key == fav120.Key
    WHERE fav32.TargetSize == 32 AND fav120.TargetSize == 120
    GROUP BY Url::GetOwner(fav120.Host) as Owner
);

INSERT INTO `//home/webmaster/prod/favicons/big-favicons-count`
SELECT CurrentUtcDate() as Day,
    COUNT(*) as Total,
    COUNT_IF(fav.HasBigFavicon) as BigTotal,
    COUNT_IF(fav.HasBigFavicon and b2b.`Top` <= 100) as BigTop100,
    COUNT_IF(fav.HasBigFavicon and b2b.`Top` <= 1000) as BigTop1000,
    COUNT_IF(fav.HasBigFavicon and b2b.`Top` <= 10000) as BigTop10000,
    COUNT_IF(fav.HasBigFavicon and b2b.`Top` <= 100000) as BigTop100000,
    COUNT_IF(fav.Owner is not null and b2b.`Top` <= 100) as Top100,
    COUNT_IF(fav.Owner is not null and b2b.`Top` <= 1000) as Top1000,
    COUNT_IF(fav.Owner is not null and b2b.`Top` <= 10000) as Top10000,
    COUNT_IF(fav.Owner is not null and b2b.`Top` <= 100000) as Top100000
FROM $ownersWithBigFavicons as fav
LEFT JOIN EACH($b2bTop) as b2b
ON fav.Owner = b2b.Name;

INSERT INTO `//home/webmaster/prod/favicons/big-favicons-owners`
SELECT CurrentUtcDate() as Day, Owner
FROM $ownersWithBigFavicons WHERE HasBigFavicon;