<?php

namespace App\Campaigns;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;

/**
 * Two equal windows of one campaign, compared on the metrics already stored for it.
 */
class CampaignComparisonReader
{
    /**
     * Result metrics that decide which window did better. Spend and CTR stay in the table only.
     *
     * @var list<string>
     */
    private const RESULT_KEYS = [
        'conversions',
        'affiliate_sales',
        'affiliate_orders',
        'roi_sales',
        'roi_orders',
        'roi_conversions',
        'roi_subscriptions',
        'roi_installs',
        'roi_bookings',
        'roi_leads',
    ];

    /**
     * @var array<string, string>
     */
    private const LABELS = [
        'spend' => 'Spend',
        'impressions' => 'Impressions',
        'reach' => 'Reach',
        'clicks' => 'Clicks',
        'ctr' => 'CTR',
        'cpc' => 'CPC',
        'conversions' => 'Conversions',
        'affiliate_clicks' => 'Affiliate clicks',
        'affiliate_sum_cpc' => 'Affiliate CPC sum',
        'affiliate_orders' => 'Affiliate orders',
        'affiliate_sales' => 'Affiliate sales',
        'roi_conversions' => 'ROI conversions',
        'roi_subscriptions' => 'Subscriptions',
        'roi_cancellations' => 'Cancellations',
        'roi_installs' => 'Installs',
        'roi_bookings' => 'Bookings',
        'roi_leads' => 'Leads',
        'roi_estimated_revenue' => 'Estimated revenue',
        'roi_orders' => 'ROI orders',
        'roi_sales' => 'ROI sales',
    ];

    /**
     * @var list<string>
     */
    private const MONEY_KEYS = [
        'spend',
        'cpc',
        'affiliate_sum_cpc',
        'affiliate_sales',
        'roi_sales',
        'roi_estimated_revenue',
    ];

    public function __construct(private readonly WhaleAdopsQuery $query) {}

    /**
     * @return array<string, mixed>
     */
    public function compare(
        string $platform,
        string $campaignId,
        ?string $preset = null,
        ?int $days = null,
        ?string $from = null,
        ?string $to = null,
        ?string $compareFrom = null,
        ?string $compareTo = null,
    ): array {
        $eachDay = $this->eachDayCount($preset, $days, $from, $to, $compareFrom, $compareTo);

        if ($eachDay !== null) {
            return $this->compareEachDay($platform, $campaignId, $eachDay);
        }

        $windows = $this->windows($preset, $days, $from, $to, $compareFrom, $compareTo);

        if (isset($windows['error'])) {
            return [
                'ok' => false,
                'error' => $windows['error'],
            ];
        }

        $current = $this->window($platform, $campaignId, $windows['current_from'], $windows['current_to']);
        $previous = $this->window($platform, $campaignId, $windows['previous_from'], $windows['previous_to']);
        $rows = $this->rows($current['metrics'], $previous['metrics']);
        $outcome = $this->outcome($current['metrics'], $previous['metrics']);
        $recommendations = $this->recommendations($current, $previous, $outcome);

        return [
            'ok' => true,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'campaign_name' => $this->campaignName($platform, $campaignId),
            'mode' => $windows['mode'],
            'current' => [
                'from' => $current['from'],
                'to' => $current['to'],
                'metrics' => $current['metrics'],
            ],
            'previous' => [
                'from' => $previous['from'],
                'to' => $previous['to'],
                'metrics' => $previous['metrics'],
            ],
            'rows' => $rows,
            'outcome' => $outcome,
            'recommendations' => $recommendations,
            'note' => $this->note($windows['current_from'], $windows['current_to'], $windows['previous_from'], $windows['previous_to']),
        ];
    }

    /**
     * Last N days, and the 3-day preset, are one column per day ending yesterday.
     */
    private function eachDayCount(?string $preset, ?int $days, ?string $from, ?string $to, ?string $compareFrom, ?string $compareTo): ?int
    {
        foreach ([$from, $to, $compareFrom, $compareTo] as $value) {
            if (is_string($value) && trim($value) !== '') {
                return null;
            }
        }

        if ($days !== null && $days >= 2) {
            return min($days, 31);
        }

        if ($this->preset($preset) === '3day') {
            return 3;
        }

        return null;
    }

