<?php

namespace App\Campaigns;

use App\Library\CampaignDecision\CampaignDecisionVerdict;
use App\Services\LandingPageAnalyzer;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;

/**
 * Facts for a "how do I improve this campaign?" answer.
 *
 * The chat prints the PHP recommendations, then adds its own suggestions
 * for budget, creative, and the landing page. Each added suggestion must
 * cite a field returned here. Page speed, profit, remaining budget, and a
 * winning creative are not in this result.
 */
class CampaignSuggestionReader
{
    public function __construct(
        private readonly WhaleAdopsQuery $query,
        private readonly WhaleAdopsTables $tables,
        private readonly RoiDashboardReader $roi,
        private readonly CampaignPerformanceAdopsMonitor $monitor,
        private readonly LandingPageAnalyzer $pages,
        private readonly CampaignPerformanceWhaleEnrichment $whale,
        private readonly WhaleAdopsReader $profiles,
        private readonly AdSetOptimizationAssembler $adSets,
    ) {}

    /**
     * Latest offsite conversion per day, keyed by platform, campaign, and window.
     *
     * @var array<string, array<string, float>|null>
     */
    private array $offsiteConversionsByWindow = [];

    /**
     * @return array<string, mixed>
     */
    public function forCampaign(string $platform, string $campaignId, string $focus = 'performance', ?string $from = null, ?string $to = null): array
    {
        $platform = strtolower(trim($platform)) ?: 'meta';
        $campaignId = trim($campaignId);
        $focus = in_array($focus, ['creative', 'landing', 'targeting'], true) ? $focus : 'performance';
        [$from, $to] = $this->window($from, $to);

        $campaign = array_merge(
            $this->firstRow('campaigns', $platform, $campaignId, $from, $to),
            $this->campaignExtras($platform, $campaignId),
        );
        $profile = $this->profiles->profileFacts($platform, $campaignId);
        $ads = $this->rows('ads', $platform, $campaignId, $from, $to);
        $targeting = $this->rows('targeting', $platform, $campaignId, $from, $to);
        $delivery = $this->delivery($platform, $campaignId, $from, $to);
        $sales = $this->sales($platform, $campaignId, $from, $to);
        $creatives = $this->creatives($platform, $ads);
        $verdict = $this->verdict($platform, $campaignId, $sales);
        $health = $this->healthLabel($verdict['verdict'] ?? null, $sales);
        $landingPages = $this->landingPages($ads, $creatives);
        $roi = $this->roiTotals($platform, $campaignId, $from, $to);
        $campaignPayload = [
            'name' => $campaign['name'] ?? $campaign['campaign_name'] ?? null,
            'objective' => $campaign['objective'] ?? $profile['objective'],
            'region' => $profile['region_label'],
            'description' => $campaign['description'] ?? null,
            'status' => $campaign['status'] ?? null,
            'effective_status' => $campaign['effective_status'] ?? null,
            'learning_status' => $campaign['learning_status'] ?? null,
            'daily_budget' => $this->numberOrNull($campaign['daily_budget'] ?? null),
            'lifetime_budget' => $this->numberOrNull($campaign['lifetime_budget'] ?? null),
            'start_time' => $campaign['start_time'] ?? null,
            'optimization_goal' => $campaign['optimization_goal'] ?? null,
        ];

        if ($campaignPayload['optimization_goal'] === null) {
            foreach ($this->rows('adsets', $platform, $campaignId, $from, $to) as $adset) {
                $goal = trim((string) ($adset['optimization_goal'] ?? ''));

                if ($goal !== '') {
                    $campaignPayload['optimization_goal'] = $goal;
                    break;
                }
            }
        }

        $adSetOptimization = $this->adSets->forCampaign($platform, $campaignId, $from, $to);
        $audienceContext = trim((string) ($campaignPayload['name'] ?? ''));
        $adSetOptimization['cards'] = AdSetOptimizationCards::cards($adSetOptimization, 'hold', $audienceContext, $platform);
        $analysis = (new CampaignFunnelAnalysis)->build(
            $campaignId,
            is_string($campaignPayload['name'] ?? null) ? $campaignPayload['name'] : null,
            $from,
            $to,
            $campaignPayload['daily_budget'],
            is_string($campaignPayload['optimization_goal'] ?? null) ? $campaignPayload['optimization_goal'] : null,
            $delivery,
            $this->dailyRows($platform, $campaignId, $from, $to),
            $this->dailyRows($platform, $campaignId, $this->previousFrom($from, $to), $this->previousTo($from)),
            $this->adDeliveryRows($platform, $campaignId, $from, $to, $ads),
            $creatives,
            $landingPages,
            $roi,
            $this->actionCounts($platform, $campaignId, $from, $to),
        );

        return [
            'ok' => true,
            'focus' => $focus,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'campaign' => $campaignPayload,
            'audience' => $this->audience($targeting),
            'delivery' => $delivery,
            'sales' => $sales,
            'daily' => $this->dailyHistory($platform, $campaignId, $from, $to),
            'roi' => $roi,
            'ads' => array_map(fn (array $ad): array => [
                'ad_id' => $ad['ad_id'] ?? null,
                'name' => $ad['name'] ?? null,
                'status' => $ad['status'] ?? null,
                'creative_id' => $ad['creative_id'] ?? null,
                'landing_url' => $this->cleanLandingUrl(
                    is_string($ad['landing_url'] ?? null) ? $ad['landing_url'] : (is_string($ad['final_url'] ?? null) ? $ad['final_url'] : null),
                ),
            ], $ads),
            'creatives' => array_map(function (array $creative): array {
                foreach (['landing_url', 'final_url'] as $key) {
                    if (array_key_exists($key, $creative)) {
                        $creative[$key] = $this->cleanLandingUrl(is_string($creative[$key]) ? $creative[$key] : null);
                    }
                }

                return $creative;
            }, $creatives),
            'landing_pages' => $landingPages,
            'analysis' => $analysis,
            'verdict' => $verdict,
            'health' => $health,
            'problems' => $this->problems($campaign, $sales, $delivery),
            'recommendations' => $this->recommendations($campaign, $sales, $delivery, $verdict, $adSetOptimization, $audienceContext, $platform),
            'ad_set_optimization' => $adSetOptimization,
            'note' => $this->note($focus),
        ];
    }

