use arnold;

$table_input    = "//home/webmaster/prod/export/iks_rival";
$table_output   = "//home/webmaster/prod/analytics/rivals/rivals";
$table_history  = "//home/webmaster/prod/analytics/rivals/rivals-history";
$current_date   = cast(CurrentUtcDate() as String);

$host_id_to_host = ($host_id) -> {
    $parts = String::SplitToList($host_id, ":");
    return if (
        $parts[2] in ("80", "443"),
        $parts[0] || "://" || $parts[1],
        $parts[0] || "://" || $parts[1] || ":" || $parts[2]
    );
};

$data = (
    select 
        Host,
        $current_date as Period,
        aggregate_list(rival) as Rivals
    from $table_input
    group by
        $host_id_to_host(host_id) as Host
);

insert into $table_output
    with truncate
select 
    Host,
    Period,
    Rivals
from $data
order by Host, Period;
commit;

insert into $table_history
    with truncate
select 
    Host,
    Period,
    some(Rivals) as Rivals
from concat($table_output, $table_history)
group by Host, Period
order by Host, Period