    /**
     * @return array<string, mixed>
     */
    private function compareEachDay(string $platform, string $campaignId, int $count): array
    {
        $yesterday = now()->startOfDay()->subDay();
        $dates = [];

        for ($offset = 0; $offset < $count; $offset++) {
            $dates[] = $yesterday->copy()->subDays($offset)->toDateString();
        }

        $periods = [];

        foreach ($dates as $date) {
            $loaded = $this->window($platform, $campaignId, $date, $date);
            $periods[] = [
                'date' => $date,
                'from' => $date,
                'to' => $date,
                'metrics' => $loaded['metrics'],
            ];
        }

        $rows = $this->dayRows($dates, $periods);
        $outcome = $this->dayOutcome($dates, $periods);
        $newest = $periods[0];
        $older = $periods[1];

        return [
            'ok' => true,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'campaign_name' => $this->campaignName($platform, $campaignId),
            'mode' => 'days',
            'dates' => $dates,
            'current' => [
                'from' => $newest['from'],
                'to' => $newest['to'],
                'metrics' => $newest['metrics'],
            ],
            'previous' => [
                'from' => $older['from'],
                'to' => $older['to'],
                'metrics' => $older['metrics'],
            ],
            'periods' => $periods,
            'rows' => $rows,
            'outcome' => $outcome,
            'recommendations' => $this->dayRecommendations($periods, $outcome),
            'note' => $this->daysNote($dates),
        ];
    }

    /**
     * @param  list<string>  $dates
     * @param  list<array{date: string, metrics: array<string, int|float|null>}>  $periods
     * @return list<array{metric: string, key: string, values: array<string, int|float|null>, change: int|float|null, change_percent: float|null}>
     */
    private function dayRows(array $dates, array $periods): array
    {
        $byDate = [];

        foreach ($periods as $period) {
            $byDate[$period['date']] = $period['metrics'];
        }

        $rows = [];

        foreach (self::LABELS as $key => $label) {
            $values = [];

            foreach ($dates as $date) {
                $values[$date] = $byDate[$date][$key] ?? null;
            }

            $change = null;
            $percent = null;

            if (count($dates) === 2) {
                $left = $values[$dates[0]];
                $right = $values[$dates[1]];

                if ((is_int($left) || is_float($left)) && (is_int($right) || is_float($right))) {
                    $change = round($left - $right, 4);
                    $percent = (float) $right !== 0.0 ? round((($left - $right) / abs((float) $right)) * 100, 2) : null;
                }
            }

            $rows[] = [
                'metric' => $label,
                'key' => $key,
                'values' => $values,
                'change' => $change,
                'change_percent' => $percent,
            ];
        }

        return $rows;
    }

    /**
     * @param  list<string>  $dates
     * @param  list<array{date: string, metrics: array<string, int|float|null>}>  $periods
     * @return array{winner: string, ahead: list<array{date: string, key: string, label: string, values: array<string, int|float>}>}
     */
    private function dayOutcome(array $dates, array $periods): array
    {
        $metrics = [];

        foreach ($periods as $period) {
            $metrics[$period['date']] = $period['metrics'];
        }

        $ahead = [];

        foreach (self::RESULT_KEYS as $key) {
            $values = [];
            $complete = true;

            foreach ($dates as $date) {
                $value = $metrics[$date][$key] ?? null;

                if (! is_int($value) && ! is_float($value)) {
                    $complete = false;
                    break;
                }

                $values[$date] = $value;
            }

            if (! $complete || $values === []) {
                continue;
            }

            $highest = max($values);
            $winners = array_keys(array_filter(
                $values,
                fn (int|float $value): bool => (float) $value === (float) $highest,
            ));

            if (count($winners) !== 1 || count(array_unique(array_map(strval(...), $values))) < 2) {
                continue;
            }

            $ahead[] = [
                'date' => $winners[0],
                'key' => $key,
                'label' => self::LABELS[$key],
                'values' => $values,
            ];
        }

        $counts = [];

        foreach ($ahead as $item) {
            $counts[$item['date']] = ($counts[$item['date']] ?? 0) + 1;
        }

        $winner = 'tie';

        if ($counts !== []) {
            $best = max($counts);
            $leaders = array_keys(array_filter($counts, fn (int $count): bool => $count === $best));

            if (count($leaders) === 1) {
                $winner = $leaders[0];
            }
        }

        return [
            'winner' => $winner,
            'ahead' => $ahead,
        ];
    }

