use hahn;

$src_root = "//logs/visit-v2-log/1d";
$dst_root = "//home/webmaster/prod/analytics/metrika/visit-v2-log/30468942";

$PERIOD = 14;

$src_days = (
    select aggregate_list(Period)
    from (
        select TableName(Path, "yt") as Period
        from folder($src_root)
        where Type == "table"
        order by Period desc
        limit $PERIOD
    )
);

$dst_days = (
    select aggregate_list(Period)
    from (
        select TableName(Path, "yt") as Period
        from folder($dst_root)
        where Type == "table"
        order by Period desc
        limit $PERIOD
    )
);

define action $copy_logs($day) as 
    $src_path = $src_root || "/" || $day;
    $dst_path = $dst_root || "/" || $day;

    insert into $dst_path
        with truncate
    select *
    from $src_path
    where CounterID == 30468942
    order by 
        CounterID,
        UserID,
        VisitID,
        VisitVersion,
        Sign
end define;

evaluate for $day in $src_days do
    begin
        evaluate if not ListHas($dst_days, $day) do
            $copy_logs($day)
    end do
else 
    do empty_action();