    /**
     * Windows for a follow-up about a campaign already discussed in the chat.
     *
     * @return array<string, mixed>
     */
    public function followUp(string $platform, string $campaignId, ?string $to = null): array
    {
        $platform = strtolower(trim($platform)) ?: 'meta';
        $campaignId = trim($campaignId);
        $end = $this->date($to) ?? now()->toDateString();
        $endDate = Carbon::parse($end);
        $campaign = $this->firstRow('campaigns', $platform, $campaignId, $endDate->copy()->subDays(29)->toDateString(), $end);
        $name = $campaign['name'] ?? $campaign['campaign_name'] ?? null;
        $windows = [];

        foreach ([3, 5, 7, 15, 30] as $days) {
            $from = $endDate->copy()->subDays($days - 1)->toDateString();
            $hasRows = $this->hasDeliveryRows('stats_campaign_daily', $platform, $campaignId, $from, $end)
                || $this->hasDeliveryRows('stats_daily', $platform, $campaignId, $from, $end);

            if (! $hasRows) {
                $windows[] = [
                    'days' => $days,
                    'from' => $from,
                    'to' => $end,
                    'has_rows' => false,
                    'subscriptions' => null,
                ];

                continue;
            }

            $roi = $this->roiTotals($platform, $campaignId, $from, $end);
            $windows[] = array_merge(
                [
                    'days' => $days,
                    'from' => $from,
                    'to' => $end,
                    'has_rows' => true,
                ],
                (new CampaignFunnelAnalysis)->windowMetrics(
                    $this->delivery($platform, $campaignId, $from, $end),
                    $this->actionCounts($platform, $campaignId, $from, $end),
                ),
                [
                    'subscriptions' => is_array($roi) ? $roi['subscriptions'] : null,
                ],
            );
        }

        return [
            'ok' => true,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'name' => is_string($name) ? $name : null,
            'to' => $end,
            'windows' => $windows,
            'audiences' => $this->audiences($platform, $campaignId),
            'response_breakdown' => $this->responseBreakdown($platform, $campaignId, $end),
            'note' => 'Answer only the follow-up the user asked about the campaign_id in this result. That campaign_id is the latest campaign the user named. Do not answer about an earlier campaign. A question about how a specific campaign is performing does not use this result. A question about the budget, whether the results are enough for the spend, a suggestion, or a pause does use this result. Do not print the Metric and Result table for those questions. Give the suggestions that fit that question. After that short answer, add three sections whose headings match the question. Recommended decision lists the choices for what was asked, and each choice cites a returned number. What should determine your decision lists the few checks that matter for that question, citing a returned number when one decides the check. My recommendation is one sentence for the choice to make, with the reason and the effect on this campaign. A landing-page question uses a page decision. A budget question uses a budget decision. When the user asks which audiences waste spend, name the audiences from the audiences list. That list is arb_adops_targeting. Spend is not split by audience. If several audiences share one ad set, the spend belongs to that whole ad set. Do not name one audience as the one that wasted the spend. This result has no keyword spend. Do not invent a keyword. response_breakdown is arb_adops_stats_breakdown_daily for age and gender over the 30 days ending on to. When the user asks who is responding, or about audience, age, or gender results, compare these slices by spend and conversions. A custom audience is not one of these slices. If slices is empty, say this window has no age or gender rows in arb_adops_stats_breakdown_daily. Do not print a table. Do not list the 3, 5, 7, 15, or 30 day windows. Those windows are context. Use a spend_label, impressions, outbound_clicks, outbound_ctr_label, landing_page_views, conversions, cost_per_conversion_label, cpc_label, or subscriptions value only inside a suggestion when that number is the reason for it. click_basis says whether outbound_clicks is the outbound click count or the click count. A window with has_rows false has no Whale rows. Do not treat it as zero. subscriptions is null when that window has no ROI rows. Do not treat a null subscription count as zero. Do not reprint the Metric and Result performance table. Do not copy the earlier budget paragraph. Do not invent a heading, offer, or button. When the user asks why people click but do not complete the action, place the drop with the returned outbound clicks, landing-page views, and conversions. When those numbers do not name the cause, add the usual checks for that stage and label each one as a check. Clicks and landing-page views close together, with conversions at zero, means the drop is after the page loads: the page, the match between the ad and the page, the offer, the optimization event, and tracking of the action. Clicks high and landing-page views missing means the drop is before the page: page load and visit tracking. A longer window that already recorded the action means tracking is one check. Do not state a check as a finding about this campaign. Do not use a sample funnel or an invented rate. Do not change the verdict.',
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function audiences(string $platform, string $campaignId): array
    {
        $adSets = [];

        foreach ($this->rows('adsets', $platform, $campaignId, now()->subDays(29)->toDateString(), now()->toDateString()) as $row) {
            $id = trim((string) ($row['adset_id'] ?? ''));

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

            $adSets[$id] = is_string($row['name'] ?? null) ? $row['name'] : null;
        }

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

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

        $columns = $this->tables->columns($table);
        $entityColumn = in_array('entity_id', $columns, true) ? 'entity_id' : null;

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

        $ids = array_values(array_unique([...array_keys($adSets), $campaignId]));

        try {
            $query = DB::connection('whale')->table($table)->whereIn($entityColumn, $ids);

            if (in_array('platform', $columns, true)) {
                $query->whereRaw('LOWER(platform) = ?', [$platform]);
            }

            $select = array_values(array_filter(
                ['entity_id', 'entity_level', 'audiences_included', 'interests', 'countries', 'age_min', 'age_max', 'genders'],
                fn (string $column): bool => in_array($column, $columns, true),
            ));
            $rows = $query->limit(25)->get($select);
        } catch (Throwable) {
            return [];
        }

        $audiences = [];

        foreach ($rows as $row) {
            $field = function (string $column) use ($row, $select): mixed {
                if (! in_array($column, $select, true)) {
                    return null;
                }

                return $row->{$column} ?? null;
            };
            $entityId = trim((string) $field('entity_id'));

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

            $audiences[] = [
                'adset_id' => $entityId === $campaignId ? null : $entityId,
                'adset_name' => $adSets[$entityId] ?? null,
                'included_audiences' => $this->audienceNames($field('audiences_included')),
                'interests' => $this->audienceNames($field('interests')),
                'countries' => $this->audienceNames($field('countries')),
                'age_min' => $field('age_min') !== null ? (int) $field('age_min') : null,
                'age_max' => $field('age_max') !== null ? (int) $field('age_max') : null,
                'genders' => $this->audienceNames($field('genders')),
            ];
        }

        return $audiences;
    }

    /**
     * @return list<string>
     */
    private function audienceNames(mixed $value): array
    {
        if (is_string($value)) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : [$value];
        }

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

        $names = [];

        foreach ($value as $item) {
            if (is_string($item) || is_numeric($item)) {
                $name = trim((string) $item);
            } elseif (is_array($item)) {
                $name = trim((string) ($item['name'] ?? ''));

                foreach (['interests', 'behaviors'] as $key) {
                    foreach ($this->audienceNames($item[$key] ?? null) as $nested) {
                        $names[$nested] = $nested;
                    }
                }
            } else {
                $name = '';
            }

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

        return array_values($names);
    }

    /**
     * @return array{from: string, to: string, slices: list<array<string, mixed>>}
     */
    private function responseBreakdown(string $platform, string $campaignId, string $end): array
    {
        $from = Carbon::parse($end)->subDays(29)->toDateString();
        $result = $this->query->run([
            'dataset' => 'stats_breakdown_daily',
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $end,
            'dimension' => 'age_gender',
            'group_by' => 'value_1,value_2',
            'limit' => 100,
        ]);
        $rows = ($result['ok'] ?? false) === true && is_array($result['rows'] ?? null) ? $result['rows'] : [];
        $slices = [];

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

            $left = $this->breakdownDemographic((string) ($row['value_1'] ?? ''));
            $right = $this->breakdownDemographic((string) ($row['value_2'] ?? ''));
            $slices[] = [
                'age' => $left['age'] ?? $right['age'],
                'gender' => $left['gender'] ?? $right['gender'],
                'spend' => array_key_exists('spend', $row) ? round((float) $row['spend'], 2) : null,
                'impressions' => array_key_exists('impressions', $row) ? (int) $row['impressions'] : null,
                'clicks' => array_key_exists('clicks', $row) ? (int) $row['clicks'] : null,
                'conversions' => array_key_exists('conversions', $row) ? round((float) $row['conversions'], 2) : null,
            ];
        }

        usort($slices, fn (array $left, array $right): int => ($right['spend'] ?? 0) <=> ($left['spend'] ?? 0));

        return [
            'from' => $from,
            'to' => $end,
            'slices' => $slices,
        ];
    }

    /**
     * @return array{age: ?string, gender: ?string}
     */
    private function breakdownDemographic(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];
    }