    /**
     * @param  list<array{date: string, from: string, to: string, metrics: array<string, int|float|null>}>  $periods
     * @param  array{winner: string, ahead: list<array{date: string, key: string, label: string, values: array<string, int|float>}>}  $outcome
     * @return list<array{action: string, why: string}>
     */
    private function dayRecommendations(array $periods, array $outcome): array
    {
        $newest = $periods[0];
        $spend = $newest['metrics']['spend'] ?? null;
        $newestResults = $this->resultTotal($newest['metrics']);
        $earlierResults = 0.0;

        foreach (array_slice($periods, 1) as $period) {
            $earlierResults += $this->resultTotal($period['metrics']);
        }

        $why = $this->dayWhy($periods, $outcome);

        if ((is_int($spend) || is_float($spend)) && (float) $spend > 0 && $newestResults === 0.0 && $earlierResults > 0) {
            return [[
                'action' => 'Do not scale. '.$newest['date'].' is the worse day.',
                'why' => 'Spend on '.$newest['date'].' is '.$this->quote('spend', $spend).' and its sales, orders, conversions, subscriptions, installs, bookings, and leads are 0. '.$why,
            ]];
        }

        if ($outcome['winner'] === $newest['date']) {
            return [[
                'action' => 'Keep '.$newest['date'].'. It is the better day.',
                'why' => $why,
            ]];
        }

        if ($outcome['winner'] !== 'tie') {
            return [[
                'action' => 'Do not increase the budget. '.$outcome['winner'].' is the better day.',
                'why' => $why,
            ]];
        }

        return [[
            'action' => 'Make no change from this comparison.',
            'why' => $why,
        ]];
    }

    /**
     * @param  list<array{date: string}>  $periods
     * @param  array{winner: string, ahead: list<array{date: string, key: string, label: string, values: array<string, int|float>}>}  $outcome
     */
    private function dayWhy(array $periods, array $outcome): string
    {
        $grouped = [];

        foreach ($outcome['ahead'] as $item) {
            $grouped[$item['date']][] = $item['label'].' ('.$this->dayValueList($item['key'], $item['values']).')';
        }

        $parts = [];

        foreach ($periods as $period) {
            $items = $grouped[$period['date']] ?? [];

            if ($items !== []) {
                $parts[] = $period['date'].' is ahead on '.implode(', ', $items).'.';
            }
        }

        if ($parts === []) {
            return 'Neither day is ahead on sales, orders, conversions, subscriptions, installs, bookings, or leads.';
        }

        if ($outcome['winner'] === 'tie') {
            $parts[] = 'Neither day is ahead on more result metrics, so neither is the better day.';
        } else {
            $parts[] = $outcome['winner'].' is the better day because it leads on more of those result metrics.';

            if (count($periods) === 2) {
                $other = $periods[0]['date'] === $outcome['winner'] ? $periods[1]['date'] : $periods[0]['date'];
                $parts[] = $other.' is the worse day.';
            }
        }

        return implode(' ', $parts);
    }

    /**
     * @param  array<string, int|float>  $values
     */
    private function dayValueList(string $key, array $values): string
    {
        $parts = [];

        foreach ($values as $date => $value) {
            $parts[] = $date.': '.$this->quote($key, $value);
        }

        return implode(', ', $parts);
    }

    /**
     * @param  list<string>  $dates
     */
    private function daysNote(array $dates): string
    {
        $change = count($dates) === 2
            ? ' Add a Change column that is '.$dates[0].' minus '.$dates[1].'.'
            : ' Do not add a Change column.';

        return 'Print the campaign name in bold. Do not use a markdown heading. Do not print the 30-day campaign stats table and do not call suggest_campaign for this question. '
            .'These dates are separate days ending yesterday. Do not include today. Do not total them into one window, and do not compare them with the days before this list. '
            .'Print one markdown table with columns Metric, '.implode(', ', $dates).'.'.$change.' '
            .'Print every returned rows item from rows[].values. When a value is null, print a dash. Print 0 when the value is zero. '
            .'Then say which day is better and which is worse. Name each metric in outcome.ahead and quote the values for every date. '
            .'Spend, impressions, reach, clicks, CTR, CPC, cancellations, and estimated revenue stay in the table and do not decide the winner. '
            .'Affiliate sales and ROI sales stay in separate rows. '
            .'Print each recommendations item with its action and why, quoting the numbers in why. '
            .'Do not change the health label or the verdict. Do not invent a page rewrite, page speed, profit, remaining budget, or a winning creative.';
    }

