<?php

namespace App\Campaigns;

use App\Services\Meta\GraphApi;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * One diagnosis per ad set from Whale.
 *
 * A missing metric stays null. A stored zero stays zero. Fields whose columns
 * are not on the Whale tables yet are named in unavailable.
 */
class AdSetOptimizationAssembler
{
    public function __construct(
        private readonly WhaleAdopsTables $tables,
        private readonly GraphApi $graph,
    ) {}

    /**
     * @return array{
     *     from: string,
     *     to: string,
     *     unavailable: list<string>,
     *     stats_available: bool,
     *     breakdowns_available: bool,
     *     targeting_available: bool,
     *     delivery_issues_available: bool,
     *     ad_sets: list<array<string, mixed>>
     * }
     */
    public function forCampaign(string $platform, string $campaignId, ?string $from = null, ?string $to = null): array
    {
        $platform = strtolower(trim($platform));
        $campaignId = trim($campaignId);
        $to = $this->day($to, now()->toDateString());
        $from = $this->day($from, Carbon::parse($to)->subDays(6)->toDateString());
        $statsTables = $this->tables->tablesFor('stats_daily', $from, $to);
        $breakdownTables = $this->tables->tablesFor('stats_breakdown_daily', $from, $to);
        $conversionTables = $this->tables->tablesFor('conversions_daily', $from, $to);
        $stored = $this->adSets($platform, $campaignId);
        $ids = array_keys($stored);

        $targeting = $this->targeting($platform, $ids);
        $delivery = $this->delivery($platform, $ids, $from, $to, $statsTables);
        $landingPageViews = $this->landingPageViews($platform, $ids, $from, $to, $conversionTables);
        $frequency = $this->frequency($platform, $ids, $to);
        $issues = $this->issues($platform, $ids);
        $breakdowns = $this->breakdowns($platform, $ids, $from, $to, $breakdownTables);

        $adSets = [];

        foreach ($stored as $id => $row) {
            $adSets[] = $this->present(
                $id,
                $row['record'],
                $row['edit'],
                $targeting[$id] ?? null,
                $delivery[$id] ?? null,
                $landingPageViews[$id] ?? null,
                $frequency[$id] ?? null,
                $issues[$id] ?? [],
                $this->withMetaPublisherPlatforms(
                    $platform,
                    $id,
                    $from,
                    $to,
                    $breakdowns[$id] ?? $this->emptyBreakdowns(),
                ),
            );
        }

        usort($adSets, function (array $left, array $right): int {
            $leftSpend = $left['delivery']['spend'];
            $rightSpend = $right['delivery']['spend'];

            if ($leftSpend === null && $rightSpend !== null) {
                return 1;
            }

            if ($rightSpend === null && $leftSpend !== null) {
                return -1;
            }

            if ($leftSpend !== null && $rightSpend !== null && $leftSpend !== $rightSpend) {
                return $rightSpend <=> $leftSpend;
            }

            return strcmp((string) $left['name'], (string) $right['name']);
        });

        return [
            'from' => $from,
            'to' => $to,
            'unavailable' => $this->unavailable(),
            'stats_available' => $statsTables !== [],
            'breakdowns_available' => $breakdownTables !== [],
            'targeting_available' => $this->tables->name('targeting') !== null,
            'delivery_issues_available' => $this->tables->name('delivery_issues') !== null,
            'ad_sets' => $adSets,
        ];
    }

    /**
     * @param  array<string, mixed>  $record
     * @param  array<string, mixed>  $edit
     * @param  array<string, mixed>|null  $targeting
     * @param  array<string, mixed>|null  $delivery
     * @param  array{reach: ?int, frequency: float}|null  $frequency
     * @param  list<array{issue_type: string, reason: ?string}>  $issues
     * @param  array<string, list<array<string, mixed>>>  $breakdowns
     * @return array<string, mixed>
     */
    private function present(
        string $id,
        array $record,
        array $edit,
        ?array $targeting,
        ?array $delivery,
        ?float $landingPageViews,
        ?array $frequency,
        array $issues,
        array $breakdowns,
    ): array {
        $spend = $delivery['spend'] ?? null;
        $impressions = $delivery['impressions'] ?? null;
        $clicks = $delivery['clicks'] ?? null;
        $outbound = $delivery['outbound_clicks'] ?? null;
        $conversions = $delivery['conversions'] ?? null;
        $conversionValue = $delivery['conversion_value'] ?? null;

        return [
            'ad_set_id' => $id,
            'name' => $record['name'],
            'status' => $record['status'],
            'delivery_issues' => $issues,
            'audience' => $targeting ?? $this->unknownAudience(),
            'optimization_goal' => $record['optimization_goal'],
            'optimization_event' => $record['optimization_event'],
            'billing_event' => $record['billing_event'],
            'attribution' => $record['attribution'],
            'bid' => $record['bid'],
            'delivery' => [
                'spend' => $spend,
                'impressions' => $impressions,
                'clicks' => $clicks,
                'outbound_clicks' => $outbound,
                'cpm' => $this->rate($spend, $impressions, 1000),
                'outbound_ctr' => $this->rate($outbound, $impressions, 1, 4),
                'cpc' => $this->rate($spend, $clicks, 1),
                'landing_page_views' => $landingPageViews,
                'conversions' => $conversions,
                'cpa' => is_float($conversions) && $conversions > 0 ? $this->rate($spend, $conversions, 1) : null,
                'roas' => $this->rate($conversionValue, $spend, 1, 4),
                'conversion_value' => $conversionValue,
                'reach' => $frequency['reach'] ?? null,
                'frequency' => $frequency['frequency'] ?? null,
                'frequency_window' => $frequency === null ? null : '7d',
            ],
            'breakdowns' => $breakdowns,
            'learning_status' => $edit['learning_status'],
            'last_significant_edit_at' => $edit['last_significant_edit_at'],
            'updated_at' => $edit['updated_at'],
            'edit_age_source' => $edit['edit_age_source'],
            'hours_since_edit' => $edit['hours_since_edit'],
        ];
    }

