use arnold;
--pragma yt.AutoMerge="disabled";

$TimestampToStr = ($ts) -> {
    return cast(
        DateTime::MakeDate(
            DateTime::StartOfWeek(
                DateTime::FromSeconds(
                    cast($ts as Uint32)
                )
            )
        ) as String
    )
};

$gsc_ywm = (
    select *
    from (
        select * from range(`//home/webmaster/prod/analytics/engagement/gsc_vs_ywm/daily`)
        union all
        select * from `//home/webmaster/prod/analytics/engagement/gsc_vs_ywm/history`
    )
    where Geo::RoundRegionById(cast(RegionId as Int32), "country").id == 225 /* Россия */
        and TableSource == "clean"
        and not IsMobile
);


$total = (
    select *
    from (
        select * 
        from range(`//home/webmaster/prod/analytics/engagement/total/similargroup/daily`)
        union all
        select * 
        from `//home/webmaster/prod/analytics/engagement/total/similargroup/history`
    )
    where TableSource == "clean"
);

$ywm = (
    select 
        Period,
        count(*) as VisitsYWM,
        count(distinct UID) as VisitorsYWM
    from $gsc_ywm
    where YandexWM 
    group by $TimestampToStr(`Timestamp`) as Period
);

$gsc = (
    select 
        Period,
        count(*) as VisitsGSC,
        count(distinct UID) as VisitorsGSC
    from $gsc_ywm
    where GoogleSC
    group by $TimestampToStr(`Timestamp`) as Period
);

insert into `//home/webmaster/prod/analytics/engagement/gsc_vs_ywm/stats`
    with truncate
select 
    ywm.Period as Period,
    VisitsGSC,
    VisitsYWM,
    VisitorsGSC,
    VisitorsYWM,
    total.Visits as VisitsTotal,
    total.Visitors as VisitorsTotal
from $ywm as ywm
join $gsc as gsc
    on ywm.Period == gsc.Period
join $total as total
    on ywm.Period == total.Period
order by Period