    /**
     * @return array{mode: string, current_from: string, current_to: string, previous_from: string, previous_to: string}|array{error: string}
     */
    private function windows(?string $preset, ?int $days, ?string $from, ?string $to, ?string $compareFrom, ?string $compareTo): array
    {
        $from = $this->date($from);
        $to = $this->date($to);
        $compareFrom = $this->date($compareFrom);
        $compareTo = $this->date($compareTo);

        if ($from !== null && $to !== null && $compareFrom !== null && $compareTo !== null) {
            if ($from > $to || $compareFrom > $compareTo) {
                return ['error' => 'Each range needs its start on or before its end.'];
            }

            return [
                'mode' => 'ranges',
                'current_from' => $from,
                'current_to' => $to,
                'previous_from' => $compareFrom,
                'previous_to' => $compareTo,
            ];
        }

        if ($from !== null && $to !== null) {
            if ($from > $to) {
                return ['error' => 'from must be on or before to.'];
            }

            [$previousFrom, $previousTo] = $this->preceding($from, $to);

            return [
                'mode' => 'range',
                'current_from' => $from,
                'current_to' => $to,
                'previous_from' => $previousFrom,
                'previous_to' => $previousTo,
            ];
        }

        if ($from !== null || $to !== null || $compareFrom !== null || $compareTo !== null) {
            return ['error' => 'Pass both from and to. Pass compare_from and compare_to only when comparing two named ranges.'];
        }

        $length = $this->length($preset, $days);

        if ($length === null) {
            return ['error' => 'Pass preset day, 3day, or week, or pass days, or pass from and to.'];
        }

        $currentTo = now()->startOfDay();
        $currentFrom = $currentTo->copy()->subDays($length - 1);
        [$previousFrom, $previousTo] = $this->preceding($currentFrom->toDateString(), $currentTo->toDateString());

        return [
            'mode' => $this->mode($preset, $days, $length),
            'current_from' => $currentFrom->toDateString(),
            'current_to' => $currentTo->toDateString(),
            'previous_from' => $previousFrom,
            'previous_to' => $previousTo,
        ];
    }

    private function length(?string $preset, ?int $days): ?int
    {
        if ($days !== null && $days > 0) {
            return min($days, 366);
        }

        return match ($this->preset($preset)) {
            'day' => 1,
            '3day' => 3,
            'week' => 7,
            default => null,
        };
    }

    private function mode(?string $preset, ?int $days, int $length): string
    {
        $preset = $this->preset($preset);

        if ($preset !== null && ($days === null || $days < 1)) {
            return $preset;
        }

        return match ($length) {
            1 => 'day',
            3 => '3day',
            7 => 'week',
            default => 'days',
        };
    }

    private function preset(?string $preset): ?string
    {
        $preset = strtolower(trim((string) $preset));

        return match ($preset) {
            'day', 'daily' => 'day',
            '3day', '3-day', '3' => '3day',
            'week', 'weekly' => 'week',
            default => null,
        };
    }

    /**
     * @return array{0: string, 1: string}
     */
    private function preceding(string $from, string $to): array
    {
        $start = Carbon::parse($from)->startOfDay();
        $end = Carbon::parse($to)->startOfDay();
        $length = (int) $start->diffInDays($end) + 1;
        $previousTo = $start->copy()->subDay();
        $previousFrom = $previousTo->copy()->subDays($length - 1);

        return [$previousFrom->toDateString(), $previousTo->toDateString()];
    }

    private function date(?string $value): ?string
    {
        if ($value === null || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
            return null;
        }

        $parsed = Carbon::createFromFormat('Y-m-d', $value);

        if ($parsed === false || $parsed->toDateString() !== $value) {
            return null;
        }

        return $value;
    }