    /**
     * @return array<string, array{record: array<string, mixed>, edit: array<string, mixed>}>
     */
    private function adSets(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('adsets');

        if ($table === null || $campaignId === '') {
            return [];
        }

        $columns = $this->tables->columns($table);
        $idColumn = $this->column($columns, ['adset_id', 'ad_set_id']);
        $campaignColumn = $this->column($columns, ['campaign_id', 'external_campaign_id']);

        if ($idColumn === null || $campaignColumn === null) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)->where($campaignColumn, $campaignId);
            $platformColumn = $this->column($columns, ['platform']);

            if ($platformColumn !== null && $platform !== '') {
                $query->where($platformColumn, $platform);
            }

            $stored = [];

            foreach ($query->get() as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);

                if ($id === null) {
                    continue;
                }

                $stored[$id] = [
                    'record' => $this->record($row, $columns),
                    'edit' => $this->edit($row, $columns),
                ];
            }

            return $stored;
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @param  list<string>  $columns
     * @return array<string, mixed>
     */
    private function record(object $row, array $columns): array
    {
        return [
            'name' => $this->nullableString($this->field($row, $columns, 'name')),
            'status' => $this->nullableString($this->field($row, $columns, 'effective_status'))
                ?? $this->nullableString($this->field($row, $columns, 'status')),
            'optimization_goal' => $this->nullableString($this->field($row, $columns, 'optimization_goal')),
            'optimization_event' => $this->nullableString($this->field($row, $columns, 'optimization_event')),
            'billing_event' => $this->nullableString($this->field($row, $columns, 'billing_event')),
            'attribution' => $this->attribution($this->field($row, $columns, 'attribution_spec')),
            'bid' => [
                'budget_level' => $this->nullableString($this->field($row, $columns, 'budget_level')),
                'daily_budget' => $this->nullableFloat($this->field($row, $columns, 'daily_budget')),
                'lifetime_budget' => $this->nullableFloat($this->field($row, $columns, 'lifetime_budget')),
                'budget_remaining' => $this->nullableFloat($this->field($row, $columns, 'budget_remaining')),
                'bid_strategy' => $this->nullableString($this->field($row, $columns, 'bid_strategy')),
                'bid_amount' => $this->nullableFloat($this->field($row, $columns, 'bid_amount')),
                'target_cpa' => $this->nullableFloat($this->field($row, $columns, 'target_cpa')),
                'target_roas' => $this->nullableFloat($this->field($row, $columns, 'target_roas')),
            ],
        ];
    }

    /**
     * @param  list<string>  $columns
     * @return array{
     *     learning_status: ?string,
     *     last_significant_edit_at: ?string,
     *     updated_at: ?string,
     *     edit_age_source: ?string,
     *     hours_since_edit: ?int
     * }
     */
    private function edit(object $row, array $columns): array
    {
        $payload = $this->decode($this->field($row, $columns, 'raw_payload'));
        $payload = is_array($payload) ? $payload : [];
        $stage = is_array($payload['learning_stage_info'] ?? null) ? $payload['learning_stage_info'] : [];
        $significant = $this->iso($this->field($row, $columns, 'last_significant_edit_at'))
            ?? (is_numeric($stage['last_sig_edit_ts'] ?? null)
                ? Carbon::createFromTimestamp((int) $stage['last_sig_edit_ts'], 'UTC')->toIso8601String()
                : null);
        $updated = $this->iso($payload['updated_time'] ?? null)
            ?? $this->iso($this->field($row, $columns, 'updated_at_platform'));
        $columnStatus = $this->nullableString($this->field($row, $columns, 'learning_status'));
        $payloadStatus = $this->nullableString(is_array($stage) ? ($stage['status'] ?? null) : null);

        return [
            'learning_status' => $columnStatus ?? $payloadStatus,
            'last_significant_edit_at' => $significant,
            'updated_at' => $updated,
            'edit_age_source' => $significant !== null ? 'significant_edit' : ($updated !== null ? 'updated_time' : null),
            'hours_since_edit' => $this->hoursSince($significant ?? $updated),
        ];
    }

    /**
     * @param  list<string>  $ids
     * @return array<string, array<string, mixed>>
     */
    private function targeting(string $platform, array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $table = $this->tables->name('targeting');

        if ($table === null) {
            return [];
        }

        $columns = $this->tables->columns($table);
        $idColumn = $this->column($columns, ['entity_id']);

        if ($idColumn === null) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)->whereIn($idColumn, $ids);
            $levelColumn = $this->column($columns, ['entity_level']);
            $platformColumn = $this->column($columns, ['platform']);

            if ($levelColumn !== null) {
                $query->where($levelColumn, 'adset');
            }

            if ($platformColumn !== null && $platform !== '') {
                $query->where($platformColumn, $platform);
            }

            $byId = [];

            foreach ($query->get() as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);

                if ($id === null || isset($byId[$id])) {
                    continue;
                }

                $byId[$id] = $this->audience($row, $columns);
            }

            return $byId;
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @param  list<string>  $columns
     * @return array<string, mixed>
     */
    private function audience(object $row, array $columns): array
    {
        $included = $this->audienceList($this->field($row, $columns, 'audiences_included'));
        $interests = $this->interestNames($this->field($row, $columns, 'interests'));
        $raw = $this->decode($this->field($row, $columns, 'raw'));
        $automation = is_array($raw) && is_array($raw['targeting_automation'] ?? null) ? $raw['targeting_automation'] : [];
        $storedAdvantage = $this->field($row, $columns, 'advantage_audience');
        $overlap = $this->decode($this->field($row, $columns, 'audience_overlap'));

        return [
            'type' => $this->audienceType($included, $interests),
            'advantage_audience' => $storedAdvantage !== null && $storedAdvantage !== ''
                ? ((int) $storedAdvantage) === 1
                : (is_numeric($automation['advantage_audience'] ?? null) ? ((int) $automation['advantage_audience']) === 1 : null),
            'audience_size_lower' => $this->nullableInt($this->field($row, $columns, 'audience_size_lower')),
            'audience_size_upper' => $this->nullableInt($this->field($row, $columns, 'audience_size_upper')),
            'audience_overlap' => is_array($overlap) ? $overlap : null,
            'countries' => $this->stringList($this->field($row, $columns, 'countries')),
            'country_source' => 'setup',
            'age_min' => $this->nullableInt($this->field($row, $columns, 'age_min')),
            'age_max' => $this->nullableInt($this->field($row, $columns, 'age_max')),
            'genders' => $this->stringList($this->field($row, $columns, 'genders')),
            'interests' => $interests,
            'included_audiences' => $included,
            'placement_labels' => $this->placementLabels($this->field($row, $columns, 'placements')),
            'devices' => $this->deviceSetup($this->field($row, $columns, 'devices')),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function unknownAudience(): array
    {
        return [
            'type' => null,
            'advantage_audience' => null,
            'audience_size_lower' => null,
            'audience_size_upper' => null,
            'audience_overlap' => null,
            'countries' => null,
            'country_source' => 'setup',
            'age_min' => null,
            'age_max' => null,
            'genders' => null,
            'interests' => [],
            'included_audiences' => [],
            'placement_labels' => [],
            'devices' => null,
        ];
    }

    /**
     * Lookalike and retargeting subtypes win over the audience name. The lookalike
     * flag on targeting relaxation is not an audience, so it does not count.
     *
     * @param  list<array{id: ?string, name: ?string, subtype: ?string}>  $included
     * @param  list<string>  $interests
     */
    private function audienceType(array $included, array $interests): string
    {
        foreach ($included as $audience) {
            if (strtoupper((string) ($audience['subtype'] ?? '')) === 'LOOKALIKE') {
                return 'lookalike';
            }
        }

        foreach ($included as $audience) {
            if (str_contains(strtolower((string) $audience['name']), 'lookalike')) {
                return 'lookalike';
            }
        }

        foreach ($included as $audience) {
            if (in_array(strtoupper((string) ($audience['subtype'] ?? '')), ['WEBSITE', 'ENGAGEMENT', 'APP', 'IG_BUSINESS', 'VIDEO', 'OFFLINE_CONVERSION'], true)) {
                return 'retargeting';
            }
        }

        foreach ($included as $audience) {
            $name = strtolower((string) $audience['name']);

            if (str_contains($name, 'retarget') || str_contains($name, 'remarket')) {
                return 'retargeting';
            }
        }

        if ($included !== []) {
            return 'custom';
        }

        if ($interests !== []) {
            return 'interest';
        }

        return 'broad';
    }

    /**
     * @param  list<string>  $ids
     * @param  list<string>  $tables
     * @return array<string, array<string, mixed>>
     */
    private function delivery(string $platform, array $ids, string $from, string $to, array $tables): array
    {
        $totals = [];

        foreach ($tables as $table) {
            $columns = $this->tables->columns($table);
            $idColumn = $this->column($columns, ['adset_id', 'ad_set_id']);
            $dateColumn = $this->column($columns, ['stat_date', 'date']);

            if ($idColumn === null || $dateColumn === null) {
                continue;
            }

            $spendColumn = $this->column($columns, ['spend', 'cost']);
            $impressionColumn = $this->column($columns, ['impressions']);
            $clickColumn = $this->column($columns, ['clicks']);
            $outboundColumn = $this->column($columns, ['outbound_clicks']);
            $conversionColumn = $this->column($columns, ['conversions']);
            $valueColumn = $this->column($columns, ['conversion_value']);

            foreach ($this->rows($table, $columns, $platform, $idColumn, $ids, $dateColumn, $from, $to) as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);

                if ($id === null) {
                    continue;
                }

                $current = $totals[$id] ?? [
                    'spend' => null,
                    'impressions' => null,
                    'clicks' => null,
                    'outbound_clicks' => null,
                    'conversions' => null,
                    'conversion_value' => null,
                ];
                $totals[$id] = [
                    'spend' => $this->addFloat($current['spend'], $spendColumn === null ? null : ($row->{$spendColumn} ?? null)),
                    'impressions' => $this->addInt($current['impressions'], $impressionColumn === null ? null : ($row->{$impressionColumn} ?? null)),
                    'clicks' => $this->addInt($current['clicks'], $clickColumn === null ? null : ($row->{$clickColumn} ?? null)),
                    'outbound_clicks' => $this->addInt($current['outbound_clicks'], $outboundColumn === null ? null : ($row->{$outboundColumn} ?? null)),
                    'conversions' => $this->addFloat($current['conversions'], $conversionColumn === null ? null : ($row->{$conversionColumn} ?? null)),
                    'conversion_value' => $this->addFloat($current['conversion_value'], $valueColumn === null ? null : ($row->{$valueColumn} ?? null)),
                ];
            }
        }

        foreach ($totals as $id => $total) {
            $totals[$id]['spend'] = $total['spend'] === null ? null : round($total['spend'], 2);
            $totals[$id]['conversion_value'] = $total['conversion_value'] === null ? null : round($total['conversion_value'], 2);
            $totals[$id]['conversions'] = $total['conversions'] === null ? null : round($total['conversions'], 2);
        }

        return $totals;
    }

    /**
     * Omni landing-page views already include landing-page views. Summing both
     * would count the same visit twice.
     *
     * @param  list<string>  $ids
     * @param  list<string>  $tables
     * @return array<string, float>
     */
    private function landingPageViews(string $platform, array $ids, string $from, string $to, array $tables): array
    {
        $totals = [];

        foreach ($tables as $table) {
            $columns = $this->tables->columns($table);
            $idColumn = $this->column($columns, ['adset_id', 'ad_set_id']);
            $dateColumn = $this->column($columns, ['stat_date', 'date']);
            $actionColumn = $this->column($columns, ['action_name']);
            $conversionColumn = $this->column($columns, ['conversions']);

            if ($idColumn === null || $dateColumn === null || $actionColumn === null || $conversionColumn === null) {
                continue;
            }

            foreach ($this->rows($table, $columns, $platform, $idColumn, $ids, $dateColumn, $from, $to) as $row) {
                $action = strtolower(trim((string) ($row->{$actionColumn} ?? '')));
                $kind = match ($action) {
                    'omni_landing_page_view' => 'omni',
                    'landing_page_view' => 'landing',
                    default => null,
                };

                if ($kind === null) {
                    continue;
                }

                $id = $this->nullableString($row->{$idColumn} ?? null);
                $count = $this->nullableFloat($row->{$conversionColumn} ?? null);

                if ($id === null || $count === null) {
                    continue;
                }

                $totals[$id][$kind] = ($totals[$id][$kind] ?? 0) + $count;
            }
        }

        $views = [];

        foreach ($totals as $id => $kinds) {
            $views[$id] = round((float) ($kinds['omni'] ?? $kinds['landing']), 2);
        }

        return $views;
    }

    /**
     * Frequency is the 7-day reach window. Adding daily frequency is not a
     * 7-day frequency.
     *
     * @param  list<string>  $ids
     * @return array<string, array{reach: ?int, frequency: float}>
     */
    private function frequency(string $platform, array $ids, string $to): array
    {
        if ($ids === []) {
            return [];
        }

        $table = $this->tables->name('reach_windows');

        if ($table === null) {
            return [];
        }

        $columns = $this->tables->columns($table);
        $idColumn = $this->column($columns, ['entity_id']);
        $dateColumn = $this->column($columns, ['as_of_date']);
        $windowColumn = $this->column($columns, ['window_key']);
        $frequencyColumn = $this->column($columns, ['frequency']);
        $reachColumn = $this->column($columns, ['reach']);

        if ($idColumn === null || $dateColumn === null || $windowColumn === null || $frequencyColumn === null) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)
                ->whereIn($idColumn, $ids)
                ->where($windowColumn, '7d')
                ->where($dateColumn, '<=', $to);
            $levelColumn = $this->column($columns, ['entity_level']);
            $platformColumn = $this->column($columns, ['platform']);

            if ($levelColumn !== null) {
                $query->where($levelColumn, 'adset');
            }

            if ($platformColumn !== null && $platform !== '') {
                $query->where($platformColumn, $platform);
            }

            $chosen = [];

            foreach ($query->orderBy($dateColumn)->get() as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);
                $frequency = $this->nullableFloat($row->{$frequencyColumn} ?? null);

                if ($id === null || $frequency === null) {
                    continue;
                }

                $chosen[$id] = [
                    'reach' => $reachColumn === null ? null : $this->nullableInt($row->{$reachColumn} ?? null),
                    'frequency' => round($frequency, 4),
                ];
            }

            return $chosen;
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @param  list<string>  $ids
     * @return array<string, list<array{issue_type: string, reason: ?string}>>
     */
    private function issues(string $platform, array $ids): array
    {
        if ($ids === []) {
            return [];
        }

        $table = $this->tables->name('delivery_issues');

        if ($table === null) {
            return [];
        }

        $columns = $this->tables->columns($table);
        $idColumn = $this->column($columns, ['entity_id']);
        $typeColumn = $this->column($columns, ['issue_type']);

        if ($idColumn === null || $typeColumn === null) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)->whereIn($idColumn, $ids);
            $levelColumn = $this->column($columns, ['entity_level']);
            $platformColumn = $this->column($columns, ['platform']);
            $resolvedColumn = $this->column($columns, ['resolved_at']);
            $reasonColumn = $this->column($columns, ['reason']);

            if ($levelColumn !== null) {
                $query->where($levelColumn, 'adset');
            }

            if ($platformColumn !== null && $platform !== '') {
                $query->where($platformColumn, $platform);
            }

            if ($resolvedColumn !== null) {
                $query->whereNull($resolvedColumn);
            }

            $byId = [];

            foreach ($query->get() as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);
                $type = $this->nullableString($row->{$typeColumn} ?? null);

                if ($id === null || $type === null) {
                    continue;
                }

                $byId[$id][] = [
                    'issue_type' => $type,
                    'reason' => $reasonColumn === null ? null : $this->nullableString($row->{$reasonColumn} ?? null),
                ];
            }

            return $byId;
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @param  list<string>  $ids
     * @param  list<string>  $tables
     * @return array<string, array<string, list<array<string, mixed>>>>
     */
    private function breakdowns(string $platform, array $ids, string $from, string $to, array $tables): array
    {
        $totals = [];

        foreach ($tables as $table) {
            $columns = $this->tables->columns($table);
            $idColumn = $this->column($columns, ['adset_id', 'ad_set_id']);
            $dateColumn = $this->column($columns, ['stat_date', 'date']);
            $dimensionColumn = $this->column($columns, ['dimension']);
            $firstColumn = $this->column($columns, ['value_1']);
            $secondColumn = $this->column($columns, ['value_2']);

            if ($idColumn === null || $dateColumn === null || $dimensionColumn === null || $firstColumn === null) {
                continue;
            }

            $spendColumn = $this->column($columns, ['spend', 'cost']);
            $impressionColumn = $this->column($columns, ['impressions']);
            $clickColumn = $this->column($columns, ['clicks']);
            $conversionColumn = $this->column($columns, ['conversions']);

            foreach ($this->rows($table, $columns, $platform, $idColumn, $ids, $dateColumn, $from, $to) as $row) {
                $id = $this->nullableString($row->{$idColumn} ?? null);
                $dimension = $this->nullableString($row->{$dimensionColumn} ?? null);

                if ($id === null || $dimension === null) {
                    continue;
                }

                $metrics = [
                    'spend' => $spendColumn === null ? null : $this->nullableFloat($row->{$spendColumn} ?? null),
                    'impressions' => $impressionColumn === null ? null : $this->nullableInt($row->{$impressionColumn} ?? null),
                    'clicks' => $clickColumn === null ? null : $this->nullableInt($row->{$clickColumn} ?? null),
                    'conversions' => $conversionColumn === null ? null : $this->nullableFloat($row->{$conversionColumn} ?? null),
                ];
                $first = trim((string) ($row->{$firstColumn} ?? ''));
                $second = $secondColumn === null ? '' : trim((string) ($row->{$secondColumn} ?? ''));
                $key = $dimension.'|'.$first.'|'.$second;
                $current = $totals[$id][$key] ?? null;
                $totals[$id][$key] = [
                    'dimension' => $dimension,
                    'value_1' => $first,
                    'value_2' => $second,
                    'spend' => $this->addFloat($current['spend'] ?? null, $metrics['spend']),
                    'impressions' => $this->addInt($current['impressions'] ?? null, $metrics['impressions']),
                    'clicks' => $this->addInt($current['clicks'] ?? null, $metrics['clicks']),
                    'conversions' => $this->addFloat($current['conversions'] ?? null, $metrics['conversions']),
                ];
            }
        }

        $byId = [];

        foreach ($totals as $id => $slices) {
            $byId[$id] = $this->emptyBreakdowns();

            foreach ($slices as $slice) {
                $placed = $this->placeBreakdown($slice);

                if ($placed === null) {
                    continue;
                }

                $byId[$id][$placed['bucket']][] = $placed['row'];
            }

            foreach ($byId[$id] as $bucket => $rows) {
                usort($rows, fn (array $left, array $right): int => ($right['spend'] ?? 0) <=> ($left['spend'] ?? 0));
                $byId[$id][$bucket] = $rows;
            }
        }

        return $byId;
    }

    /**
     * @param  array<string, mixed>  $slice
     * @return array{bucket: string, row: array<string, mixed>}|null
     */
    private function placeBreakdown(array $slice): ?array
    {
        $spend = $slice['spend'] === null ? null : round((float) $slice['spend'], 2);
        $conversions = $slice['conversions'] === null ? null : round((float) $slice['conversions'], 2);
        $metrics = [
            'spend' => $spend,
            'impressions' => $slice['impressions'],
            'clicks' => $slice['clicks'],
            'conversions' => $conversions,
        ];
        $first = (string) $slice['value_1'];
        $second = (string) $slice['value_2'];

        if ($slice['dimension'] === 'placement') {
            return [
                'bucket' => 'placements',
                'row' => [
                    'label' => $this->placementLabel($first, $second),
                    'publisher' => strtolower($first),
                    'position' => strtolower($second),
                    ...$metrics,
                    'cost_per_result' => ($spend !== null && $conversions !== null && $conversions > 0)
                        ? round($spend / $conversions, 2)
                        : null,
                ],
            ];
        }

        if ($slice['dimension'] === 'device') {
            $device = strtolower($first);

            return [
                'bucket' => 'devices',
                'row' => [
                    'device' => $device,
                    'group' => $this->deviceGroup($device),
                    ...$metrics,
                ],
            ];
        }

        if ($slice['dimension'] === 'region') {
            if ($first === '') {
                return null;
            }

            return [
                'bucket' => 'regions',
                'row' => [
                    'region' => $first,
                    ...$metrics,
                ],
            ];
        }

        if ($slice['dimension'] === 'country') {
            $country = strtoupper(trim($first));

            if ($country === '') {
                return null;
            }

            return [
                'bucket' => 'countries',
                'row' => [
                    'country' => $country,
                    ...$metrics,
                ],
            ];
        }

        if ($slice['dimension'] !== 'age_gender') {
            return null;
        }

        $left = $this->demographic($first);
        $right = $this->demographic($second);
        $age = $left['age'] ?? $right['age'];
        $gender = $left['gender'] ?? $right['gender'];

        if ($age !== null && $gender !== null) {
            return ['bucket' => 'age_gender', 'row' => ['age' => $age, 'gender' => $gender, ...$metrics]];
        }

        if ($age !== null) {
            return ['bucket' => 'ages', 'row' => ['age' => $age, ...$metrics]];
        }

        if ($gender !== null) {
            return ['bucket' => 'genders', 'row' => ['gender' => $gender, ...$metrics]];
        }

        return null;
    }

    /**
     * @return array{age: ?string, gender: ?string}
     */
    private function demographic(string $value): array
    {
        $trimmed = trim($value);

        if ($trimmed === '') {
            return ['age' => null, 'gender' => null];
        }

        $upper = strtoupper($trimmed);

        if (in_array($upper, ['MALE', 'FEMALE', 'UNDETERMINED', 'UNKNOWN'], true)) {
            return [
                'age' => null,
                'gender' => in_array($upper, ['UNDETERMINED', 'UNKNOWN'], true) ? 'unknown' : strtolower($trimmed),
            ];
        }

        if ($upper === 'AGE_RANGE_UNDETERMINED') {
            return ['age' => 'unknown', 'gender' => null];
        }

        if (preg_match('/^AGE_RANGE_(\d+)_(\d+)$/', $upper, $matches) === 1) {
            return ['age' => $matches[1].'-'.$matches[2], 'gender' => null];
        }

        if (preg_match('/^AGE_RANGE_(\d+)_UP$/', $upper, $matches) === 1) {
            return ['age' => $matches[1].'+', 'gender' => null];
        }

        return ['age' => $trimmed, 'gender' => null];
    }

    /**
     * Whale placement rows do not store landing page views. Ads Manager
     * Breakdown → Platform does, via Graph insights.
     *
     * @param  array<string, list<array<string, mixed>>>  $breakdowns
     * @return array<string, list<array<string, mixed>>>
     */
    private function withMetaPublisherPlatforms(
        string $platform,
        string $adSetId,
        string $from,
        string $to,
        array $breakdowns,
    ): array {
        if ($platform !== 'meta' || ! $this->needsMetaPublisherResults($breakdowns)) {
            return $breakdowns;
        }

        try {
            $rows = $this->graph->publisherPlatformInsights($adSetId, $from, $to);
        } catch (Throwable) {
            return $breakdowns;
        }

        $platforms = [];

        foreach ($rows as $row) {
            $publisher = strtolower(trim((string) ($row['publisher'] ?? '')));
            $lpv = (float) ($row['landing_page_views'] ?? 0);

            if ($publisher === '' || $lpv <= 0) {
                continue;
            }

            $platforms[] = [
                'label' => match ($publisher) {
                    'facebook' => 'Facebook',
                    'instagram' => 'Instagram',
                    'audience_network' => 'Audience Network',
                    'messenger' => 'Messenger',
                    'threads' => 'Threads',
                    default => ucfirst($publisher),
                },
                'publisher' => $publisher,
                'spend' => $row['spend'],
                'impressions' => $row['impressions'],
                'clicks' => $row['clicks'],
                'landing_page_views' => $lpv,
                'conversions' => $lpv,
                'cost_per_result' => $row['cost_per_result'],
            ];
        }

        if ($platforms !== []) {
            $breakdowns['publisher_platforms'] = $platforms;
        }

        return $breakdowns;
    }

    /**
     * @param  array<string, list<array<string, mixed>>>  $breakdowns
     */
    private function needsMetaPublisherResults(array $breakdowns): bool
    {
        $rows = is_array($breakdowns['placements'] ?? null) ? $breakdowns['placements'] : [];
        $publishers = [];
        $results = 0.0;

        foreach ($rows as $row) {
            if (! is_array($row)) {
                continue;
            }

            $publisher = strtolower(trim((string) ($row['publisher'] ?? '')));

            if ($publisher !== '') {
                $publishers[$publisher] = true;
            }

            $results += (float) ($row['landing_page_views'] ?? 0) + (float) ($row['conversions'] ?? 0);
        }

        return $results <= 0 && count($publishers) >= 2;
    }

    /**
     * @return array<string, list<array<string, mixed>>>
     */
    private function emptyBreakdowns(): array
    {
        return [
            'placements' => [],
            'publisher_platforms' => [],
            'devices' => [],
            'ages' => [],
            'genders' => [],
            'age_gender' => [],
            'regions' => [],
            'countries' => [],
        ];
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $ids
     * @return list<object>
     */
    private function rows(
        string $table,
        array $columns,
        string $platform,
        string $idColumn,
        array $ids,
        string $dateColumn,
        string $from,
        string $to,
    ): array {
        if ($ids === []) {
            return [];
        }

        try {
            $query = DB::connection('whale')->table($table)
                ->whereIn($idColumn, $ids)
                ->whereBetween($dateColumn, [$from, $to]);
            $platformColumn = $this->column($columns, ['platform']);

            if ($platformColumn !== null && $platform !== '') {
                $query->where($platformColumn, $platform);
            }

            return $query->get()->all();
        } catch (Throwable) {
            return [];
        }
    }

    /**
     * @return list<array{event_type: string, window_days: int}>|null
     */
    private function attribution(mixed $value): ?array
    {
        $decoded = $this->decode($value);

        if (! is_array($decoded)) {
            return null;
        }

        $windows = [];

        foreach ($decoded as $window) {
            if (! is_array($window)) {
                continue;
            }

            $event = $this->nullableString($window['event_type'] ?? null);
            $days = $this->nullableInt($window['window_days'] ?? null);

            if ($event === null || $days === null) {
                continue;
            }

            $windows[] = ['event_type' => $event, 'window_days' => $days];
        }

        return $windows === [] ? null : $windows;
    }

    /**
     * @return list<string>
     */
    private function unavailable(): array
    {
        $adsetTable = $this->tables->name('adsets');
        $targetingTable = $this->tables->name('targeting');
        $adsetColumns = $adsetTable === null ? [] : $this->tables->columns($adsetTable);
        $targetingColumns = $targetingTable === null ? [] : $this->tables->columns($targetingTable);
        $missing = [];

        if (! in_array('audience_size_lower', $targetingColumns, true)) {
            $missing[] = 'audience_size';
        }

        if (! in_array('audience_overlap', $targetingColumns, true)) {
            $missing[] = 'audience_overlap';
        }

        if (! in_array('optimization_event', $adsetColumns, true)) {
            $missing[] = 'optimization_event';
        }

        return $missing;
    }

    /**
     * @return list<array{id: ?string, name: ?string, subtype: ?string}>
     */
    private function audienceList(mixed $value): array
    {
        $decoded = $this->decode($value);

        if (! is_array($decoded)) {
            return [];
        }

        $audiences = [];

        foreach ($decoded as $item) {
            if (! is_array($item)) {
                continue;
            }

            $id = $this->nullableString($item['id'] ?? null);
            $name = $this->nullableString($item['name'] ?? null);

            if ($id === null && $name === null) {
                continue;
            }

            $audiences[] = [
                'id' => $id,
                'name' => $name,
                'subtype' => $this->nullableString($item['subtype'] ?? null),
            ];
        }

        return $audiences;
    }

    /**
     * @return list<string>
     */
    private function interestNames(mixed $value): array
    {
        $decoded = $this->decode($value);

        if (! is_array($decoded)) {
            return [];
        }

        $specs = $decoded['flexible_spec'] ?? [$decoded];
        $names = [];

        if (! is_array($specs)) {
            return [];
        }

        foreach ($specs as $spec) {
            if (! is_array($spec)) {
                continue;
            }

            foreach (['interests', 'behaviors'] as $key) {
                foreach ($spec[$key] ?? [] as $item) {
                    $name = is_array($item) ? $this->nullableString($item['name'] ?? null) : null;

                    if ($name !== null) {
                        $names[$name] = $name;
                    }
                }
            }
        }

        return array_values($names);
    }

    /**
     * @return list<string>
     */
    private function placementLabels(mixed $value): array
    {
        $decoded = $this->decode($value);

        if (! is_array($decoded)) {
            return [];
        }

        $labels = [];
        $positions = [
            'facebook' => $decoded['facebook_positions'] ?? [],
            'instagram' => $decoded['instagram_positions'] ?? [],
            'messenger' => $decoded['messenger_positions'] ?? [],
            'audience_network' => $decoded['audience_network_positions'] ?? [],
            'threads' => $decoded['threads_positions'] ?? [],
        ];

        foreach ($positions as $publisher => $publisherPositions) {
            if (! is_array($publisherPositions)) {
                continue;
            }

            foreach ($publisherPositions as $position) {
                if (! is_string($position) || trim($position) === '') {
                    continue;
                }

                $labels[$this->placementLabel($publisher, $position)] = true;
            }
        }

        return array_keys($labels);
    }

    private function placementLabel(string $publisher, string $position): string
    {
        $publisher = strtolower(trim($publisher));
        $position = strtolower(trim($position));
        $known = [
            'facebook|feed' => 'Facebook Feed',
            'facebook|story' => 'Facebook Stories',
            'facebook|facebook_stories' => 'Facebook Stories',
            'facebook|reels' => 'Facebook Reels',
            'facebook|facebook_reels' => 'Facebook Reels',
            'instagram|feed' => 'Instagram Feed',
            'instagram|stream' => 'Instagram Feed',
            'instagram|story' => 'Instagram Stories',
            'instagram|instagram_stories' => 'Instagram Stories',
            'instagram|reels' => 'Instagram Reels',
            'instagram|instagram_reels' => 'Instagram Reels',
        ];

        if (isset($known[$publisher.'|'.$position])) {
            return $known[$publisher.'|'.$position];
        }

        $publisherLabel = match ($publisher) {
            'facebook' => 'Facebook',
            'instagram' => 'Instagram',
            'audience_network' => 'Audience Network',
            'messenger' => 'Messenger',
            'threads' => 'Threads',
            '' => 'Unknown',
            default => ucfirst($publisher),
        };
        $positionLabel = ucwords(str_replace('_', ' ', $position));

        if ($positionLabel === '' || strtolower($positionLabel) === 'unknown') {
            return $publisherLabel;
        }

        return $publisherLabel.' '.$positionLabel;
    }

    /**
     * @return list<string>|null
     */
    private function deviceSetup(mixed $value): ?array
    {
        $decoded = $this->decode($value);

        if (! is_array($decoded)) {
            return null;
        }

        $list = $decoded['device_platforms'] ?? $decoded['user_os'] ?? null;

        if (! is_array($list)) {
            return null;
        }

        $devices = [];

        foreach ($list as $device) {
            if (is_string($device) && trim($device) !== '') {
                $devices[] = strtolower(trim($device));
            }
        }

        return $devices === [] ? null : $devices;
    }

    private function deviceGroup(string $device): string
    {
        if (str_contains($device, 'mobile') || str_contains($device, 'iphone') || str_contains($device, 'android_smartphone')) {
            return 'mobile';
        }

        if (str_contains($device, 'tablet') || str_contains($device, 'ipad')) {
            return 'tablet';
        }

        if (str_contains($device, 'desktop')) {
            return 'desktop';
        }

        return 'other';
    }

    /**
     * @return list<string>|null
     */
    private function stringList(mixed $value): ?array
    {
        if ($value === null || $value === '' || $value === '[]' || $value === 'null') {
            return null;
        }

        $decoded = $this->decode($value);

        if (is_string($decoded) && trim($decoded) !== '') {
            return [trim($decoded)];
        }

        if (! is_array($decoded)) {
            return null;
        }

        $values = [];

        foreach ($decoded as $item) {
            if (is_string($item) && trim($item) !== '') {
                $values[] = trim($item);
            } elseif (is_array($item)) {
                $name = $this->nullableString($item['name'] ?? null);

                if ($name !== null) {
                    $values[] = $name;
                }
            }
        }

        return $values === [] ? null : $values;
    }

    private function decode(mixed $value): mixed
    {
        if (is_array($value)) {
            return $value;
        }

        if (! is_string($value)) {
            return null;
        }

        $trimmed = trim($value);

        if ($trimmed === '' || $trimmed === 'null') {
            return null;
        }

        $decoded = json_decode($trimmed, true);

        return json_last_error() === JSON_ERROR_NONE ? $decoded : $trimmed;
    }

    private function hoursSince(?string $iso): ?int
    {
        if ($iso === null) {
            return null;
        }

        try {
            $seconds = now()->getTimestamp() - Carbon::parse($iso)->getTimestamp();
        } catch (Throwable) {
            return null;
        }

        if ($seconds < 0) {
            return null;
        }

        return intdiv($seconds, 3600);
    }

    private function iso(mixed $value): ?string
    {
        if (! is_string($value) || trim($value) === '') {
            return null;
        }

        try {
            return Carbon::parse($value)->utc()->toIso8601String();
        } catch (Throwable) {
            return null;
        }
    }

    private function addFloat(?float $current, mixed $value): ?float
    {
        $addition = $this->nullableFloat($value);

        if ($addition === null) {
            return $current;
        }

        return ($current ?? 0) + $addition;
    }

    private function addInt(?int $current, mixed $value): ?int
    {
        $addition = $this->nullableInt($value);

        if ($addition === null) {
            return $current;
        }

        return ($current ?? 0) + $addition;
    }

    private function rate(int|float|null $numerator, int|float|null $denominator, float $scale, int $precision = 2): ?float
    {
        if ($numerator === null || $denominator === null || $denominator <= 0) {
            return null;
        }

        return round(($numerator / $denominator) * $scale, $precision);
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    private function column(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $candidate) {
            if (in_array($candidate, $columns, true) && preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $candidate) === 1) {
                return $candidate;
            }
        }

        return null;
    }

    /**
     * @param  list<string>  $columns
     */
    private function field(object $row, array $columns, string $name): mixed
    {
        if (! in_array($name, $columns, true)) {
            return null;
        }

        return $row->{$name} ?? null;
    }

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

        return $fallback;
    }

    private function nullableString(mixed $value): ?string
    {
        if ($value === null) {
            return null;
        }

        $string = trim((string) $value);

        return $string === '' ? null : $string;
    }

    private function nullableFloat(mixed $value): ?float
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (! is_numeric($value)) {
            return null;
        }

        return (float) $value;
    }

    private function nullableInt(mixed $value): ?int
    {
        if ($value === null || $value === '' || ! is_numeric($value)) {
            return null;
        }

        return (int) $value;
    }
}