    /**
     * @return array{0: string, 1: string}
     */
    private function window(?string $from, ?string $to): array
    {
        $start = $this->date($from);
        $end = $this->date($to);

        if ($start !== null && $end !== null && $start <= $end) {
            return [$start, $end];
        }

        return [now()->subDays(29)->toDateString(), now()->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;
    }

    /**
     * @param  list<array<string, mixed>>  $ads
     * @param  list<array<string, mixed>>  $creatives
     * @return list<array<string, mixed>>
     */
    private function landingPages(array $ads, array $creatives): array
    {
        $urls = [];

        foreach ([...$ads, ...$creatives] as $row) {
            foreach (['landing_url', 'final_url'] as $key) {
                $url = $this->cleanLandingUrl(is_string($row[$key] ?? null) ? $row[$key] : null) ?? '';

                if ($url !== '' && filter_var($url, FILTER_VALIDATE_URL)) {
                    $urls[$url] = $url;
                }
            }
        }

        $pages = [];

        foreach (array_slice(array_values($urls), 0, 5) as $url) {
            $pages[] = $this->readLandingPage($url);
        }

        return $pages;
    }

    /**
     * Drop unfilled Meta tokens such as {{campaign.id}} before the page is read.
     */
    private function cleanLandingUrl(?string $url): ?string
    {
        if ($url === null) {
            return null;
        }

        $url = trim($url);

        if ($url === '') {
            return '';
        }

        $url = preg_replace('/%7B%7B.*?%7D%7D/i', '', $url) ?? $url;
        $url = preg_replace('/\{\{.*?\}\}/', '', $url) ?? $url;
        $parts = parse_url($url);

        if (! is_array($parts) || ! isset($parts['host'])) {
            return trim($url, '?&= ');
        }

        $path = preg_replace('#/{2,}#', '/', $parts['path'] ?? '') ?? '';
        $query = [];

        if (isset($parts['query']) && $parts['query'] !== '') {
            parse_str($parts['query'], $parsed);

            foreach ($parsed as $key => $value) {
                if (! is_string($key) || $key === '' || ! is_scalar($value)) {
                    continue;
                }

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

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

                $query[$key] = $value;
            }
        }

        $rebuilt = ($parts['scheme'] ?? 'https').'://'.$parts['host'];

        if (isset($parts['port'])) {
            $rebuilt .= ':'.$parts['port'];
        }

        $rebuilt .= $path;

        if ($query !== []) {
            $rebuilt .= '?'.http_build_query($query);
        }

        return $rebuilt;
    }

    /**
     * @return array<string, mixed>
     */
    private function readLandingPage(string $url): array
    {
        try {
            $analysis = $this->pages->analyze($url);

            return [
                'url' => $analysis->url,
                'title' => $analysis->title,
                'description' => $analysis->description,
                'headings' => $analysis->headings,
                'text' => $analysis->text,
                'suggested_outcome' => $analysis->suggestedOutcome(),
            ];
        } catch (Throwable) {
            return [
                'url' => $url,
                'title' => null,
                'description' => null,
                'headings' => [],
                'text' => null,
                'suggested_outcome' => null,
            ];
        }
    }

    /**
     * @return array<string, mixed>
     */
    private function campaignExtras(string $platform, string $campaignId): array
    {
        $table = $this->tables->name('campaigns');

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

        $columns = $this->tables->columns($table);
        $wanted = array_values(array_filter(
            ['start_time', 'description'],
            fn (string $column): bool => in_array($column, $columns, true),
        ));
        $idColumn = $this->pick($columns, ['campaign_id', 'external_campaign_id']);

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

        try {
            $query = DB::connection('whale')->table($table)->where($idColumn, $campaignId);

            if (in_array('platform', $columns, true)) {
                $query->where('platform', $platform);
            }

            $row = $query->first($wanted);

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

            $extras = [];

            foreach ($wanted as $column) {
                $extras[$column] = $row->{$column} ?? null;
            }

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

    /**
     * @return array<string, mixed>
     */
    private function firstRow(string $dataset, string $platform, string $campaignId, string $from, string $to): array
    {
        return $this->rows($dataset, $platform, $campaignId, $from, $to)[0] ?? [];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function rows(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' => 25,
        ]);

        return ($result['ok'] ?? false) === true && is_array($result['rows'] ?? null) ? $result['rows'] : [];
    }

    /**
     * @return array<string, mixed>
     */
    private function delivery(string $platform, string $campaignId, string $from, string $to): array
    {
        $source = 'arb_adops_stats_campaign_daily';
        $row = [];

        if ($this->hasDeliveryRows('stats_campaign_daily', $platform, $campaignId, $from, $to)) {
            $row = $this->deliveryTotals('stats_campaign_daily', $platform, $campaignId, $from, $to);
        } else {
            $source = 'arb_adops_stats_daily';
            $monthFrom = now()->startOfMonth()->subMonth()->toDateString();
            $boundedFrom = $from > $monthFrom ? $from : $monthFrom;
            $row = $this->deliveryTotals('stats_daily', $platform, $campaignId, $boundedFrom, $to);
        }

        $spend = (float) ($row['spend'] ?? 0);
        $clicks = (float) $this->deliveryClicks($row);
        $impressions = (float) ($row['impressions'] ?? 0);
        $reach = array_key_exists('reach', $row) ? (float) $row['reach'] : null;
        $conversions = array_key_exists('conversions', $row) ? (float) $row['conversions'] : null;
        $offsite = $this->offsiteConversions($platform, $campaignId, $from, $to);

        if ($offsite !== null) {
            $conversions = round(array_sum($offsite), 4);
        } elseif ($conversions === null && $source === 'arb_adops_stats_campaign_daily') {
            $monthFrom = now()->startOfMonth()->subMonth()->toDateString();
            $boundedFrom = $from > $monthFrom ? $from : $monthFrom;
            $adDaily = $this->deliveryTotals('stats_daily', $platform, $campaignId, $boundedFrom, $to);

            if (array_key_exists('conversions', $adDaily) && $adDaily['conversions'] !== null) {
                $conversions = (float) $adDaily['conversions'];
            }
        }

        return [
            'from' => $from,
            'to' => $to,
            'spend' => round($spend, 2),
            'impressions' => $impressions,
            'reach' => $reach,
            'clicks' => $clicks,
            'conversions' => $conversions,
            'all_clicks' => array_key_exists('clicks', $row) ? (int) $row['clicks'] : null,
            'link_clicks' => array_key_exists('link_clicks', $row) ? (int) $row['link_clicks'] : null,
            'outbound_clicks' => array_key_exists('outbound_clicks', $row) ? (int) $row['outbound_clicks'] : null,
            'conversion_value' => array_key_exists('conversion_value', $row) ? round((float) $row['conversion_value'], 2) : null,
            'ctr' => $impressions > 0 ? round($clicks / $impressions, 4) : null,
            'cpc' => $clicks > 0 ? round($spend / $clicks, 4) : null,
            'cpm' => $impressions > 0 ? round(($spend / $impressions) * 1000, 4) : null,
            'source' => $source,
        ];
    }

    /**
     * One conversion count per day from arb_adops_conversions_daily_YYYYMM.
     *
     * Meta stores the same result under several offsite_conversion keys. The
     * newest row for that day is the count Ads Manager shows. Null when this
     * campaign has no offsite_conversion row in the window, so other campaigns
     * keep the daily stats column.
     *
     * @return array<string, float>|null
     */
    private function offsiteConversions(string $platform, string $campaignId, string $from, string $to): ?array
    {
        $key = $platform.'|'.$campaignId.'|'.$from.'|'.$to;

        if (array_key_exists($key, $this->offsiteConversionsByWindow)) {
            return $this->offsiteConversionsByWindow[$key];
        }

        $byDate = [];
        $found = false;

        foreach ($this->tables->tablesFor('conversions_daily', $from, $to) as $table) {
            $columns = $this->tables->columns($table);
            $actionColumn = $this->listedColumn($columns, ['action_key', 'action_name']);
            $dateColumn = $this->listedColumn($columns, ['stat_date', 'date']);
            $conversionColumn = $this->listedColumn($columns, ['conversions']);
            $campaignColumn = $this->listedColumn($columns, ['campaign_id']);

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

            $platformColumn = $this->listedColumn($columns, ['platform']);
            $idColumn = $this->listedColumn($columns, ['id']);

            try {
                $query = DB::connection('whale')->table($table)
                    ->where($campaignColumn, $campaignId)
                    ->whereBetween($dateColumn, [$from, $to])
                    ->where($actionColumn, 'like', 'offsite_conversion%')
                    ->orderBy($dateColumn);

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

                if ($idColumn !== null) {
                    $query->orderBy($idColumn);
                }

                foreach ($query->get([$dateColumn, $conversionColumn]) as $row) {
                    $found = true;
                    $date = Carbon::parse((string) $row->{$dateColumn})->toDateString();
                    $byDate[$date] = (float) $row->{$conversionColumn};
                }
            } catch (Throwable) {
                continue;
            }
        }

        return $this->offsiteConversionsByWindow[$key] = $found ? $byDate : null;
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $names
     */
    private function listedColumn(array $columns, array $names): ?string
    {
        foreach ($names as $name) {
            if (in_array($name, $columns, true)) {
                return $name;
            }
        }

        return null;
    }

    private function hasDeliveryRows(string $dataset, string $platform, string $campaignId, string $from, string $to): bool
    {
        $result = $this->query->run([
            'dataset' => $dataset,
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'group_by' => 'stat_date',
            'limit' => 1,
        ]);

        return ($result['ok'] ?? false) === true && ($result['rows'] ?? []) !== [];
    }

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

        $row = (($totals['ok'] ?? false) === true) ? ($totals['rows'][0] ?? []) : [];

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

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

        if (($performance['ok'] ?? false) === true && ($performance['rows'][0] ?? null) !== null) {
            $row = $performance['rows'][0];
            $sales = (float) ($row['net_revenue'] ?? 0);

            return [
                'source' => 'arb_adops_campaign_performance',
                'from' => $from,
                'to' => $to,
                'spend' => null,
                'sales' => round($sales, 2),
                'orders' => round((float) ($row['orders'] ?? 0), 4),
                'conversions' => null,
                'roas' => null,
            ];
        }

        $roi = $this->roi->forCampaign($platform, $campaignId, $from, $to);
        $spent = 0.0;
        $sales = 0.0;
        $orders = 0.0;
        $conversions = 0.0;

        foreach ($roi['rows'] as $row) {
            $spent += (float) ($row['spent'] ?? 0);
            $sales += (float) ($row['arb_sales_amount'] ?? 0);
            $orders += (float) ($row['arb_orders'] ?? 0);
            $conversions += (float) ($row['conversions'] ?? 0);
        }

        return [
            'source' => $roi['included'] ? 'roi_dashboard_campaign_stats' : null,
            'from' => $from,
            'to' => $to,
            'spend' => round($spent, 2),
            'sales' => round($sales, 2),
            'orders' => round($orders, 4),
            'conversions' => round($conversions, 4),
            'roas' => $spent > 0 ? round($sales / $spent, 4) : null,
        ];
    }

    /**
     * @return array{
     *     from: string,
     *     to: string,
     *     expected_days: int,
     *     days_on_file: int,
     *     rows: list<array<string, mixed>>
     * }
     */
    private function dailyHistory(string $platform, string $campaignId, string $from, string $to): array
    {
        $result = $this->query->run([
            'dataset' => 'stats_campaign_daily',
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'group_by' => 'stat_date',
            'limit' => PerformanceWindows::AI_CONTEXT_DAYS,
        ]);
        $rows = (($result['ok'] ?? false) === true && is_array($result['rows'] ?? null)) ? $result['rows'] : [];
        $offsite = $this->offsiteConversions($platform, $campaignId, $from, $to);
        $days = collect($rows)->map(function (array $row) use ($offsite): ?PerformanceDay {
            $date = $row['stat_date'] ?? $row['date'] ?? null;

            if (! is_string($date) || trim($date) === '') {
                return null;
            }

            $day = Carbon::parse($date)->startOfDay();
            $clicks = $this->deliveryClicks($row);
            $impressions = (int) ($row['impressions'] ?? 0);
            $spend = round((float) ($row['spend'] ?? 0), 2);
            $conversions = array_key_exists('conversions', $row) ? (int) $row['conversions'] : null;

            if ($offsite !== null && array_key_exists($day->toDateString(), $offsite)) {
                $conversions = (int) round($offsite[$day->toDateString()]);
            }

            return new PerformanceDay(
                stat_date: $day,
                spend: $spend,
                impressions: $impressions,
                clicks: $clicks,
                cpc: $clicks > 0 ? round($spend / $clicks, 4) : null,
                ctr: $impressions > 0 ? round($clicks / $impressions, 4) : null,
                conversions: $conversions,
                conversion_value: array_key_exists('conversion_value', $row) ? (float) $row['conversion_value'] : null,
            );
        })->filter();

        return PerformanceDailyHistory::fromDays(
            $days,
            $this->whale->outcomeDaily($platform, $campaignId),
        );
    }

    /**
     * ROI totals for the same window. Null when this campaign has no ROI rows in the window.
     * Kept off the verdict inputs.
     *
     * @return array<string, int|float|string|null>|null
     */
    private function roiTotals(string $platform, string $campaignId, string $from, string $to): ?array
    {
        if (! Schema::connection('whale')->hasTable('roi_dashboard_campaign_stats')) {
            return null;
        }

        $row = $this->roiSum($campaignId, $from, $to, $platform);

        if ((int) ($row->row_count ?? 0) === 0) {
            $row = $this->roiSum($campaignId, $from, $to, null);
        }

        if ((int) ($row->row_count ?? 0) === 0) {
            return null;
        }

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

    private function roiSum(string $campaignId, string $from, string $to, ?string $platform): ?object
    {
        $query = DB::connection('whale')
            ->table('roi_dashboard_campaign_stats')
            ->where('campaign_id', $campaignId)
            ->whereBetween('date', [$from, $to]);

        if ($platform !== null && $platform !== '') {
            $query->whereRaw('LOWER(platform) = ?', [strtolower($platform)]);
        }

        return $query
            ->selectRaw('COUNT(*) as row_count')
            ->selectRaw('COALESCE(SUM(arb_sales_amount), 0) as sales')
            ->selectRaw('COALESCE(SUM(arb_orders), 0) as orders')
            ->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')
            ->first();
    }

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

        foreach ($ads as $ad) {
            $id = trim((string) ($ad['creative_id'] ?? ''));

            if ($id !== '') {
                $ids[$id] = $id;
            }
        }

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

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

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

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

        $select = array_values(array_filter(
            ['creative_id', 'name', 'headlines', 'primary_text', 'description', 'cta', 'landing_url', 'final_url', 'type'],
            fn (string $column): bool => in_array($column, $columns, true),
        ));

        try {
            $rows = DB::connection('whale')->table($table)->whereIn($idColumn, array_values($ids));

            if (in_array('platform', $columns, true)) {
                $rows->where('platform', $platform);
            }

            return $rows->limit(25)->get($select)->map(function (object $row) use ($select): array {
                $out = [];

                foreach ($select as $column) {
                    $out[$column] = $row->{$column} ?? null;
                }

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

    /**
     * @param  list<array<string, mixed>>  $targeting
     * @return array<string, mixed>
     */
    private function audience(array $targeting): array
    {
        $row = $targeting[0] ?? [];

        return [
            'countries' => $row['countries'] ?? $row['country'] ?? null,
            'age_min' => $row['age_min'] ?? null,
            'age_max' => $row['age_max'] ?? null,
            'placements' => $row['placements'] ?? null,
            'devices' => $row['devices'] ?? null,
        ];
    }

    /**
     * @param  array<string, mixed>  $sales
     * @return array<string, mixed>
     */
    private function verdict(string $platform, string $campaignId, array $sales): array
    {
        $health = null;

        try {
            $health = $this->monitor->health($platform, $campaignId);
        } catch (Throwable) {
            $health = null;
        }

        $evaluation = is_array($health['evaluation'] ?? null) ? $health['evaluation'] : [];
        $snapshot = is_array($health['snapshot'] ?? null) ? $health['snapshot'] : [];
        $reasons = is_array($snapshot['reasons'] ?? null) ? $snapshot['reasons'] : [];
        $basis = $this->basis($sales, $reasons);

        return [
            'verdict' => $evaluation['final_verdict'] ?? $snapshot['verdict'] ?? null,
            'reason' => $evaluation['final_reason'] ?? $snapshot['reason'] ?? null,
            'recommended_action' => $snapshot['recommended_action'] ?? null,
            'recommended_budget_change_percent' => $snapshot['recommended_budget_change_percent'] ?? null,
            'confidence' => $snapshot['confidence'] ?? null,
            'reasons' => $reasons,
            'basis' => $basis,
        ];
    }

    /**
     * @param  array<string, mixed>  $sales
     * @param  list<array<string, mixed>>  $reasons
     * @return array<string, mixed>
     */
    private function basis(array $sales, array $reasons): array
    {
        $good = (float) config('campaign-decisions.defaults.good_cost_per_result', 2);
        $acceptable = (float) config('campaign-decisions.defaults.acceptable_cost_per_result', 4);
        $minimumRoas = (float) config('campaign-decisions.defaults.minimum_roas', 1.2);
        $conversions = (float) ($sales['conversions'] ?? 0);
        $spend = (float) ($sales['spend'] ?? 0);
        $cost = $conversions > 0 ? round($spend / $conversions, 2) : null;

        foreach ($reasons as $reason) {
            if (! is_array($reason) || ! str_starts_with((string) ($reason['metric'] ?? ''), 'cost_per_')) {
                continue;
            }

            $cost = isset($reason['current']) ? round((float) $reason['current'], 2) : $cost;
            $good = isset($reason['target']) ? (float) $reason['target'] : $good;
            $acceptable = isset($reason['maximum']) ? (float) $reason['maximum'] : $acceptable;
            $conversions = isset($reason['count']) ? (float) $reason['count'] : $conversions;
        }

        $rule = 'Sales are '.(float) ($sales['sales'] ?? 0).'.';

        if ((float) ($sales['sales'] ?? 0) <= 0 && $conversions > 0 && $cost !== null) {
            $band = $cost <= $good ? 'at or under the good line' : ($cost <= $acceptable ? 'above the good line and at or under the acceptable line' : 'above the acceptable line');
            $rule = 'Sales are 0, so the result used is conversions ('.$conversions.'). Cost per conversion is spend '.$spend.' divided by that count, which is $'.$cost.'. Good is $'.$good.' and acceptable is $'.$acceptable.'. $'.$cost.' is '.$band.'.';
        } elseif ((float) ($sales['sales'] ?? 0) > 0) {
            $rule = 'Sales are '.(float) $sales['sales'].' on spend '.$spend.'. ROAS is '.($sales['roas'] ?? 'null').'. The minimum ROAS line is '.$minimumRoas.'.';
        }

        return [
            'sales' => (float) ($sales['sales'] ?? 0),
            'spend' => $spend,
            'conversions' => $conversions,
            'cost_per_conversion' => $cost,
            'good_cost_per_result' => $good,
            'acceptable_cost_per_result' => $acceptable,
            'minimum_roas' => $minimumRoas,
            'roas' => $sales['roas'] ?? null,
            'rule' => $rule,
        ];
    }

    /**
     * @param  array<string, mixed>  $campaign
     * @param  array<string, mixed>  $sales
     * @param  array<string, mixed>  $delivery
     * @return list<string>
     */
    private function problems(array $campaign, array $sales, array $delivery): array
    {
        $problems = [];
        $objective = strtoupper((string) ($campaign['objective'] ?? ''));
        $salesAmount = (float) ($sales['sales'] ?? 0);
        $spend = (float) ($delivery['spend'] ?? 0);

        if ($salesAmount <= 0 && $spend > 0 && $this->isSalesObjective($objective)) {
            $problems[] = 'Objective is '.$campaign['objective'].' and spend is '.$spend.', but sales are 0.';
        }

        if ($salesAmount <= 0 && (float) ($sales['conversions'] ?? 0) <= 0 && $spend > 0) {
            $problems[] = 'Spend is '.$spend.' with no sales and no conversions in the sales source.';
        }

        return $problems;
    }

    /**
     * @param  array<string, mixed>  $campaign
     * @param  array<string, mixed>  $sales
     * @param  array<string, mixed>  $delivery
     * @param  array<string, mixed>  $verdict
     * @param  array<string, mixed>  $adSetOptimization
     * @return list<array<string, mixed>>
     */
    private function recommendations(array $campaign, array $sales, array $delivery, array $verdict, array $adSetOptimization = [], string $audienceContext = '', string $platform = 'meta'): array
    {
        $recommendations = [];
        $basis = is_array($verdict['basis'] ?? null) ? $verdict['basis'] : [];
        $cost = $basis['cost_per_conversion'] ?? null;
        $good = (float) ($basis['good_cost_per_result'] ?? 2);
        $acceptable = (float) ($basis['acceptable_cost_per_result'] ?? 4);
        $salesAmount = (float) ($sales['sales'] ?? 0);
        $roas = $sales['roas'] ?? null;
        $minimumRoas = (float) ($basis['minimum_roas'] ?? 1.2);

        if ($salesAmount <= 0 && is_numeric($cost)) {
            $cost = (float) $cost;

            if ($cost <= $good) {
                $recommendations[] = $this->recommendation(
                    'Maintain the current budget.',
                    $basis['rule'] ?? '',
                    $basis,
                    'Keep the conversion cost in the good band. This is not a scale action because sales are 0.',
                    'medium',
                    'medium',
                );
            } elseif ($cost <= $acceptable) {
                $recommendations[] = $this->recommendation(
                    'Keep the budget and watch. Do not scale.',
                    $basis['rule'] ?? '',
                    $basis,
                    'Cost stays acceptable, but there are no sales to justify more spend.',
                    'medium',
                    'high',
                );
            } else {
                $recommendations[] = $this->recommendation(
                    'Decrease the budget.',
                    $basis['rule'] ?? '',
                    $basis,
                    'Spend above the acceptable cost line is reduced.',
                    'medium',
                    'high',
                );
            }
        } elseif ($salesAmount > 0 && is_numeric($roas) && (float) $roas >= $minimumRoas) {
            $recommendations[] = $this->recommendation(
                'Increase the budget gradually.',
                (string) ($basis['rule'] ?? ''),
                $basis,
                'More spend at a ROAS that is at or above the minimum line.',
                'medium',
                'high',
            );
        } elseif ($salesAmount <= 0 && (float) ($delivery['spend'] ?? 0) > 0 && (float) ($sales['conversions'] ?? 0) <= 0) {
            $recommendations[] = $this->recommendation(
                'Do not increase the budget. Investigate tracking and the offer before more spend.',
                'Spend is '.$delivery['spend'].' and both sales and conversions are 0.',
                ['spend' => $delivery['spend'], 'sales' => $salesAmount, 'objective' => $campaign['objective'] ?? null],
                'Stops adding spend that has not produced a sale or a conversion.',
                'medium',
                'high',
            );
        }

        if (is_string($verdict['recommended_action'] ?? null) && $verdict['recommended_action'] !== '') {
            $recommendations[] = $this->recommendation(
                (string) $verdict['recommended_action'].(isset($verdict['recommended_budget_change_percent']) ? ' ('.$verdict['recommended_budget_change_percent'].'%)' : ''),
                (string) ($verdict['reason'] ?? $basis['rule'] ?? ''),
                $basis,
                'This is the existing verdict action, not a separate estimate.',
                is_string($verdict['confidence'] ?? null) ? (string) $verdict['confidence'] : 'medium',
                'high',
            );
        }

        return array_merge($recommendations, AdSetOptimizationCards::recommendations($adSetOptimization, 'hold', $audienceContext, $platform));
    }

    /**
     * @param  array<string, mixed>  $supporting
     * @return array<string, mixed>
     */
    private function recommendation(string $action, string $why, array $supporting, string $impact, string $confidence, string $priority): array
    {
        return [
            'action' => $action,
            'why' => $why,
            'supporting_data' => $supporting,
            'expected_impact' => $impact,
            'confidence' => $confidence,
            'priority' => $priority,
        ];
    }

    private function note(string $focus): string
    {
        if ($focus === 'creative') {
            return 'Focus is creative. Print the campaign name in bold. Do not use a markdown heading. Do not print the campaign stats table, budget recommendation, health, or verdict. Answer only from ads and creatives. For each ad, print its name and status. For each creative, print its headline, primary text, and call to action. Do not print creative ids. Delivery spend, clicks, and impressions are campaign totals, not per creative, so do not name a winning creative from those totals. Add a suggestion only when the returned ad text shows a concrete problem, and include the reason quoting that text. If nothing shows a problem, do not add a filler suggestion.';
        }

        if ($focus === 'landing') {
            return 'Focus is landing. Print the campaign name in bold. Do not use a markdown heading. Do not print the campaign stats table, budget recommendation, health, or verdict. Answer only from landing_pages. For each page, print the URL once, the title, the headings, and the text that relates to the campaign objective. Add a suggestion only when that text conflicts with the objective or the ad text, and include the reason quoting it. If nothing conflicts, do not add a filler suggestion. Do not invent page speed.';
        }

        if ($focus === 'targeting') {
            return 'Focus is targeting. Print the campaign name in bold. Do not use a markdown heading. Do not print the campaign stats table, budget recommendation, health, or verdict. Answer from ad_set_optimization for each ad set: audience type, countries, age, genders, interests, included audiences, placement labels, and devices. Skip a field that is null. Do not invent audience size, overlap, or an optimization event. Do not change the campaign verdict. Add a suggestion only when a returned value does not fit the objective, and include the reason quoting that value. If nothing shows a problem, do not add a filler suggestion.';
        }

        return $this->performanceNote();
    }

    private function previousTo(string $from): string
    {
        return Carbon::parse($from)->subDay()->toDateString();
    }

    private function previousFrom(string $from, string $to): string
    {
        $length = Carbon::parse($from)->diffInDays(Carbon::parse($to)) + 1;

        return Carbon::parse($from)->subDays($length)->toDateString();
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function dailyRows(string $platform, string $campaignId, string $from, string $to): array
    {
        $result = $this->query->run([
            'dataset' => 'stats_campaign_daily',
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'group_by' => 'stat_date',
            'limit' => 100,
        ]);
        $rows = (($result['ok'] ?? false) === true && is_array($result['rows'] ?? null)) ? $result['rows'] : [];
        $offsite = $this->offsiteConversions($platform, $campaignId, $from, $to);
        $out = [];

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

            $date = $row['stat_date'] ?? $row['date'] ?? null;

            if (! is_string($date) || trim($date) === '') {
                continue;
            }

            $day = Carbon::parse($date)->toDateString();
            $conversions = array_key_exists('conversions', $row) ? (float) $row['conversions'] : 0;

            if ($offsite !== null && array_key_exists($day, $offsite)) {
                $conversions = $offsite[$day];
            }

            $out[] = [
                'date' => $day,
                'spend' => (float) ($row['spend'] ?? 0),
                'impressions' => (int) ($row['impressions'] ?? 0),
                'clicks' => (int) ($row['clicks'] ?? 0),
                'outbound_clicks' => array_key_exists('outbound_clicks', $row) ? (int) $row['outbound_clicks'] : null,
                'conversions' => $conversions,
            ];
        }

        return $out;
    }

    /**
     * @param  list<array<string, mixed>>  $ads
     * @return list<array<string, mixed>>
     */
    private function adDeliveryRows(string $platform, string $campaignId, string $from, string $to, array $ads): array
    {
        $result = $this->query->run([
            'dataset' => 'stats_daily',
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'group_by' => 'ad_id',
            'limit' => 25,
        ]);
        $rows = (($result['ok'] ?? false) === true && is_array($result['rows'] ?? null)) ? $result['rows'] : [];
        $names = [];

        foreach ($ads as $ad) {
            $id = trim((string) ($ad['ad_id'] ?? ''));

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

            $names[$id] = [
                'name' => $ad['name'] ?? null,
                'status' => $ad['status'] ?? null,
            ];
        }

        $out = [];

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

            $id = trim((string) ($row['ad_id'] ?? ''));
            $out[] = [
                'ad_id' => $id,
                'name' => $names[$id]['name'] ?? ($id !== '' ? $id : 'Ad'),
                'status' => $names[$id]['status'] ?? null,
                'spend' => (float) ($row['spend'] ?? 0),
                'clicks' => (int) ($row['clicks'] ?? 0),
                'outbound_clicks' => array_key_exists('outbound_clicks', $row) ? (int) $row['outbound_clicks'] : null,
                'conversions' => array_key_exists('conversions', $row) ? (float) $row['conversions'] : 0,
            ];
        }

        return $out;
    }

    /**
     * @return array<string, float>
     */
    private function actionCounts(string $platform, string $campaignId, string $from, string $to): array
    {
        $result = $this->query->run([
            'dataset' => 'conversions_daily',
            'platform' => $platform,
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'group_by' => 'action_name',
            'limit' => 25,
        ]);
        $rows = (($result['ok'] ?? false) === true && is_array($result['rows'] ?? null)) ? $result['rows'] : [];
        $counts = [];

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

            $name = trim((string) ($row['action_name'] ?? ''));

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

            $counts[$name] = ($counts[$name] ?? 0) + (float) ($row['conversions'] ?? 0);
        }

        return $counts;
    }

    private function performanceNote(): string
    {
        return 'Print the campaign name in bold. Do not use a markdown heading. State the campaign id and the from and to dates in that opening sentence. Then print analysis.table as one markdown table with columns Metric and Result, one row per pair, in that order. Do not add Platform, Objective, or Region rows to this table. Do not print ROI sales in this table. Conversions is delivery.conversions from the Whale daily stats. Subscriptions is roi.subscriptions. ROI conversions is roi.conversions from the ROI table. Do not add it to Conversions. Do not skip a row that analysis.table includes. Do not use the roi numbers to change the verdict or the health label. Do not change the verdict or the health label. Do not replace analysis.lines.budget with verdict.basis. After the table, print each analysis.lines value that is not null, in this order: working, problem, budget, landing, creatives, fatigue, ads, event, next. Copy those sentences. Do not recalculate a number and do not add a number that is not in them. The budget action is analysis.lines.budget. Print each returned recommendations item with its action and why only when that item does not tell the reader to increase, decrease, or scale the budget. Ad set improvement items are in that same recommendations list. Print one card for each ad_set_optimization.cards entry, the same way a creative card and a landing page card are printed: the ad set name, the action, the why, then each field label and its text. Print the ad set name with the action and why. Name the area, the change, and the reason in each recommendation. Do not give a vague suggestion such as "improve the creative" or "optimize the landing page" without the number or text in that line. Do not print every day. Do not print creative ids. Print the landing URL once, from analysis.landing.url, and only inside the landing line. When the user asks about an ad set, its audience, placements, device, age, gender, bid, or budget, answer from ad_set_optimization for that ad set. A null delivery field means the number is not on file. Do not turn it into zero. Do not invent audience size, overlap, the optimization event, or country delivery by ad set. Do not change the campaign verdict from an ad set row or from an ad set recommendation.';
    }

    private function healthLabel(?string $verdict, array $sales): string
    {
        $mapped = CampaignDecisionVerdict::tryFrom((string) $verdict);

        return match ($mapped) {
            CampaignDecisionVerdict::ScaleUp => 'Excellent',
            CampaignDecisionVerdict::Maintain => 'Healthy',
            CampaignDecisionVerdict::Pause, CampaignDecisionVerdict::DecreaseBudget => 'Critical',
            CampaignDecisionVerdict::Watch, CampaignDecisionVerdict::Learning => 'Needs Optimization',
            default => (float) ($sales['sales'] ?? 0) <= 0 && (float) ($sales['spend'] ?? 0) > 0
                ? 'Needs Optimization'
                : 'Healthy',
        };
    }

    private function isSalesObjective(string $objective): bool
    {
        foreach (['SALE', 'PURCHASE', 'CONVERSION'] as $needle) {
            if (str_contains($objective, $needle)) {
                return true;
            }
        }

        return false;
    }

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

        return round((float) $value, 2);
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    /**
     * @param  array<string, mixed>  $row
     */
    private function deliveryClicks(array $row): int
    {
        if (array_key_exists('link_clicks', $row)) {
            return (int) $row['link_clicks'];
        }

        return (int) ($row['clicks'] ?? 0);
    }

    /**
     * @param  list<string>  $columns
     * @param  list<string>  $candidates
     */
    private function pick(array $columns, array $candidates): ?string
    {
        foreach ($candidates as $candidate) {
            if (in_array($candidate, $columns, true)) {
                return $candidate;
            }
        }

        return null;
    }
}