    /**
     * @return array{from: string, to: string, metrics: array<string, int|float|null>}
     */
    private function window(string $platform, string $campaignId, string $from, string $to): array
    {
        $delivery = $this->delivery($platform, $campaignId, $from, $to);
        $affiliate = $this->summed('campaign_performance', $platform, $campaignId, $from, $to);
        $roi = $this->roi($platform, $campaignId, $from, $to);

        return [
            'from' => $from,
            'to' => $to,
            'metrics' => [
                'spend' => $this->metric($delivery, 'spend', true),
                'impressions' => $this->metric($delivery, 'impressions', true),
                'reach' => $this->metric($delivery, 'reach', false),
                'clicks' => $this->metric($delivery, 'clicks', true),
                'ctr' => $this->metric($delivery, 'ctr', false),
                'cpc' => $this->metric($delivery, 'cpc', false),
                'conversions' => $this->metric($delivery, 'conversions', false),
                'affiliate_clicks' => $this->metric($affiliate, 'clicks', true),
                'affiliate_sum_cpc' => $this->metric($affiliate, 'sum_cpc', true),
                'affiliate_orders' => $this->metric($affiliate, 'orders', true),
                'affiliate_sales' => $this->metric($affiliate, 'net_revenue', true),
                'roi_conversions' => $roi['conversions'],
                'roi_subscriptions' => $roi['subscriptions'],
                'roi_cancellations' => $roi['cancellations'],
                'roi_installs' => $roi['installs'],
                'roi_bookings' => $roi['bookings'],
                'roi_leads' => $roi['leads'],
                'roi_estimated_revenue' => $roi['estimated_revenue'],
                'roi_orders' => $roi['orders'],
                'roi_sales' => $roi['sales'],
            ],
        ];
    }

    /**
     * Campaign-daily stats for each day in the window. A day with no campaign-daily row
     * is filled from arb_adops_stats_daily_YYYYMM. A day present in both is not added twice.
     *
     * @return array<string, mixed>|null
     */
    private function delivery(string $platform, string $campaignId, string $from, string $to): ?array
    {
        $length = (int) Carbon::parse($from)->startOfDay()->diffInDays(Carbon::parse($to)->startOfDay()) + 1;

        if ($length > 100) {
            if ($this->hasDeliveryRows('stats_campaign_daily', $platform, $campaignId, $from, $to)) {
                return $this->summed('stats_campaign_daily', $platform, $campaignId, $from, $to);
            }

            return $this->summed('stats_daily', $platform, $campaignId, $from, $to);
        }

        $campaign = $this->rowsByDate('stats_campaign_daily', $platform, $campaignId, $from, $to, $length);
        $adDaily = $this->rowsByDate('stats_daily', $platform, $campaignId, $from, $to, $length);

        if ($campaign === null && $adDaily === null) {
            return null;
        }

        $campaign ??= [];
        $adDaily ??= [];
        $spend = 0.0;
        $impressions = 0.0;
        $clicks = 0.0;
        $reach = 0.0;
        $conversions = 0.0;
        $hasReach = false;
        $hasConversions = false;

        foreach (array_unique([...array_keys($campaign), ...array_keys($adDaily)]) as $date) {
            $row = $campaign[$date] ?? $adDaily[$date];
            $spend += (float) ($row['spend'] ?? 0);
            $impressions += (float) ($row['impressions'] ?? 0);
            $clicks += (float) ($row['clicks'] ?? 0);

            if (array_key_exists('reach', $row) && $row['reach'] !== null) {
                $hasReach = true;
                $reach += (float) $row['reach'];
            }

            $conversionValue = $this->conversionValue($campaign[$date] ?? null, $adDaily[$date] ?? null);

            if ($conversionValue !== null) {
                $hasConversions = true;
                $conversions += $conversionValue;
            }
        }

        return [
            'spend' => round($spend, 4),
            'impressions' => $impressions,
            'clicks' => $clicks,
            'conversions' => $hasConversions ? $conversions : null,
            'reach' => $hasReach ? $reach : null,
            'ctr' => $impressions > 0 ? round($clicks / $impressions, 4) : null,
            'cpc' => $clicks > 0 ? round($spend / $clicks, 4) : null,
        ];
    }

    /**
     * Whale conversions from the stats row for that day. Campaign-daily wins when it has the column.
     * Otherwise the monthly ad stats value is used.
     *
     * @param  array<string, mixed>|null  $campaign
     * @param  array<string, mixed>|null  $adDaily
     */
    private function conversionValue(?array $campaign, ?array $adDaily): ?float
    {
        foreach ([$campaign, $adDaily] as $row) {
            if (is_array($row) && array_key_exists('conversions', $row) && $row['conversions'] !== null) {
                return (float) $row['conversions'];
            }
        }

        return null;
    }

