use hahn;

-- moved from https://hitman.yandex-team.ru/projects/wmc-5084/

$tmp_range1 = (
    select
        simdistance,
        count_if(CH.countertype == 1) as Shows,
        count_if(CH.countertype == 2) as Clicks,
        sum(cast(CH.eventcost as Double)) / 1000000 as Cost,
        day
    from range(`statbox/cooked_logs/bs-chevent-cooked-log/v2/1d`, `2017-09-01`, `2018-06-07`) as CH
    where CH.contexttype == 7
        and CH.fraudbits == 0
    group by
        if (CH.simdistance == 700010 or CH.simdistance == 700050, "our", "other") as simdistance,
        DateTime::ToDate(DateTime::FromSeconds(CAST(CH.eventtime as Uint64))) as day
);

$tmp_range2 = (
    select
        simdistance,
        count_if(CH.countertype == 1) as Shows,
        count_if(CH.countertype == 2) as Clicks,
        sum(cast(CH.eventcost as Double)) / 1000000 as Cost,
        day
    from range(`statbox/cooked_logs/bs-chevent-cooked-log/v2/1d`, `2018-06-08`) as CH
    where CH.contexttype == 7
        and CH.fraudbits == 0
    group by
        if (CH.simdistance == 700010 or CH.simdistance == 700050, "our", "other") as simdistance,
        DateTime::ToDate(DateTime::FromSeconds(CAST(CH.eventtime as Uint64))) as day
);

$tmp = (
              select simdistance, Shows, Clicks, Cost, day from $tmp_range1
    union all select simdistance, Shows, Clicks, Cost, day from $tmp_range2
);

insert into `//home/webmaster/users/aleksart/wmc-5084/daily/webmaster` with truncate 
    select day, sum(Shows) as Shows, sum(Clicks) as Clicks, sum(Cost) as Cost
    from $tmp
    where simdistance == "our"
    group by day;
       
insert into `//home/webmaster/users/aleksart/wmc-5084/daily/other` with truncate 
    select  day, sum(Shows) as Shows, sum(Clicks) as Clicks, sum(Cost) as Cost
    from $tmp
    group by day;
       
insert into `//home/webmaster/users/aleksart/wmc-5084/weekly/webmaster` with truncate 
    select week, sum(Shows) as Shows, sum(Clicks) as Clicks, sum(Cost) as Cost
    from $tmp
    where simdistance == "our" 
    group by DateTime::ToString(DateTime::DateStartOfWeek(CAST(day AS Date))) as week;
       
insert into `//home/webmaster/users/aleksart/wmc-5084/weekly/other` with truncate 
    select week, sum(Shows) as Shows, sum(Clicks) as Clicks, sum(Cost) as Cost
    from $tmp 
    group by DateTime::ToString(DateTime::DateStartOfWeek(CAST(day as Date))) as week;
       
insert into `//home/webmaster/users/aleksart/wmc-5084/monthly/webmaster` with truncate 
    select month, sum(Shows) as Shows, sum(Clicks) as Clicks, sum(Cost) as Cost
    from $tmp
    where simdistance == "our" 
    group by DateTime::ToString(DateTime::DateStartOfMonth(CAST(day as Date))) as month;
       
insert into `//home/webmaster/users/aleksart/wmc-5084/monthly/other` with truncate 
    select month, sum(Shows) as Shows, sum(Clicks) as Clicks, sum(Cost) as Cost
    from $tmp 
    group by DateTime::ToString(DateTime::DateStartOfMonth(CAST(day as Date))) as month;
    