#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use utf8;
binmode(STDOUT, ":utf8");

my $json_text = do { local $/; <STDIN> };
my $input_data = decode_json($json_text);

my $restaurant_id = $input_data->{restaurant_id};
my $start_date    = $input_data->{start_date};
my $end_date      = $input_data->{end_date};
my $records       = $input_data->{data};

my %output = (
    restaurant_id => $restaurant_id,
    date_range => {
        start => $start_date,
        end   => $end_date,
    },
    predictions => [],
);

my %by_date;
foreach my $row (@$records) {
    my $date        = $row->{prediction_date};
    my $table_id    = $row->{table_id};
    my $table_label = $row->{table_label};
    my $hour        = $row->{hour};
    my $customers_hour = $row->{total_customers_hour};
    my $customers_table = $row->{total_customers_table};
    my $customers_restaurant = $row->{total_customers_restaurant};

    $by_date{$date}->{total_reservations}++;
    $by_date{$date}->{total_customers} += $customers_restaurant;

    $by_date{$date}->{tables}{$table_id}->{table_label} = $table_label;
    $by_date{$date}->{tables}{$table_id}->{total_customers} += $customers_table;
    push @{ $by_date{$date}->{tables}{$table_id}->{by_hour} }, {
        hour => $hour,
        total_customers => $customers_hour,
    };
}

foreach my $date (sort keys %by_date) {
    my $entry = {
        date               => $date,
        total_reservations => $by_date{$date}->{total_reservations},
        total_customers    => $by_date{$date}->{total_customers},
        tables             => [],
    };

    foreach my $table_id (sort keys %{ $by_date{$date}->{tables} }) {
        my $tdata = $by_date{$date}->{tables}{$table_id};
        push @{ $entry->{tables} }, {
            table_id        => $table_id,
            table_label     => $tdata->{table_label},
            total_customers => $tdata->{total_customers},
            by_hour         => $tdata->{by_hour},
        };
    }

    push @{ $output{predictions} }, $entry;
}

print to_json(\%output, { utf8 => 1, pretty => 1 });