    private function hasDeliveryRows(string $dataset, string $platform, string $campaignId, string $from, string $to): bool
    {
        $rows = $this->rowsByDate($dataset, $platform, $campaignId, $from, $to, 1);

        return $rows !== null && $rows !== [];
    }

    /**
     * @return array<string, array<string, mixed>>|null
     */
    private function rowsByDate(string $dataset, string $platform, string $campaignId, string $from, string $to, int $limit): ?array
    {
        $result = $this->query->run([
            'dataset' => $dataset,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'group_by' => 'stat_date',
            'limit' => $limit,
        ]);

        if (($result['ok'] ?? false) !== true) {
            return null;
        }

        $byDate = [];

        foreach ($result['rows'] ?? [] as $row) {
            if (! is_array($row)) {
                continue;
            }

            $date = (string) ($row['stat_date'] ?? '');

            if ($date === '') {
                continue;
            }

            try {
                $date = Carbon::parse($date)->toDateString();
            } catch (Throwable) {
                continue;
            }

            $byDate[$date] = $row;
        }

        return $byDate;
    }

    /**
     * @return array<string, mixed>|null
     */
    private function summed(string $dataset, string $platform, string $campaignId, string $from, string $to): ?array
    {
        $result = $this->query->run([
            'dataset' => $dataset,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'limit' => 1,
        ]);

        if (($result['ok'] ?? false) !== true) {
            return null;
        }

        $row = $result['rows'][0] ?? null;

        return is_array($row) ? $row : [];
    }

    /**
     * ROI totals for the window even when the campaign also has affiliate rows.
     *
     * @return array<string, int|float|null>
     */
    private function roi(string $platform, string $campaignId, string $from, string $to): array
    {
        $empty = [
            'conversions' => null,
            'subscriptions' => null,
            'cancellations' => null,
            'installs' => null,
            'bookings' => null,
            'leads' => null,
            'estimated_revenue' => null,
            'orders' => null,
            'sales' => null,
        ];

        if (! Schema::connection('whale')->hasTable('roi_dashboard_campaign_stats')) {
            return $empty;
        }

        $row = DB::connection('whale')
            ->table('roi_dashboard_campaign_stats')
            ->where('campaign_id', $campaignId)
            ->whereRaw('LOWER(platform) = ?', [strtolower($platform)])
            ->whereBetween('date', [$from, $to])
            ->selectRaw('COALESCE(SUM(conversions), 0) as conversions')
            ->selectRaw('COALESCE(SUM(subscriptions), 0) as subscriptions')
            ->selectRaw('COALESCE(SUM(cancellations), 0) as cancellations')
            ->selectRaw('COALESCE(SUM(installs), 0) as installs')
            ->selectRaw('COALESCE(SUM(bookings), 0) as bookings')
            ->selectRaw('COALESCE(SUM(leads), 0) as leads')
            ->selectRaw('COALESCE(SUM(estimated_revenue), 0) as estimated_revenue')
            ->selectRaw('COALESCE(SUM(arb_orders), 0) as orders')
            ->selectRaw('COALESCE(SUM(arb_sales_amount), 0) as sales')
            ->first();

        return [
            'conversions' => round((float) ($row->conversions ?? 0), 4),
            'subscriptions' => round((float) ($row->subscriptions ?? 0), 4),
            'cancellations' => round((float) ($row->cancellations ?? 0), 4),
            'installs' => round((float) ($row->installs ?? 0), 4),
            'bookings' => round((float) ($row->bookings ?? 0), 4),
            'leads' => round((float) ($row->leads ?? 0), 4),
            'estimated_revenue' => round((float) ($row->estimated_revenue ?? 0), 4),
            'orders' => round((float) ($row->orders ?? 0), 4),
            'sales' => round((float) ($row->sales ?? 0), 4),
        ];
    }

    /**
     * @param  array<string, mixed>|null  $row
     */
    private function metric(?array $row, string $key, bool $zeroWhenEmpty): int|float|null
    {
        if ($row === null) {
            return null;
        }

        if (! array_key_exists($key, $row)) {
            return $zeroWhenEmpty ? 0 : null;
        }

        $value = $row[$key];

        if ($value === null) {
            return $zeroWhenEmpty ? 0 : null;
        }

        return is_int($value) ? $value : (float) $value;
    }

    private function campaignName(string $platform, string $campaignId): ?string
    {
        $row = $this->summed('campaigns', $platform, $campaignId, '2000-01-01', '2100-01-01');

        if ($row === null) {
            return null;
        }

        $name = $row['name'] ?? $row['campaign_name'] ?? null;

        return is_string($name) && $name !== '' ? $name : null;
    }

    /**
     * @param  array<string, int|float|null>  $current
     * @param  array<string, int|float|null>  $previous
     * @return list<array{metric: string, key: string, current: int|float|null, previous: int|float|null, change: int|float|null, change_percent: float|null}>
     */
    private function rows(array $current, array $previous): array
    {
        $rows = [];

        foreach (self::LABELS as $key => $label) {
            $left = $current[$key] ?? null;
            $right = $previous[$key] ?? null;
            $change = null;
            $percent = null;

            if (is_int($left) || is_float($left)) {
                if (is_int($right) || is_float($right)) {
                    $change = round($left - $right, 4);
                    $percent = (float) $right !== 0.0 ? round((($left - $right) / abs((float) $right)) * 100, 2) : null;
                }
            }

            $rows[] = [
                'metric' => $label,
                'key' => $key,
                'current' => $left,
                'previous' => $right,
                'change' => $change,
                'change_percent' => $percent,
            ];
        }

        return $rows;
    }

    /**
     * @param  array<string, int|float|null>  $current
     * @param  array<string, int|float|null>  $previous
     * @return array{winner: string, current_ahead: list<array{key: string, label: string, current: int|float, previous: int|float}>, previous_ahead: list<array{key: string, label: string, current: int|float, previous: int|float}>}
     */
    private function outcome(array $current, array $previous): array
    {
        $currentAhead = [];
        $previousAhead = [];

        foreach (self::RESULT_KEYS as $key) {
            $left = $current[$key] ?? null;
            $right = $previous[$key] ?? null;

            if (! is_int($left) && ! is_float($left)) {
                continue;
            }

            if (! is_int($right) && ! is_float($right)) {
                continue;
            }

            if ((float) $left === (float) $right) {
                continue;
            }

            $item = [
                'key' => $key,
                'label' => self::LABELS[$key],
                'current' => $left,
                'previous' => $right,
            ];

            if ((float) $left > (float) $right) {
                $currentAhead[] = $item;
            } else {
                $previousAhead[] = $item;
            }
        }

        $winner = 'tie';

        if (count($currentAhead) > count($previousAhead)) {
            $winner = 'current';
        } elseif (count($previousAhead) > count($currentAhead)) {
            $winner = 'previous';
        }

        return [
            'winner' => $winner,
            'current_ahead' => $currentAhead,
            'previous_ahead' => $previousAhead,
        ];
    }

    /**
     * @param  array{from: string, to: string, metrics: array<string, int|float|null>}  $current
     * @param  array{from: string, to: string, metrics: array<string, int|float|null>}  $previous
     * @param  array{winner: string, current_ahead: list<array{key: string, label: string, current: int|float, previous: int|float}>, previous_ahead: list<array{key: string, label: string, current: int|float, previous: int|float}>}  $outcome
     * @return list<array{action: string, why: string}>
     */
    private function recommendations(array $current, array $previous, array $outcome): array
    {
        $currentResults = $this->resultTotal($current['metrics']);
        $previousResults = $this->resultTotal($previous['metrics']);
        $spend = $current['metrics']['spend'] ?? null;
        $why = $this->why($current, $previous, $outcome);

        if ((is_int($spend) || is_float($spend)) && (float) $spend > 0 && $currentResults === 0.0 && $previousResults > 0) {
            return [[
                'action' => 'Do not scale. The recent window is the worse window.',
                'why' => 'Current spend is '.$this->quote('spend', $spend).' and its sales, orders, conversions, subscriptions, installs, bookings, and leads are 0. '.$why,
            ]];
        }

        if ($outcome['winner'] === 'current') {
            return [[
                'action' => 'Keep the current window. It is the better window.',
                'why' => $why,
            ]];
        }

        if ($outcome['winner'] === 'previous') {
            return [[
                'action' => 'Do not increase the budget. The earlier window is the better window.',
                'why' => $why,
            ]];
        }

        return [[
            'action' => 'Make no change from this comparison.',
            'why' => $why,
        ]];
    }

    /**
     * @param  array<string, int|float|null>  $metrics
     */
    private function resultTotal(array $metrics): float
    {
        $total = 0.0;

        foreach (self::RESULT_KEYS as $key) {
            $value = $metrics[$key] ?? null;

            if (is_int($value) || is_float($value)) {
                $total += (float) $value;
            }
        }

        return $total;
    }

    /**
     * @param  array{from: string, to: string}  $current
     * @param  array{from: string, to: string}  $previous
     * @param  array{winner: string, current_ahead: list<array{key: string, label: string, current: int|float, previous: int|float}>, previous_ahead: list<array{key: string, label: string, current: int|float, previous: int|float}>}  $outcome
     */
    private function why(array $current, array $previous, array $outcome): string
    {
        $currentLabel = 'The current window ('.$current['from'].' to '.$current['to'].')';
        $previousLabel = 'The earlier window ('.$previous['from'].' to '.$previous['to'].')';
        $parts = [];

        if ($outcome['current_ahead'] !== []) {
            $parts[] = $currentLabel.' is ahead on '.$this->aheadList($outcome['current_ahead'], 'current').'.';
        }

        if ($outcome['previous_ahead'] !== []) {
            $parts[] = $previousLabel.' is ahead on '.$this->aheadList($outcome['previous_ahead'], 'previous').'.';
        }

        if ($parts === []) {
            return 'Neither window is ahead on sales, orders, conversions, subscriptions, installs, bookings, or leads.';
        }

        if ($outcome['winner'] === 'current') {
            $parts[] = $currentLabel.' is the better window because it leads on more of those result metrics.';
        } elseif ($outcome['winner'] === 'previous') {
            $parts[] = $previousLabel.' is the better window because it leads on more of those result metrics. '.$currentLabel.' is the worse window.';
        } else {
            $parts[] = 'Neither window is ahead on more result metrics, so neither is the better window.';
        }

        return implode(' ', $parts);
    }

    /**
     * @param  list<array{key: string, label: string, current: int|float, previous: int|float}>  $items
     */
    private function aheadList(array $items, string $side): string
    {
        $parts = [];

        foreach ($items as $item) {
            $winner = $side === 'current' ? $item['current'] : $item['previous'];
            $other = $side === 'current' ? $item['previous'] : $item['current'];
            $parts[] = $item['label'].' ('.$this->quote($item['key'], $winner).' vs '.$this->quote($item['key'], $other).')';
        }

        return implode(', ', $parts);
    }

    private function quote(string $key, int|float|null $value): string
    {
        if ($value === null) {
            return '—';
        }

        if (in_array($key, self::MONEY_KEYS, true)) {
            return '$'.number_format((float) $value, 2, '.', '');
        }

        if (floor((float) $value) == (float) $value) {
            return (string) (int) $value;
        }

        return rtrim(rtrim(number_format((float) $value, 4, '.', ''), '0'), '.');
    }

    private function note(string $currentFrom, string $currentTo, string $previousFrom, string $previousTo): string
    {
        return 'Print the campaign name in bold. Do not use a markdown heading. Do not print the 30-day campaign stats table and do not call suggest_campaign for this question. '
            .'Print one markdown table with columns Metric, Current ('.$currentFrom.' to '.$currentTo.'), Previous ('.$previousFrom.' to '.$previousTo.'), and Change. '
            .'Print every returned rows item, including zeros. When a value is null, print a dash. '
            .'Then say which window is better and which is worse. Name each metric in outcome.current_ahead and outcome.previous_ahead, and quote its current and previous values. '
            .'Spend, impressions, reach, clicks, CTR, CPC, cancellations, and estimated revenue stay in the table and do not decide the winner. '
            .'Affiliate sales and ROI sales stay in separate rows. '
            .'Print each recommendations item with its action and why, quoting the numbers in why. '
            .'Do not change the health label or the verdict. Do not invent a page rewrite, page speed, profit, remaining budget, or a winning creative.';
    }
}
