<?php

namespace App\Library\CampaignDecision;

use Illuminate\Support\Carbon;

/**
 * ChatGPT-style performance brief: metrics, scaling stance, insights, next actions.
 * Built from the decision snapshot (platform + internal). List uses short_lines; detail uses the full shape.
 */
class CampaignPerformanceBrief
{
    public static function platformName(array $snapshot): string
    {
        $platform = strtolower((string) ($snapshot['platform'] ?? 'meta'));

        return match ($platform) {
            'google' => 'Google',
            'linkedin' => 'LinkedIn',
            default => 'Meta',
        };
    }

    private const MAX_ACTION_LENGTH = 560;

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     version: int,
     *     window_label: string,
     *     internal_window_label: ?string,
     *     verdict: string,
     *     verdict_label: string,
     *     scaling_stance: string,
     *     primary_bottleneck: string,
     *     primary_lever: ?string,
     *     metrics: list<array{label: string, value: string, group: string}>,
     *     insights: list<string>,
     *     next_actions: list<string>,
     *     summary: string,
     *     data_notes: list<string>,
     *     short_lines: list<string>
     * }
     */
    public static function fromSnapshot(array $snapshot, ?string $status = null): array
    {
        $verdict = CampaignDecisionVerdict::tryFromStored($status)
            ?? CampaignDecisionVerdict::tryFromStored(is_string($snapshot['verdict'] ?? null) ? $snapshot['verdict'] : null)
            ?? CampaignDecisionVerdict::InsufficientData;

        $diagnosis = is_array($snapshot['marketing_diagnosis'] ?? null) ? $snapshot['marketing_diagnosis'] : [];
        $primaryLever = is_string($diagnosis['primary_lever'] ?? null) ? $diagnosis['primary_lever'] : null;
        $budget = CampaignBudgetRecommendation::fromStored($verdict->value, $snapshot);
        $metrics = self::metrics($snapshot);
        $dataNotes = self::dataNotes($snapshot);
        $insights = self::insights($snapshot, $verdict, $diagnosis);
        $nextActions = self::nextActions($verdict, $diagnosis, $budget, $dataNotes, $snapshot);
        $facts = self::funnelFacts($snapshot, $diagnosis);
        $scalingStance = in_array($verdict, [
            CampaignDecisionVerdict::Learning,
            CampaignDecisionVerdict::InsufficientData,
            CampaignDecisionVerdict::Watch,
        ], true)
            ? self::issueStatement($facts)
            : self::scalingStance($verdict, $budget);
        $bottleneck = self::bottleneckLabel($primaryLever, $verdict, $facts);
        $summary = self::summary($nextActions, $facts);
        $windowLabel = self::windowLabel($snapshot);
        $internalWindow = self::internalWindowLabel($snapshot);

        $objective = self::objectiveLabel($snapshot);
        $shortLines = array_values(array_filter(
            $nextActions,
            fn (string $line): bool => $line !== '' && $line !== $scalingStance,
        ));

        return [
            'version' => 21,
            'allowed_moves' => self::allowedMoves($facts, $verdict),
            'page_heading_saved' => self::pageHeadingSaved($facts),
            'window_label' => $windowLabel,
            'internal_window_label' => $internalWindow,
            'objective' => $objective,
            'verdict' => $verdict->value,
            'verdict_label' => $verdict->label(),
            'issue' => self::issueStatement($facts),
            'scaling_stance' => $scalingStance,
            'primary_bottleneck' => $bottleneck,
            'primary_lever' => $primaryLever,
            'metrics' => $metrics,
            'insights' => $insights,
            'next_actions' => $nextActions,
            'summary' => $summary,
            'data_notes' => $dataNotes,
            'short_lines' => $shortLines,
        ];
    }

    /**
     * PHP-treated campaign: objective, five levels, one bottleneck.
     * The LLM writes the buyer suggestion from this, not from a raw snapshot dump.
     *
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     objective: string,
     *     kind: string,
     *     primary_metric: string,
     *     bottleneck: string,
     *     bottleneck_label: string,
     *     lever: string,
     *     levels: array{tracking: string, traffic: string, funnel: string, economics: string, stability: string},
     *     plan: list<string>
     * }
     */
    public static function campaignReview(array $snapshot, ?string $status = null): array
    {
        $verdict = CampaignDecisionVerdict::tryFromStored($status)
            ?? CampaignDecisionVerdict::tryFromStored(is_string($snapshot['verdict'] ?? null) ? $snapshot['verdict'] : null)
            ?? CampaignDecisionVerdict::InsufficientData;
        $diagnosis = is_array($snapshot['marketing_diagnosis'] ?? null) ? $snapshot['marketing_diagnosis'] : [];
        $facts = self::funnelFacts($snapshot, $diagnosis);
        $objective = self::objectiveLabel($snapshot);
        $break = (string) ($facts['break'] ?? '');
        $strategyBreak = (string) data_get($snapshot, 'performance_strategy.broken_step', '');
        $deliveryState = (string) data_get($snapshot, 'performance_strategy.delivery_state', '');
        if ($strategyBreak === 'paused' || $deliveryState === 'paused') {
            $break = 'paused';
        } elseif ($strategyBreak === 'archived' || $deliveryState === 'archived') {
            $break = 'archived';
        } elseif (
            ($strategyBreak === 'delivery' || $deliveryState === 'not_delivering')
            && in_array($break, ['delivery', 'awareness', 'thin', 'tracking', ''], true)
        ) {
            $break = 'delivery';
        } elseif ($strategyBreak === 'tracking' && ! in_array((string) ($facts['kind'] ?? ''), ['traffic', 'awareness'], true)) {
            $break = 'tracking';
        }
        $lever = self::reviewLever($break);
        $primaryMetric = self::primaryMetricName($facts);
        $levels = [
            'tracking' => self::reviewTrackingLevel($facts),
            'traffic' => self::trafficQualityLine($facts),
            'funnel' => self::issueStatement($facts),
            'economics' => self::reviewEconomicsLevel($facts),
            'stability' => self::reviewStabilityLevel($facts),
        ];

        $plan = array_values(array_filter([
            'Objective is '.($objective !== '' ? $objective : 'not set').'. Primary metric is '.$primaryMetric.'.',
            $levels['funnel'],
            $break === 'tracking' && $levels['tracking'] !== ''
                ? $levels['tracking']
                : ($levels['traffic'] !== '' ? $levels['traffic'] : $levels['economics']),
        ]));

        return [
            'objective' => $objective,
            'kind' => (string) ($facts['kind'] ?? 'results'),
            'primary_metric' => $primaryMetric,
            'bottleneck' => $break,
            'bottleneck_label' => self::bottleneckLabel($lever, $verdict, $facts),
            'lever' => $lever,
            'levels' => $levels,
            'plan' => array_slice($plan, 0, 3),
        ];
    }

    /**
     * The three marketing levers only apply when the bottleneck is creative, page, or scale.
     *
     * @param  array<string, mixed>  $diagnosis
     * @param  array<string, mixed>  $review
     * @return array<string, mixed>
     */
    public static function alignMarketingDiagnosis(array $diagnosis, array $review): array
    {
        $lever = is_string($review['lever'] ?? null) ? (string) $review['lever'] : 'hold';
        $diagnosis['primary_lever'] = $lever;
        $plan = is_array($review['plan'] ?? null) ? $review['plan'] : [];

        if ($plan !== []) {
            $diagnosis['plan'] = $plan;
            $diagnosis['summary'] = implode(' ', $plan);
        }

        return $diagnosis;
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function primaryMetricName(array $facts): string
    {
        return match ((string) ($facts['kind'] ?? 'results')) {
            'subscriptions' => 'cost per paid subscriber',
            'leads' => 'cost per qualified lead',
            'installs' => 'cost per install',
            'sales' => 'cost per result and ROAS',
            'traffic' => 'qualified visits at acceptable cost',
            'awareness' => 'delivery quality (CPM, CTR, reach)',
            default => 'the objective result',
        };
    }

    private static function reviewLever(string $break): string
    {
        return match ($break) {
            'creative' => 'improve_creative',
            'page' => 'fix_landing_page',
            'scale' => 'spend_more',
            default => 'hold',
        };
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function reviewTrackingLevel(array $facts): string
    {
        $platform = (float) ($facts['platform_conversions'] ?? 0);
        $internal = (float) ($facts['internal_results'] ?? 0);
        $platformName = (string) ($facts['platform_name'] ?? 'Meta');

        if (in_array((string) ($facts['kind'] ?? ''), ['traffic', 'awareness'], true)) {
            return 'Tracking: this campaign is judged on landing page views and delivery, not Meta conversions versus internal leads.';
        }

        if (($facts['download_install_funnel'] ?? false) === true) {
            $rate = $platform > 0 ? number_format(100 * $internal / $platform, 1).'%' : 'n/a';

            return 'Tracking: Meta conversions are downloads ('.self::int((int) $platform).') and internal records are installs ('.self::decimal($internal).', '.$rate.' install rate). That is the funnel, not a broken pixel.';
        }

        if ($platform > 0 && $internal + 0.5 < $platform) {
            return 'Tracking: '.$platformName.' reports '.self::int((int) $platform).' conversions and internal records show '.self::decimal($internal).'. Check the tracking tag before changing the ad or the page.';
        }

        $spend = (float) ($facts['spend'] ?? 0);
        $landingViews = (int) ($facts['landing_views'] ?? 0);
        $results = (float) ($facts['results'] ?? 0);

        if ($results <= 0 && $spend > 0 && ($landingViews > 0 || (int) ($facts['clicks'] ?? 0) > 0)) {
            return 'Tracking: spent $'.number_format($spend, 2).' with '.$landingViews.' landing page views and 0 optimization results. Check Events Manager and a test conversion before changing ads or the page.';
        }

        if ($platform <= 0 && $internal <= 0) {
            return 'Tracking: no platform or internal conversions are on file yet.';
        }

        return 'Tracking: '.$platformName.' and internal counts are close enough to use.';
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function reviewEconomicsLevel(array $facts): string
    {
        $status = self::performanceStatus($facts);

        return 'Economics: '.$status.'. '.self::performanceWhy($facts, $status);
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function reviewStabilityLevel(array $facts): string
    {
        if (($facts['thin'] ?? false) === true) {
            return 'Stability: too little delivery to judge.';
        }

        $days = (int) ($facts['evidence_days'] ?? 0);
        $lag = ($facts['break'] ?? '') === 'lag' || (($facts['internal_results'] ?? 0) <= 0 && (float) ($facts['spend'] ?? 0) > 0);

        return 'Stability: '.$days.'-day window'
            .($lag ? '; internal results usually arrive a few days after spend' : '')
            .'. Do not make a major change from one day of data.';
    }

    /**
     * Prefer a stored brief; otherwise build from the snapshot/row fields.
     *
     * @param  array<string, mixed>  $row
     * @param  array<string, mixed>|null  $snapshot
     * @return array<string, mixed>
     */
    public static function forDisplay(array $row, ?array $snapshot = null): array
    {
        $snapshot = $snapshot ?? (is_array($row['brief_snapshot'] ?? null) ? $row['brief_snapshot'] : []);
        $stored = is_array($row['brief'] ?? null) ? $row['brief'] : data_get($snapshot, 'brief');

        if ($snapshot === [] && is_array($row['snapshot'] ?? null)) {
            $snapshot = $row['snapshot'];
        }

        $merged = $snapshot;
        if (! isset($merged['verdict']) && is_string($row['status'] ?? null)) {
            $merged['verdict'] = $row['status'];
        }
        if (! isset($merged['last_7_days']) && isset($row['spend_7d'])) {
            $merged['last_7_days'] = [
                'spend' => $row['spend_7d'] ?? 0,
                'clicks' => $row['clicks_7d'] ?? 0,
                'impressions' => $row['impressions_7d'] ?? 0,
                'cpc' => $row['cpc_7d'] ?? null,
                'ctr' => $row['ctr_7d'] ?? null,
                'conversions' => $row['platform_conversions_7d'] ?? 0,
                'conversion_value' => $row['platform_conversion_value_7d'] ?? 0,
            ];
        }
        if (! isset($merged['affiliate']) && ($row['affiliate_matched'] ?? false)) {
            $merged['affiliate'] = [
                'matched' => true,
                '7d' => [
                    'orders' => $row['affiliate_orders_7d'] ?? 0,
                    'clicks' => $row['affiliate_clicks_7d'] ?? 0,
                    'sum_cpc' => $row['affiliate_sum_cpc_7d'] ?? 0,
                    'net_revenue' => $row['affiliate_net_revenue_7d'] ?? 0,
                ],
            ];
        }
        if (! isset($merged['roi_performance']) && is_array($row['roi_performance'] ?? null)) {
            $merged['roi_performance'] = $row['roi_performance'];
        }
        if (! isset($merged['marketing_diagnosis']) && (isset($row['marketing_plan']) || isset($row['marketing_lever']))) {
            $merged['marketing_diagnosis'] = [
                'plan' => $row['marketing_plan'] ?? [],
                'primary_lever' => $row['marketing_lever'] ?? null,
                'summary' => $row['marketing_summary'] ?? null,
            ];
        }
        $liveObjective = is_string($row['objective'] ?? null) ? trim($row['objective']) : '';
        $profile = is_array($merged['campaign_profile'] ?? null) ? $merged['campaign_profile'] : [];
        $storedObjective = is_string($profile['objective'] ?? null) ? trim($profile['objective']) : '';

        if ($storedObjective === '' && $liveObjective !== '') {
            $profile['objective'] = $liveObjective;
        }

        if ($profile === [] && is_string($row['name'] ?? null) && $row['name'] !== '') {
            $profile['name'] = $row['name'];
        }

        if ($profile !== []) {
            $merged['campaign_profile'] = $profile;
        }

        if (! is_array($merged['performance_strategy'] ?? null)) {
            $merged['performance_strategy'] = CampaignPerformanceStrategy::fromSnapshot(
                $merged,
                is_string($row['status'] ?? null) ? $row['status'] : null,
            );
        }

        $liveLabel = self::objectiveLabel($merged);
        $storedLabel = is_array($stored) && is_string($stored['objective'] ?? null) ? trim($stored['objective']) : '';
        $storedMatchesLive = $liveLabel === '' || strcasecmp($storedLabel, $liveLabel) === 0;

        if (is_array($stored) && (int) ($stored['version'] ?? 0) >= 21 && is_array($stored['short_lines'] ?? null) && $storedMatchesLive) {
            return $stored;
        }

        return self::fromSnapshot($merged, is_string($row['status'] ?? null) ? $row['status'] : null);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<array{label: string, value: string, group: string}>
     */
    private static function metrics(array $snapshot): array
    {
        $platform = self::platformWindow($snapshot);
        $delivery = is_array(data_get($snapshot, 'performance_strategy.delivery'))
            ? data_get($snapshot, 'performance_strategy.delivery')
            : (is_array(data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery'))
                ? data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery')
                : []);
        $linkClicks = $platform['link_clicks'] ?? $delivery['link_clicks_7d'] ?? null;
        $ctr = $platform['ctr'];
        if (($delivery['ctr_percent'] ?? null) !== null) {
            $ctr = ((float) $delivery['ctr_percent']) / 100;
        } elseif ($linkClicks !== null && $platform['impressions'] > 0) {
            $ctr = ((int) $linkClicks) / $platform['impressions'];
        }

        $rows = [
            ['label' => 'Spend', 'value' => self::money($platform['spend']), 'group' => 'platform'],
            ['label' => 'Impressions', 'value' => self::int($platform['impressions']), 'group' => 'platform'],
            ['label' => 'Link clicks', 'value' => self::int((int) ($linkClicks ?? $platform['clicks'])), 'group' => 'platform'],
            ['label' => 'CTR', 'value' => self::pct($ctr), 'group' => 'platform'],
            ['label' => 'CPC', 'value' => self::moneyOrDash($platform['cpc']), 'group' => 'platform'],
            ['label' => 'Platform conversions', 'value' => self::int($platform['conversions']), 'group' => 'platform'],
        ];

        foreach (
            [
                'cpm' => 'CPM',
                'reach' => 'Reach',
                'frequency' => 'Frequency',
                'landing_page_views' => 'Landing page views',
                'cost_per_lpv' => 'Cost per LPV',
            ] as $key => $label
        ) {
            $value = $delivery[$key] ?? null;
            if ($value === null || ! is_numeric($value)) {
                continue;
            }

            $rows[] = [
                'label' => $label,
                'value' => match ($key) {
                    'reach', 'landing_page_views' => self::int((int) $value),
                    'frequency' => number_format((float) $value, 2),
                    default => self::money((float) $value),
                },
                'group' => 'platform',
            ];
        }

        $learning = data_get($snapshot, 'performance_strategy.meta_learning_stage')
            ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.learning_status')
            ?? data_get($snapshot, 'campaign_profile.platform_learning_label');
        if (is_string($learning) && $learning !== '') {
            $platformName = self::platformName($snapshot);
            $rows[] = ['label' => $platformName.' learning', 'value' => $learning, 'group' => 'platform'];
        }

        $outcome = self::outcomeWindow($snapshot);

        if ($outcome !== null) {
            $rows[] = ['label' => 'Internal orders', 'value' => self::decimal($outcome['orders']), 'group' => 'internal'];
            $rows[] = ['label' => 'Internal revenue', 'value' => self::money($outcome['revenue']), 'group' => 'internal'];
            $rows[] = ['label' => 'ROAS', 'value' => self::ratio($outcome['roas']), 'group' => 'internal'];
            $rows[] = ['label' => 'CPA', 'value' => self::moneyOrDash($outcome['cpa']), 'group' => 'internal'];
            if (($outcome['revenue_source'] ?? null) === 'roi_dashboard') {
                foreach (['subscriptions', 'conversions', 'leads', 'installs', 'bookings'] as $key) {
                    if (($outcome[$key] ?? 0) > 0) {
                        $rows[] = [
                            'label' => ucfirst(str_replace('_', ' ', $key)),
                            'value' => self::decimal($outcome[$key]),
                            'group' => 'internal',
                        ];
                    }
                }
            }
        }

        return $rows;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $diagnosis
     * @return list<string>
     */
    private static function insights(
        array $snapshot,
        CampaignDecisionVerdict $verdict,
        array $diagnosis,
    ): array {
        $facts = self::funnelFacts($snapshot, $diagnosis);
        $objective = self::objectiveLabel($snapshot);
        $goal = (string) ($facts['goal'] ?? self::goalNoun($objective));
        $issueInStance = in_array($verdict, [
            CampaignDecisionVerdict::Learning,
            CampaignDecisionVerdict::InsufficientData,
            CampaignDecisionVerdict::Watch,
        ], true);
        $lines = [
            $issueInStance
                ? 'Health: '.self::healthLabel($facts).'.'
                : 'Health: '.self::healthLabel($facts).'. '.self::issueStatement($facts),
            self::performanceMetricsLine($facts, $objective),
        ];

        if ($objective === '' && ($facts['kind'] ?? '') === 'results' && ($facts['thin'] ?? false) !== true) {
            $lines[1] .= ' Objective is not set, so this is not cost per lead, cost per subscriber, or revenue per visit.';
        } else {
            $objectiveLine = self::objectiveMetricLine($facts, $objective);

            if ($objectiveLine !== '') {
                $lines[] = $objectiveLine;
            }
        }

        $trafficLine = self::trafficQualityLine($facts);

        if ($trafficLine !== '') {
            $lines[] = $trafficLine;
        }

        $platformName = self::platformName($snapshot);
        $outcome = self::outcomeWindow($snapshot);
        $kind = (string) ($facts['kind'] ?? '');
        $scoresOnDelivery = in_array($kind, ['traffic', 'awareness'], true)
            || ($facts['download_install_funnel'] ?? false) === true;

        if ($outcome === null) {
            $lines[] = 'Internal outcomes are not matched, so '.$goal.' are judged from '.$platformName.' delivery and a cost per '.$goal.' is not invented.';
        } elseif (! $scoresOnDelivery
            && ($outcome['orders'] ?? 0) <= 0 && ($outcome['revenue'] ?? 0) <= 0
            && ($outcome['leads'] ?? 0) <= 0 && ($outcome['subscriptions'] ?? 0) <= 0
            && ($outcome['conversions'] ?? 0) <= 0) {
            $lines[] = $platformName.' is spending, but our own records for this period are still at zero. Those records arrive a few days after the spend.';
        }

        if ($verdict === CampaignDecisionVerdict::DataIssue && ! self::containsSimilar($lines, 'Fix data or sync before changing budget or creatives.')) {
            $lines[] = 'Fix data or sync before changing budget or creatives.';
        }

        $strategy = is_array($snapshot['performance_strategy'] ?? null) ? $snapshot['performance_strategy'] : [];
        $placementLine = PlacementPublisherCosts::mustSay(
            is_array($strategy['placement_cost'] ?? null)
                ? $strategy['placement_cost']
                : PlacementPublisherCosts::fromSnapshot($snapshot, (string) ($facts['kind'] ?? 'results')),
        );
        if ($placementLine !== null) {
            $lines[] = $placementLine;
        }
        if (($strategy['tracking_mismatch'] ?? false) === true) {
            $lines[] = 'Tracking mismatch: '.$platformName.' shows '.self::decimal($strategy['platform_results'] ?? 0)
                .' results and our records show '.self::decimal($strategy['internal_results'] ?? 0)
                .'. Check the pixel, Conversions API, form, or CRM before rewriting the page.';
        }
        if (($strategy['creative_brand_mismatch'] ?? false) === true) {
            $lines[] = 'Creative brand mismatch: at least one ad headline does not match this campaign. Fix that ad before restarting spend.';
        }
        if (($strategy['delivery_state'] ?? '') === 'paused') {
            $lines[] = 'Campaign is paused on '.$platformName.'. Resume it before changing budget, bid, or creatives.';
        }
        if (($strategy['delivery_state'] ?? '') === 'archived') {
            $lines[] = 'This campaign is archived on '.$platformName.'. Advice on this row is not for the live copy.';
        }
        if (($strategy['delivery_state'] ?? '') === 'not_delivering') {
            $cap = data_get($strategy, 'delivery.bid_amount');
            $bid = (string) data_get($strategy, 'delivery.bid_strategy', '');
            if (str_contains(strtoupper($bid), 'COST_CAP') || str_contains(strtoupper($bid), 'BID_CAP')) {
                $lines[] = 'Not delivering: a cost cap'
                    .(is_numeric($cap) ? ' of $'.number_format((float) $cap, 2) : '')
                    .' is blocking spend. Switch to lowest cost or raise the cap before raising budget.';
            } else {
                $lines[] = 'Not delivering: prefer lowest cost to restart. Check the bid limit and audience size. Do not assume ads are paused or payment failed.';
            }
        }

        return array_values(array_slice(array_unique(array_values(array_filter($lines))), 0, 7));
    }

    /**
     * PDF title status, without repeating the metric table.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function healthLabel(array $facts): string
    {
        $spend = (float) ($facts['spend'] ?? 0);
        $results = (float) ($facts['results'] ?? 0);
        $break = (string) ($facts['break'] ?? '');

        if (($facts['thin'] ?? false) === true || $break === 'lag' || ($spend < 20 && $results <= 0 && ! in_array($break, ['creative', 'tracking'], true))) {
            return 'Not yet ready to judge';
        }

        if ($break === 'tracking' || ($break === 'traffic' && ($facts['landing_views'] ?? null) === null)) {
            return 'Not yet ready to judge';
        }

        if (in_array($break, ['page', 'creative', 'auction', 'visit', 'cost', 'delivery'], true) || (($facts['past_early'] ?? false) === true && $results <= 0)) {
            return 'Underperforming';
        }

        if ($break === 'scale' || $results > 0) {
            return 'Healthy';
        }

        return 'Not yet ready to judge';
    }

    /**
     * One plain sentence for the broken step. Numbers stay in the metric table.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function issueStatement(array $facts): string
    {
        $goal = (string) ($facts['goal'] ?? 'results');
        $break = (string) ($facts['break'] ?? '');
        $platformName = (string) ($facts['platform_name'] ?? 'Meta');
        $line = match ($break) {
            'tracking' => 'The issue is tracking. '.$platformName.'’s count and our own count do not match, so the result is not trustworthy yet.',
            'visit' => 'The issue is the click. People click the ad, but most of those clicks never open the landing page.',
            'auction' => 'The issue is the click price. People are clicking the ad, and each click costs more than our internal target. The ad and the page are not the problem.',
            'lag' => 'The internal count is not in yet. Those records arrive a few days after the spend, so this is not a landing-page failure yet.',
            'delivery' => 'The issue is delivery. This campaign is not spending enough in this window to learn.',
            'paused' => 'This campaign is paused on Meta. Do not treat it as a live delivery problem.',
            'archived' => 'This campaign is deleted or archived on Meta. Do not change bid, budget, or creatives on this row.',
            'awareness' => 'Delivery is healthy. Nothing in this window needs a change.',
            'traffic' => 'The issue is missing landing-page views. This campaign is meant to buy visits, and those visits are not in this window.',
            'visits' => 'There is no landing-page failure. This campaign is buying visits, and the clicks are opening the page.',
            'creative' => (int) ($facts['clicks'] ?? 0) === 0
                ? 'The issue is the ad. People see it, and 0 clicks are coming through.'
                : 'The issue is the ad. People see it, and almost no clicks are coming through.',
            'page' => 'The issue is the landing page. People click the ad, and the page is not turning them into '.$goal.'.',
            'cost' => 'The issue is the cost. '.ucfirst($goal).' are coming in, and each one costs more than this campaign can afford.',
            'scale' => 'There is no broken step. '.ucfirst($goal).' are coming in at an acceptable cost. Keep the ad and the page as they are.',
            'thin' => 'Delivery is too small to name a problem yet.',
            default => 'Delivery is not strong enough to name a problem yet.',
        };

        if (($facts['past_early'] ?? false) === true && ! in_array($break, ['tracking', 'lag', 'awareness'], true)) {
            $line .= ' '.self::money((float) ($facts['spend'] ?? 0)).' has been spent and there are still '.self::countText((float) ($facts['results'] ?? 0)).' '.$goal.'. That is enough to judge.';
        }

        return $line;
    }

    /**
     * Objective metric plus the traffic-quality formulas the framework lists.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function performanceMetricsLine(array $facts, string $objective): string
    {
        $parts = ['Spend '.self::money((float) ($facts['spend'] ?? 0))];
        $goal = (string) ($facts['goal'] ?? 'results');

        if (is_numeric($facts['ctr_percent'] ?? null)) {
            $ctrName = ($facts['link_clicks'] ?? null) !== null ? 'link-click CTR' : 'CTR';
            $parts[] = $ctrName.' '.number_format((float) $facts['ctr_percent'], 2).'%';
        }

        if (is_numeric($facts['cpc'] ?? null)) {
            $parts[] = 'CPC '.self::money((float) $facts['cpc']);
        }

        if (is_numeric($facts['lpv_rate'] ?? null)) {
            $parts[] = 'LPV rate '.number_format((float) $facts['lpv_rate'] * 100, 0).'%';
        }

        $results = (float) ($facts['results'] ?? 0);
        $parts[] = match ($facts['kind'] ?? 'results') {
            'leads', 'subscriptions', 'installs' => $results > 0 && is_numeric($facts['unit_cost'] ?? null)
                ? self::unitCostLabel((string) $facts['kind']).' '.self::money((float) $facts['unit_cost'])
                : self::countText($results).' '.$goal.', so there is no '.self::unitCostLabel((string) ($facts['kind'] ?? 'results')).' yet',
            'traffic' => self::trafficMetric($facts),
            'sales' => self::salesMetric($facts),
            default => ($objective !== '' ? $objective.': ' : '').self::decimal($results).' '.$goal,
        };

        if (is_numeric($facts['roas'] ?? null) && ($facts['kind'] ?? '') !== 'sales') {
            $parts[] = 'ROAS '.self::ratio((float) $facts['roas']);
        }

        $status = self::performanceStatus($facts);

        return 'Performance: '.$status.'. '.self::performanceWhy($facts, $status).' '.implode('; ', $parts).'.';
    }

    /**
     * PDF section 1: the objective owns the primary metric. CPC is traffic quality.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function objectiveMetricLine(array $facts, string $objective): string
    {
        return match ((string) ($facts['kind'] ?? 'results')) {
            'subscriptions' => 'Objective is subscriptions. Primary metric is cost per paid subscriber, not CPC.',
            'leads' => 'Objective is leads. Primary metric is cost per qualified lead, not CPC.',
            'installs' => 'Objective is app installs. Primary metric is cost per install, not CPC.',
            'sales' => 'Objective is sales. Primary metric is cost per result and ROAS, not CPC.',
            'traffic' => 'Objective is traffic. Primary metric is qualified visits at acceptable cost (CTR, CPC, landing-page views).',
            'awareness' => 'Objective is awareness. Primary metric is delivery quality (CPM, CTR, reach), not purchases.',
            default => $objective === ''
                ? ''
                : 'Objective is '.$objective.'. Judge the campaign on that result, not on a single traffic metric.',
        };
    }

    /**
     * PDF level 2: CTR, CPC, landing-page-view rate, and CPM as traffic quality.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function trafficQualityLine(array $facts): string
    {
        if (($facts['thin'] ?? false) === true) {
            return '';
        }

        $bits = [];
        $ctr = is_numeric($facts['ctr_percent'] ?? null) ? (float) $facts['ctr_percent'] : null;
        $cpc = is_numeric($facts['cpc'] ?? null) ? (float) $facts['cpc'] : null;
        $lpv = is_numeric($facts['lpv_rate'] ?? null) ? (float) $facts['lpv_rate'] : null;
        $cpm = is_numeric($facts['cpm'] ?? null) ? (float) $facts['cpm'] : null;
        $maxCpc = (float) ($facts['max_cpc'] ?? 2);
        $kind = (string) ($facts['kind'] ?? 'results');
        $goal = (string) ($facts['goal'] ?? 'results');
        $conversionKind = in_array($kind, ['leads', 'sales', 'subscriptions', 'installs'], true);

        if ((int) ($facts['clicks'] ?? 0) === 0) {
            $bits[] = '0 clicks';
        } elseif ($ctr !== null) {
            $bits[] = number_format($ctr, 2).'% CTR'.($ctr >= 1.5 ? ' (healthy)' : ($ctr < 0.8 ? ' (weak - ad or audience)' : ''));
        }

        if ($lpv !== null) {
            $bits[] = 'LPV rate '.number_format($lpv * 100, 0).'%'
                .($lpv >= 0.5 ? ' (clicks are landing)' : ' (clicks are not becoming visits)');
        } elseif (
            (int) ($facts['landing_views'] ?? 0) > 0
            && (int) ($facts['link_clicks'] ?? 0) > 0
            && ((int) $facts['landing_views'] / (int) $facts['link_clicks']) >= 0.5
        ) {
            $bits[] = 'clicks are landing';
        }

        if ($cpm !== null) {
            $bits[] = 'CPM '.self::money($cpm);
        }

        if ($cpc !== null && $cpc > $maxCpc) {
            $bits[] = 'CPC '.self::money($cpc).' is above the '.self::money($maxCpc).' traffic-quality line'
                .($conversionKind ? ' - that is auction cost, not the '.$goal.' target' : '');
        } elseif ($cpc !== null) {
            $bits[] = 'CPC '.self::money($cpc);
        }

        if ($bits === []) {
            return '';
        }

        return 'Traffic: '.implode('; ', $bits).'.';
    }

    /**
     * PDF section 3 statuses, using only metrics this snapshot can calculate.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function performanceStatus(array $facts): string
    {
        return self::performanceDecision($facts)['status'];
    }

    /**
     * One short reason for the Performance status on the Insights line.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function performanceWhy(array $facts, string $status): string
    {
        return self::performanceDecision($facts)['why'];
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return array{status: string, why: string}
     */
    private static function performanceDecision(array $facts): array
    {
        $break = (string) ($facts['break'] ?? '');
        $spend = (float) ($facts['spend'] ?? 0);
        $results = (float) ($facts['results'] ?? 0);
        $kind = (string) ($facts['kind'] ?? 'results');

        $goal = (string) ($facts['goal'] ?? 'results');

        if (($facts['thin'] ?? false) === true) {
            return ['status' => 'Inconclusive', 'why' => 'Too few impressions and clicks to decide yet.'];
        }

        if ($break === 'tracking') {
            $platformName = (string) ($facts['platform_name'] ?? 'Meta');

            return ['status' => 'Inconclusive', 'why' => $platformName.'’s count and our own count do not match, so the result is not trustworthy yet.'];
        }

        if ($break === 'delivery') {
            return ['status' => 'Needs attention', 'why' => 'This campaign is not spending enough in this window.'];
        }

        if ($break === 'lag') {
            return ['status' => 'Inconclusive', 'why' => 'Our own results usually arrive a few days after the spend, so wait before judging.'];
        }

        if ($break === 'traffic' && ($facts['landing_views'] ?? null) === null) {
            return ['status' => 'Inconclusive', 'why' => 'Landing-page views are not in this window yet, so visits cannot be judged.'];
        }

        if ($spend < 20 && $results <= 0 && $break !== 'creative') {
            return ['status' => 'Inconclusive', 'why' => 'Less than $20 has been spent and there are no '.$goal.' yet.'];
        }

        if (($facts['past_early'] ?? false) === true) {
            return ['status' => 'Poor', 'why' => self::money($spend).' has been spent and there are still no '.$goal.'.'];
        }

        if (self::economicsMiss($facts)) {
            return ['status' => 'Poor', 'why' => match ($kind) {
                'traffic' => 'Each visit brings in less money than the click costs.',
                'sales' => 'ROAS is below '.self::ratio((float) ($facts['min_roas'] ?? 1.2)).', or CPA is above '.self::money((float) ($facts['max_cpa'] ?? 75)).'.',
                'leads', 'subscriptions', 'installs' => 'Each of the '.$goal.' costs more than '.self::money((float) ($facts['max_cpa'] ?? 75)).'.',
                default => 'The '.$goal.' cost more than this campaign can afford.',
            }];
        }

        if (in_array($break, ['page', 'creative', 'auction', 'visit'], true)) {
            return ['status' => 'Needs attention', 'why' => match ($break) {
                'page' => 'People open the page, and it is not turning them into '.$goal.'.',
                'creative' => 'People see the ad, and almost nobody clicks.',
                'auction' => in_array($kind, ['leads', 'sales', 'subscriptions', 'installs'], true)
                    ? 'Traffic quality is expensive (CPC above '.self::money((float) ($facts['max_cpc'] ?? 2)).'), but '.$goal.' is the objective metric.'
                    : 'Each click costs more than '.self::money((float) ($facts['max_cpc'] ?? 2)).'.',
                default => 'People click the ad, but most of those clicks never open the page.',
            }];
        }

        if (self::trafficQualityWeak($facts)) {
            return ['status' => 'Needs attention', 'why' => 'Click rate, click price, or landing-page views look weak for this spend.'];
        }

        if ($kind === 'traffic' && $results > 0) {
            return ['status' => 'Good', 'why' => 'People are visiting at an acceptable click cost. This campaign is judged on landing-page views, not revenue.'];
        }

        if ($results > 0 && self::economicsMet($facts)) {
            return ['status' => 'Good', 'why' => 'The campaign is getting '.$goal.' at a cost this budget can afford.'];
        }

        if ($results <= 0 && $spend >= 20) {
            return ['status' => 'Needs attention', 'why' => self::money($spend).' has been spent and there are still no '.$goal.'.'];
        }

        if ($kind === 'awareness') {
            return ['status' => 'Inconclusive', 'why' => 'The ads are delivering, and this objective has no cost-per-result target to call the run good or poor.'];
        }

        return ['status' => 'Inconclusive', 'why' => 'We do not have enough of the right numbers yet to call this good or poor.'];
    }

    /**
     * Target CPA, ROAS, or revenue per visit is worse than the configured line.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function economicsMiss(array $facts): bool
    {
        $maxCpa = (float) ($facts['max_cpa'] ?? 75);
        $minRoas = (float) ($facts['min_roas'] ?? 1.2);
        $unitCost = is_numeric($facts['unit_cost'] ?? null) ? (float) $facts['unit_cost'] : null;
        $roas = is_numeric($facts['roas'] ?? null) ? (float) $facts['roas'] : null;
        $cpc = is_numeric($facts['cpc'] ?? null) ? (float) $facts['cpc'] : null;
        $revenuePerSession = is_numeric($facts['revenue_per_session'] ?? null) ? (float) $facts['revenue_per_session'] : null;
        $revenue = is_numeric($facts['revenue'] ?? null) ? (float) $facts['revenue'] : null;

        return match ($facts['kind'] ?? 'results') {
            'subscriptions', 'leads', 'installs' => $unitCost !== null && $unitCost > $maxCpa,
            'traffic' => $revenue !== null && $revenue > 0 && $revenuePerSession !== null && $cpc !== null && $revenuePerSession < $cpc,
            'sales' => ($roas !== null && $roas < $minRoas) || ($unitCost !== null && $unitCost > $maxCpa),
            default => $roas !== null && $roas < $minRoas,
        };
    }

    /**
     * The objective metric is present and inside the configured line.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function economicsMet(array $facts): bool
    {
        if (self::economicsMiss($facts)) {
            return false;
        }

        return match ($facts['kind'] ?? 'results') {
            'subscriptions', 'leads', 'installs' => is_numeric($facts['unit_cost'] ?? null),
            'sales' => is_numeric($facts['roas'] ?? null) || is_numeric($facts['cpa'] ?? null),
            'traffic' => (float) ($facts['landing_views'] ?? $facts['results'] ?? 0) > 0,
            default => is_numeric($facts['roas'] ?? null),
        };
    }

    /**
     * CTR, CPC, or landing-page-view rate is weak on a sample large enough to read.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function trafficQualityWeak(array $facts): bool
    {
        $ctr = is_numeric($facts['ctr_percent'] ?? null) ? (float) $facts['ctr_percent'] : null;
        $cpc = is_numeric($facts['cpc'] ?? null) ? (float) $facts['cpc'] : null;
        $lpvRate = is_numeric($facts['lpv_rate'] ?? null) ? (float) $facts['lpv_rate'] : null;
        $maxCpc = (float) ($facts['max_cpc'] ?? 2);

        if ($ctr !== null && (int) ($facts['impressions'] ?? 0) >= 500 && $ctr < 0.8) {
            return true;
        }

        if ($ctr !== null && $ctr >= 1.5 && $cpc !== null && $cpc > $maxCpc) {
            return true;
        }

        return $lpvRate !== null && (int) ($facts['link_clicks'] ?? 0) >= 8 && $lpvRate < 0.5;
    }

    private static function unitCostLabel(string $kind): string
    {
        return match ($kind) {
            'subscriptions' => 'cost per subscriber',
            'leads' => 'cost per lead',
            'installs' => 'cost per install',
            default => 'cost per result',
        };
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function salesMetric(array $facts): string
    {
        $bits = [];

        if (is_numeric($facts['cpa'] ?? null)) {
            $bits[] = 'CPA '.self::money((float) $facts['cpa']);
        }

        if (is_numeric($facts['roas'] ?? null)) {
            $bits[] = 'ROAS '.self::ratio((float) $facts['roas']);
        }

        if ($bits === []) {
            return self::decimal((float) ($facts['results'] ?? 0)).' '.(string) ($facts['goal'] ?? 'results');
        }

        return implode(' and ', $bits);
    }

    /**
     * Interpret the same drop-off that drives the next actions.
     *
     * @param  array<string, mixed>  $facts
     */
    private static function funnelInsight(array $facts, CampaignDecisionVerdict $verdict): string
    {
        $goal = (string) ($facts['goal'] ?? 'results');
        $break = (string) ($facts['break'] ?? '');
        $ctr = is_numeric($facts['ctr_percent'] ?? null)
            ? number_format((float) $facts['ctr_percent'], 2).'% CTR'
            : null;

        if (($facts['thin'] ?? false) === true) {
            return 'Only '.self::money((float) $facts['spend']).' and '.self::int((int) $facts['impressions']).' impressions — too early to name a funnel break.';
        }

        $platformName = (string) ($facts['platform_name'] ?? 'Meta');

        $line = match ($break) {
            'tracking' => $platformName.' reports '.self::int((int) $facts['platform_conversions']).' conversions and internal records show '.self::decimal((float) $facts['internal_results']).'. Platform conversions above internal results means check tracking before the ad or the page.',
            'visit' => self::int((int) $facts['link_clicks']).' link clicks produced '.self::int((int) $facts['landing_views']).' landing-page views ('.number_format((float) $facts['lpv_rate'] * 100, 0).'%). A low landing-page-view rate means the click is not becoming a visit.',
            'auction' => ($ctr ?? 'CTR').' and CPC '.self::money((float) $facts['cpc']).' against an internal '.self::money((float) config('campaign-decisions.defaults.max_cpc', 2)).' CPC target. A healthy click-through with a CPC above that target means the auction is expensive, so cut the dearest placement with no '.$goal.', widen the audience, or switch off a bid cap. Do not rewrite the ad or the page first.',
            'traffic' => self::int((int) $facts['clicks']).' clicks'.($ctr !== null ? ' at '.$ctr : '').'. The objective is traffic, so purchases are not the result being measured. Landing-page views are not on this window.',
            'creative' => self::int((int) $facts['impressions']).' impressions'.($ctr !== null ? ' and '.$ctr : '').'. A weak click-through means the creative is the break on the way to '.$goal.'.',
            'page' => self::int((int) $facts['clicks']).' clicks'.($ctr !== null ? ' at '.$ctr : '').' became '.self::decimal((float) $facts['results']).' '.$goal.'. Clicks without '.$goal.' means the page is the break.',
            'cost' => self::costInsight($facts),
            'scale' => 'The funnel is holding'.($facts['roas'] === null ? '' : ' at ROAS '.self::ratio((float) $facts['roas'])).'.',
            default => self::money((float) $facts['spend']).' spend, '.self::int((int) $facts['clicks']).' clicks, and '.self::decimal((float) $facts['results']).' '.$goal.'.',
        };

        if (($facts['past_early'] ?? false) === true && $break !== 'tracking') {
            $line = self::money((float) $facts['spend']).' is past an early read. '.$line;
        }

        if (in_array($verdict, [CampaignDecisionVerdict::Learning, CampaignDecisionVerdict::InsufficientData], true)
            && ($facts['past_early'] ?? false) === true) {
            $line .= ' The learning verdict still leaves the budget unchanged.';
        }

        return $line;
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function costInsight(array $facts): string
    {
        $parts = [];

        if ($facts['kind'] === 'traffic' && $facts['revenue_per_session'] !== null) {
            $parts[] = 'revenue per visit '.self::money((float) $facts['revenue_per_session']);
        } elseif ($facts['unit_cost'] !== null && in_array($facts['kind'], ['subscriptions', 'leads', 'installs'], true)) {
            $label = match ($facts['kind']) {
                'subscriptions' => 'cost per subscriber',
                'leads' => 'cost per lead',
                default => 'cost per install',
            };
            $parts[] = $label.' '.self::money((float) $facts['unit_cost']);
        } elseif ($facts['cpa'] !== null) {
            $parts[] = 'CPA '.self::money((float) $facts['cpa']);
        }

        if ($facts['roas'] !== null) {
            $parts[] = 'ROAS '.self::ratio((float) $facts['roas']);
        }

        $lead = $parts === []
            ? self::money((float) $facts['spend']).' spent'
            : implode(' and ', $parts);

        return $lead.' on '.self::decimal((float) $facts['results']).' '.$facts['goal'].'. Results are arriving, and they cost more than this objective supports.';
    }

    /**
     * @param  array<string, mixed>  $diagnosis
     * @param  array<string, mixed>|null  $budget
     * @param  list<string>  $dataNotes
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    /**
     * Replace PHP steps with model lines only when they cite this campaign.
     *
     * @param  array<string, mixed>  $brief
     * @param  list<mixed>  $lines
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>
     */
    public static function applyModelSteps(array $brief, array $lines, array $snapshot): array
    {
        $verdict = (string) ($brief['verdict'] ?? '');
        $verdictCase = CampaignDecisionVerdict::tryFromStored($verdict);

        if (self::strategyNextActions($snapshot, $verdictCase ?? CampaignDecisionVerdict::InsufficientData) !== []) {
            return $brief;
        }

        $clean = [];
        $allowedMoves = is_array($brief['allowed_moves'] ?? null) ? $brief['allowed_moves'] : [];
        $healthOnly = in_array('cite_health', $allowedMoves, true);

        foreach ($lines as $line) {
            if (! is_string($line)) {
                return $brief;
            }

            $trimmed = trim($line);

            if ($trimmed === '' || mb_strlen($trimmed) > self::MAX_ACTION_LENGTH) {
                continue;
            }

            if ($healthOnly && preg_match('/\bretarget/i', $trimmed) === 1) {
                continue;
            }

            $clean[] = $trimmed;
        }

        if (count($clean) < 2 || count($clean) > 4) {
            return $brief;
        }

        $joined = implode(' ', $clean);

        if (self::textInventsNumbers($joined, $snapshot) || ! self::citesThisCampaign($joined, $snapshot)) {
            return $brief;
        }

        if (self::campaignPauseForbidden($verdictCase) && preg_match('/\bpause the campaign\b/i', $joined) === 1) {
            return $brief;
        }

        if (self::deliveryIsBroken($snapshot) && preg_match('/\bhealthy\b/i', $joined) === 1) {
            return $brief;
        }

        if ($verdict !== CampaignDecisionVerdict::ScaleUp->value
            && preg_match('/\b(scale up|increase the budget|raise the budget)\b/i', $joined) === 1
            && preg_match('/only after|hold budget/i', $joined) !== 1) {
            return $brief;
        }

        if (preg_match('/\b(ai-generated image|generate an image|image model|midjourney|dall-?e)\b/i', $joined) === 1) {
            return $brief;
        }

        if (preg_match('/\b(not on file|clearer offer|page owner)\b/i', $joined) === 1) {
            return $brief;
        }

        if (preg_match('/\b(higher chance|subscription chance|more likely to (?:buy|subscribe))\b/i', $joined) === 1) {
            return $brief;
        }

        if (preg_match('/bring cpc under/i', $joined) === 1
            && preg_match('/placement|advantage\+|lowest cost|visitor window/i', $joined) !== 1) {
            return $brief;
        }

        $phpJoined = implode(' ', is_array($brief['next_actions'] ?? null) ? $brief['next_actions'] : []);

        if ($healthOnly || str_contains($phpJoined, 'Do not switch to a different audience') || str_contains($phpJoined, 'Do not name a new audience')) {
            $storedNames = array_filter(array_merge(
                is_array(data_get($snapshot, 'audience.interests')) ? data_get($snapshot, 'audience.interests') : [],
                is_array(data_get($snapshot, 'audience.job_titles')) ? data_get($snapshot, 'audience.job_titles') : [],
            ), is_string(...));
            $citesStored = false;

            foreach ($storedNames as $name) {
                if ($name !== '' && str_contains($joined, $name)) {
                    $citesStored = true;
                    break;
                }
            }

            if (preg_match('/\btarget\b/i', $joined) === 1 && ! $citesStored) {
                return $brief;
            }
        }

        $modelMarks = self::actionMarks($joined);

        if ($allowedMoves === []) {
            $phpMarks = self::actionMarks($phpJoined);

            foreach ($modelMarks as $mark) {
                if (! in_array($mark, $phpMarks, true)) {
                    return $brief;
                }
            }
        } elseif (! self::marksAllowed($modelMarks, $allowedMoves, $verdict)) {
            return $brief;
        }

        if ($verdictCase !== null) {
            $phpVerdictLine = null;

            foreach (is_array($brief['next_actions'] ?? null) ? $brief['next_actions'] : [] as $phpLine) {
                if (is_string($phpLine) && self::statesVerdict($phpLine, $verdictCase)) {
                    $phpVerdictLine = $phpLine;
                    break;
                }
            }

            $clean = array_slice(self::withVerdictLine($clean, $verdictCase, $phpVerdictLine), 0, 4);
        }

        if (count($clean) < 2) {
            return $brief;
        }

        $brief['next_actions'] = $clean;
        $brief['next_actions_source'] = 'llm';

        return $brief;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function strategyNextActions(array $snapshot, CampaignDecisionVerdict $verdict): array
    {
        $rows = data_get($snapshot, 'performance_strategy.proposed_changes');

        if (! is_array($rows) || $rows === []) {
            return [];
        }

        $lines = [];

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

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

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

            if (self::campaignPauseForbidden($verdict) && preg_match('/\bpause the campaign\b/i', $text) === 1) {
                continue;
            }

            $lines[] = $text;
        }

        return $lines;
    }

    /**
     * Campaign-level moves the roster does not cover (restart delivery, hold budget).
     *
     * @param  array<string, mixed>  $facts
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function campaignControlSteps(array $facts, CampaignDecisionVerdict $verdict, array $snapshot): array
    {
        $steps = [];
        $deliveryState = (string) data_get($snapshot, 'performance_strategy.delivery_state', '');

        if ($deliveryState === 'paused') {
            return [
                'Campaign is paused on Meta. Resume it before changing budget, bid, or creatives.',
                'Do not rewrite the ad or the landing page while it is off.',
            ];
        }

        if ($deliveryState === 'archived') {
            return [
                'This campaign is deleted or archived on Meta. Do not change bid, budget, or creatives on this row.',
            ];
        }

        if (self::recentDeliveryStopped($snapshot)) {
            $steps[] = self::deliveryRestartLine($facts, $snapshot);
            $steps[] = 'Do not rewrite the ad or the landing page until this campaign is spending again.';

            return array_values(array_filter($steps, fn (string $line): bool => trim($line) !== ''));
        }

        if (self::campaignPauseForbidden($verdict)) {
            $steps[] = 'Leave the budget as it is. Watch this campaign; do not pause it.';
        }

        return array_values(array_filter($steps, fn (string $line): bool => trim($line) !== ''));
    }

    /**
     * @param  array<string, mixed>  $facts
     * @param  array<string, mixed>  $snapshot
     */
    private static function deliveryRestartLine(array $facts, array $snapshot): string
    {
        $daily = data_get($snapshot, 'campaign_profile.daily_budget') ?? data_get($snapshot, 'daily_budget');
        $seven = is_array($snapshot['windows']['7d'] ?? null) ? $snapshot['windows']['7d'] : [];
        $spend7 = array_key_exists('spend', $seven) ? (float) $seven['spend'] : (float) ($facts['spend'] ?? 0);
        $line = 'Restart delivery before changing the ad or the page. Last 7 days spent '.self::money($spend7);

        if (is_numeric($daily)) {
            $line .= ' against a '.self::money((float) $daily).' daily budget';
        }

        $line .= '.';

        $thirty = is_array($snapshot['windows']['30d'] ?? null) ? $snapshot['windows']['30d'] : [];
        $spend30 = (float) ($thirty['spend'] ?? 0);
        $clicks30 = (int) ($thirty['clicks'] ?? 0);

        if ($spend7 <= 0 && $spend30 > 0) {
            $line .= ' The last 30 days still show '.self::money($spend30).' spend and '.self::int($clicks30).' clicks, so this is a delivery stop, not a new campaign.';
        }

        if (($facts['bid_is_capped'] ?? false) === true) {
            $cap = $facts['bid_amount'] ?? null;
            $line .= ' Switch to lowest cost (Highest volume)'
                .(is_numeric($cap) ? ' or raise the cap from '.self::money((float) $cap) : '')
                .'. Do not raise the budget until it spends.';
        } else {
            $line .= ' Prefer lowest cost. Check the bid limit and audience size. Do not assume ads are paused or payment failed unless status says so.';
        }

        return $line;
    }

    private static function campaignPauseForbidden(?CampaignDecisionVerdict $verdict): bool
    {
        return $verdict === CampaignDecisionVerdict::Watch;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function deliveryIsBroken(array $snapshot): bool
    {
        $step = (string) data_get($snapshot, 'performance_strategy.broken_step');
        $state = (string) data_get($snapshot, 'performance_strategy.delivery_state');

        return $step === 'delivery' || $state === 'not_delivering';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function recentDeliveryStopped(array $snapshot): bool
    {
        if (! self::deliveryIsBroken($snapshot)) {
            return false;
        }

        $seven = $snapshot['windows']['7d'] ?? null;

        if (! is_array($seven)) {
            return false;
        }

        return (float) ($seven['spend'] ?? 0) < 1
            && (int) ($seven['impressions'] ?? 0) < 50;
    }

    /**
     * @param  list<string>  $marks
     * @param  list<string>  $allowedMoves
     */
    private static function marksAllowed(array $marks, array $allowedMoves, string $verdict): bool
    {
        foreach ($marks as $mark) {
            $allowed = match ($mark) {
                'page' => in_array('fix_first_screen', $allowedMoves, true) || in_array('new_heading', $allowedMoves, true),
                'new_heading' => in_array('new_heading', $allowedMoves, true),
                'creative' => in_array('new_creative', $allowedMoves, true),
                'pause' => in_array('pause', $allowedMoves, true),
                'raise' => $verdict === CampaignDecisionVerdict::ScaleUp->value,
                'cut' => $verdict === CampaignDecisionVerdict::DecreaseBudget->value,
                'hold_budget' => in_array('hold_budget', $allowedMoves, true) || in_array('restart_same_budget', $allowedMoves, true),
                default => false,
            };

            if (! $allowed) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function audienceNeedles(array $snapshot): array
    {
        $audience = is_array($snapshot['audience'] ?? null) ? $snapshot['audience'] : [];
        $names = array_merge(
            is_array($audience['interests'] ?? null) ? $audience['interests'] : [],
            is_array($audience['job_titles'] ?? null) ? $audience['job_titles'] : [],
            is_array($audience['countries'] ?? null) ? $audience['countries'] : [],
        );

        return array_values(array_filter(
            $names,
            fn (mixed $name): bool => is_string($name) && mb_strlen(trim($name)) >= 3,
        ));
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function pageNeedles(array $snapshot): array
    {
        $page = data_get($snapshot, 'creative_context.landing_page');

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

        $names = is_array($page['headings'] ?? null) ? $page['headings'] : [];
        $names[] = $page['title'] ?? null;

        return array_values(array_filter(
            $names,
            fn (mixed $name): bool => is_string($name) && mb_strlen(trim($name)) >= 8,
        ));
    }

    private static function nextActions(
        CampaignDecisionVerdict $verdict,
        array $diagnosis,
        ?array $budget,
        array $dataNotes,
        array $snapshot = [],
    ): array {
        $facts = self::funnelFacts($snapshot, $diagnosis);
        $verdictLine = self::verdictLine($verdict, $budget);
        $fromStrategy = self::strategyNextActions($snapshot, $verdict);
        $control = self::campaignControlSteps($facts, $verdict, $snapshot);
        $deliveryBroken = self::recentDeliveryStopped($snapshot);

        if ($facts['thin'] && $fromStrategy === [] && $control === []) {
            return [$verdictLine ?? self::thinLine($facts)];
        }

        $actions = $deliveryBroken ? [] : match ($facts['break']) {
            'page' => self::landerSteps($facts, $verdict),
            'delivery' => [],
            'traffic' => self::trafficSteps($facts),
            'visits' => self::visitsLandedSteps($facts),
            'awareness' => self::awarenessSteps($snapshot),
            'lag' => self::lagSteps(),
            default => [],
        };
        $trackingLine = self::trackingMismatchLine($snapshot);
        $single = match ($facts['break'] ?? '') {
            'page', 'traffic', 'awareness', 'delivery' => null,
            'tracking' => $trackingLine ?? self::actionLine($facts, $verdict),
            default => self::actionLine($facts, $verdict),
        };

        if (is_string($single) && $single !== '') {
            $actions[] = $single;
        }

        $actions = array_values(array_filter([
            ...$control,
            ...$actions,
            ...$fromStrategy,
            ($facts['break'] ?? '') === 'tracking' ? null : $trackingLine,
            (($facts['auction_expensive'] ?? false) === true && ($facts['break'] ?? '') !== 'auction')
                ? self::auctionAction($facts)
                : null,
            self::scaleLine($verdict, $facts, $budget),
        ], fn (?string $line): bool => is_string($line) && $line !== ''));

        $mentionsBudget = false;

        foreach ($actions as $action) {
            if (preg_match('/\b(budget|pause the campaign)\b/i', $action) === 1) {
                $mentionsBudget = true;
                break;
            }
        }

        if (! $mentionsBudget
            && in_array($verdict, [
                CampaignDecisionVerdict::Learning,
                CampaignDecisionVerdict::InsufficientData,
                CampaignDecisionVerdict::Watch,
            ], true)
            && ! ($facts['break'] === 'page' && ($facts['past_early'] ?? false) === true)
            && ! in_array($facts['break'], ['traffic', 'visits', 'lag', 'awareness'], true)) {
            $actions[] = 'Leave the budget as it is. Do not raise or cut spend while you make this change.';
        }

        if ($actions === [] && $dataNotes !== []) {
            $actions[] = $dataNotes[0];
        }

        $actions = self::withVerdictLine($actions, $verdict, $verdictLine);

        if (self::campaignPauseForbidden($verdict)) {
            $actions = array_values(array_filter(
                array_map(
                    fn (string $line): string => (string) preg_replace(
                        '/Pause the campaign\.?\s*/i',
                        'Hold the budget. ',
                        $line,
                    ),
                    $actions,
                ),
                fn (string $line): bool => trim($line) !== '',
            ));
        }

        $unique = [];

        foreach ($actions as $action) {
            if (! self::containsSimilar($unique, $action)) {
                $unique[] = $action;
            }
        }

        return array_values(array_slice($unique, 0, 6));
    }

    /**
     * The budget move a pause or decrease verdict requires, so What to do next never contradicts the verdict.
     *
     * @param  array<string, mixed>|null  $budget
     */
    private static function verdictLine(CampaignDecisionVerdict $verdict, ?array $budget): ?string
    {
        $summary = is_string($budget['summary'] ?? null) ? trim($budget['summary']) : '';

        return match ($verdict) {
            CampaignDecisionVerdict::Pause => $summary !== '' ? $summary : 'Pause the campaign and stop all spend.',
            CampaignDecisionVerdict::DecreaseBudget => $summary !== '' ? $summary : 'Decrease the daily budget.',
            default => null,
        };
    }

    private static function statesVerdict(string $line, CampaignDecisionVerdict $verdict): bool
    {
        return match ($verdict) {
            CampaignDecisionVerdict::Pause => preg_match('/\bpause\b/i', $line) === 1,
            CampaignDecisionVerdict::DecreaseBudget => preg_match('/\b(decrease|reduce|cut|lower)\b[^.]*\bbudget\b/i', $line) === 1,
            default => true,
        };
    }

    /**
     * Drops lines that keep the budget or wait for delivery, and leads with the verdict move when no line states it.
     *
     * @param  list<string>  $actions
     * @return list<string>
     */
    private static function withVerdictLine(array $actions, CampaignDecisionVerdict $verdict, ?string $verdictLine): array
    {
        if ($verdictLine === null || $verdictLine === '') {
            return $actions;
        }

        $kept = array_values(array_filter(
            $actions,
            fn (string $line): bool => preg_match('/\b(leave|keep|hold)\b[^.]*\bbudget\b|do not raise or cut|wait for more delivery/i', $line) !== 1,
        ));

        foreach ($kept as $line) {
            if (self::statesVerdict($line, $verdict)) {
                return $kept;
            }
        }

        return [$verdictLine, ...$kept];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $diagnosis
     * @return array<string, mixed>
     */
    private static function funnelFacts(array $snapshot, array $diagnosis): array
    {
        $platform = self::platformWindow($snapshot);
        $outcome = self::outcomeWindow($snapshot);
        $objective = self::objectiveLabel($snapshot);
        $kind = is_string(data_get($snapshot, 'performance_strategy.objective_kind'))
            ? (string) data_get($snapshot, 'performance_strategy.objective_kind')
            : self::objectiveKind($objective);
        $creative = is_array($snapshot['creative_context'] ?? null) ? $snapshot['creative_context'] : [];
        $signals = is_array($diagnosis['signals'] ?? null) ? $diagnosis['signals'] : [];
        $ctr = $platform['ctr'];
        $ctrPercent = $ctr === null
            ? (is_numeric($signals['ctr_percent'] ?? null) ? (float) $signals['ctr_percent'] : null)
            : round($ctr * 100, 2);
        $orders = $outcome === null ? 0.0 : (float) ($outcome['orders'] ?? 0);
        $leads = $outcome === null ? 0.0 : (float) ($outcome['leads'] ?? 0);
        $installs = $outcome === null ? 0.0 : (float) ($outcome['installs'] ?? 0);
        $subscriptions = $outcome === null ? 0.0 : (float) ($outcome['subscriptions'] ?? 0);
        if ($objective === '') {
            $kind = match (true) {
                $subscriptions > 0 => 'subscriptions',
                $leads > 0 => 'leads',
                $installs > 0 => 'installs',
                default => 'results',
            };
            $objective = match ($kind) {
                'subscriptions' => 'Subscriptions',
                'leads' => 'Leads',
                'installs' => 'App installs',
                default => '',
            };
        }
        $linkClicks = $platform['link_clicks'];
        $outboundClicks = $platform['outbound_clicks'] ?? null;
        $landingViews = $platform['landing_page_views'];
        $clickCount = $linkClicks ?? $platform['clicks'];
        $results = match ($kind) {
            'leads' => $leads > 0 ? $leads : ($orders > 0 ? $orders : (float) $platform['conversions']),
            'installs' => $installs > 0 ? $installs : (float) $platform['conversions'],
            'subscriptions' => $subscriptions > 0 ? $subscriptions : ($orders > 0 ? $orders : (float) $platform['conversions']),
            'sales' => $orders > 0 ? $orders : (float) $platform['conversions'],
            'traffic' => $landingViews !== null ? (float) $landingViews : (float) $clickCount,
            'awareness' => (float) max($platform['impressions'], $clickCount),
            default => max($orders, $subscriptions, $leads, (float) $platform['conversions']),
        };
        $spend = $outcome !== null && (float) ($outcome['revenue'] ?? 0) >= 0
            ? (float) ($platform['spend'] > 0 ? $platform['spend'] : 0)
            : $platform['spend'];
        $roas = $outcome !== null && is_numeric($outcome['roas'] ?? null) ? (float) $outcome['roas'] : null;
        $cpa = $outcome !== null && is_numeric($outcome['cpa'] ?? null) ? (float) $outcome['cpa'] : null;
        $minRoas = (float) config('campaign-decisions.defaults.minimum_roas', 1.2);
        $maxCpa = (float) config('campaign-decisions.defaults.maximum_cpa', 75);
        $explicitLandingViews = $platform['explicit_landing_page_views'] ?? null;
        $lpvRate = ($linkClicks !== null && $linkClicks > 0 && is_numeric($explicitLandingViews))
            ? ((int) $explicitLandingViews) / $linkClicks
            : (($linkClicks !== null && $linkClicks > 0 && $outboundClicks !== null && $outboundClicks < (int) round($linkClicks * 0.9))
                ? $outboundClicks / $linkClicks
                : null);
        $revenue = $outcome === null ? null : (float) ($outcome['revenue'] ?? 0);
        $sessions = $landingViews ?? $clickCount;
        $revenuePerSession = ($revenue !== null && $sessions > 0) ? $revenue / $sessions : null;
        $unitCost = match ($kind) {
            'subscriptions' => $subscriptions > 0 ? $platform['spend'] / $subscriptions : $cpa,
            'leads' => $leads > 0 ? $platform['spend'] / $leads : $cpa,
            'installs' => $installs > 0 ? $platform['spend'] / $installs : $cpa,
            default => $cpa,
        };
        $weakCost = match ($kind) {
            'subscriptions', 'leads', 'installs' => $unitCost !== null && $unitCost > $maxCpa,
            'traffic' => $revenue !== null && $revenue > 0 && $revenuePerSession !== null && $platform['cpc'] !== null && $revenuePerSession < $platform['cpc'],
            'sales' => ($roas !== null && $roas < $minRoas) || ($unitCost !== null && $unitCost > $maxCpa),
            default => $roas !== null && $roas < $minRoas,
        };
        $downloadInstall = (bool) data_get($snapshot, 'performance_strategy.download_install_funnel')
            || CampaignPerformanceStrategy::isDownloadInstallFunnel($snapshot);
        $internalResults = $downloadInstall
            ? $installs
            : ($orders + $subscriptions + $leads + $installs);
        $mismatchOnFile = data_get($snapshot, 'performance_strategy.tracking_mismatch');
        $countsDisagree = $outcome !== null
            && $platform['conversions'] >= 1
            && $internalResults + 0.5 < $platform['conversions'];
        $trackingGap = ! $downloadInstall
            && ! in_array($kind, ['traffic', 'awareness'], true)
            && ($mismatchOnFile === true
                || ($mismatchOnFile !== false && $countsDisagree));
        $thin = $platform['impressions'] < 200 && $platform['clicks'] < 8 && $platform['spend'] < 20 && $results <= 0;
        $pastEarly = $platform['spend'] >= 60 && $results <= 0;
        $conversionKind = in_array($kind, ['leads', 'sales', 'subscriptions', 'installs'], true);
        $landedWithoutResult = $conversionKind
            && $landingViews !== null
            && $landingViews > 0
            && $results <= 0;
        $lever = (string) ($diagnosis['primary_lever'] ?? '');
        $maxCpc = (float) config('campaign-decisions.defaults.max_cpc', 2);
        $auctionExpensive = $ctrPercent !== null
            && $ctrPercent >= 1.5
            && $platform['cpc'] !== null
            && $platform['cpc'] > $maxCpc;
        $cpm = is_numeric(data_get($snapshot, 'performance_strategy.delivery.cpm'))
            ? (float) data_get($snapshot, 'performance_strategy.delivery.cpm')
            : (is_numeric(data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery.cpm'))
                ? (float) data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery.cpm')
                : null);

        if ($cpm === null && $platform['impressions'] > 0 && $platform['spend'] > 0) {
            $cpm = round(($platform['spend'] / $platform['impressions']) * 1000, 2);
        }

        $break = 'delivery';

        if (! $thin) {
            if ($trackingGap) {
                $break = 'tracking';
            } elseif ($lpvRate !== null && $linkClicks >= 8 && $lpvRate < 0.5) {
                $break = 'visit';
            } elseif ($clickCount === 0 && $platform['impressions'] >= 200) {
                $break = 'creative';
            } elseif ($ctrPercent !== null && $platform['impressions'] >= 500 && $ctrPercent < 0.8) {
                $break = 'creative';
            } elseif ($auctionExpensive && ! $landedWithoutResult) {
                $break = 'auction';
            } elseif ($kind === 'traffic' && $landingViews === null && $clickCount >= 5) {
                $break = 'traffic';
            } elseif ($clickCount >= 5 && $results <= 0 && self::internalCountIsOpen($snapshot, $outcome, $platform) && ! ($landedWithoutResult && $pastEarly)) {
                $break = 'lag';
            } elseif ($clickCount >= 5 && $results <= 0) {
                $break = 'page';
            } elseif ($results > 0 && $weakCost) {
                $break = 'cost';
            } elseif ($kind === 'traffic' && $landingViews !== null && $landingViews > 0) {
                $break = 'visits';
            } elseif ($lever === 'fix_landing_page') {
                $break = 'page';
            } elseif ($lever === 'improve_creative') {
                $break = 'creative';
            } elseif ($lever === 'spend_more') {
                $break = 'scale';
            }
        }

        if (! $thin && self::prospectingAwareness($snapshot) && ($break === 'visits' || ($kind === 'awareness' && $break === 'page'))) {
            $break = 'awareness';
        }

        $strategyBreak = (string) data_get($snapshot, 'performance_strategy.broken_step');
        $deliveryState = (string) data_get($snapshot, 'performance_strategy.delivery_state');

        if ($strategyBreak === 'paused' || $deliveryState === 'paused') {
            $break = 'paused';
            $thin = false;
        } elseif ($strategyBreak === 'archived' || $deliveryState === 'archived') {
            $break = 'archived';
            $thin = false;
        } elseif (
            ($strategyBreak === 'delivery' || $deliveryState === 'not_delivering')
            && in_array($break, ['delivery', 'awareness', 'thin', 'tracking', ''], true)
        ) {
            $break = 'delivery';
            $thin = false;
        } elseif ($strategyBreak === 'tracking' && ! in_array($kind, ['traffic', 'awareness'], true)) {
            $break = 'tracking';
        }

        $bid = self::bidFactsFromSnapshot($snapshot);

        return [
            'platform' => (string) ($snapshot['platform'] ?? 'meta'),
            'platform_name' => self::platformName($snapshot),
            'kind' => $kind,
            'goal' => self::goalNoun($objective),
            'spend' => $platform['spend'],
            'impressions' => $platform['impressions'],
            'clicks' => $platform['clicks'],
            'link_clicks' => $linkClicks,
            'landing_views' => $landingViews,
            'lpv_rate' => $lpvRate,
            'ctr_percent' => $ctrPercent,
            'cpc' => $platform['cpc'],
            'cpm' => $cpm,
            'auction_expensive' => $auctionExpensive,
            'platform_conversions' => $platform['conversions'],
            'internal_results' => $internalResults,
            'download_install_funnel' => $downloadInstall,
            'results' => $results,
            'roas' => $roas,
            'cpa' => $cpa,
            'unit_cost' => $unitCost,
            'revenue_per_session' => $revenuePerSession,
            'revenue' => $revenue,
            'subscriptions' => $subscriptions,
            'evidence_days' => (int) ($platform['evidence_days'] ?? 7),
            'headline' => self::firstAdHeadline($creative),
            'headlines' => self::adHeadlines($creative),
            'primary_text' => self::firstPrimaryText($creative),
            'image_url' => self::firstImageUrl($creative),
            'cta' => self::firstAdCta($creative),
            'landing_url' => self::firstString(data_get($creative, 'landing_url'), data_get($creative, 'landing_urls.0')),
            'page_title' => self::firstString(data_get($creative, 'landing_page.title')),
            'page_headings' => self::pageHeadings($creative),
            'page_text' => self::firstString(data_get($creative, 'landing_page.text')),
            'landing_flow' => is_array($creative['landing_flow'] ?? null) ? $creative['landing_flow'] : [],
            'thin' => $thin,
            'past_early' => $pastEarly,
            'break' => $thin ? 'thin' : $break,
            'min_roas' => $minRoas,
            'max_cpa' => $maxCpa,
            'max_cpc' => $maxCpc,
            'spend_label' => $spend,
            'audience_mode' => self::audienceModeFromSnapshot($snapshot),
            'bid_strategy' => $bid['bid_strategy'],
            'bid_amount' => $bid['bid_amount'],
            'bid_is_capped' => $bid['bid_is_capped'],
            'costly_placement' => self::costlyPlacementFromSnapshot($snapshot),
        ];
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function thinLine(array $facts): string
    {
        return 'Wait for more delivery before changing the ad or the page.';
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function breakLine(array $facts): string
    {
        $goal = (string) $facts['goal'];
        $clicks = (int) $facts['clicks'];
        $results = (float) $facts['results'];
        $ctr = $facts['ctr_percent'];
        $cpc = $facts['cpc'];

        $who = is_string($facts['headline'] ?? null) && $facts['headline'] !== ''
            ? '“'.$facts['headline'].'”'
            : 'This campaign';
        $span = 'over '.(int) ($facts['evidence_days'] ?? 7).' days';
        $ctrText = $ctr === null ? null : number_format((float) $ctr, 2).'%';
        $rate = ($ctrText !== null ? 'CTR '.$ctrText : '')
            .($cpc !== null ? ($ctrText !== null ? ', ' : '').'CPC '.self::money((float) $cpc) : '');

        $platformName = (string) ($facts['platform_name'] ?? 'Meta');

        $line = match ($facts['break']) {
            'tracking' => $platformName.' reports '.self::int((int) $facts['platform_conversions']).' conversions and internal records show '.self::decimal((float) $facts['internal_results']).'. Confirm tracking before changing the ad or the page.',
            'visit' => $who.' '.$span.': '.self::int((int) $facts['link_clicks']).' link clicks produced '.self::int((int) $facts['landing_views']).' landing-page views ('.number_format((float) $facts['lpv_rate'] * 100, 0).'% ). Clicks are not becoming visits.',
            'auction' => $who.' '.$span.': CTR '.($ctr === null ? '—' : number_format((float) $ctr, 2).'%').' and CPC '.self::money((float) $cpc).'. The ad is being clicked. The expensive part is the auction, not the message.',
            'traffic' => $who.' '.$span.': '.self::money((float) $facts['spend']).', '.self::int($clicks).' clicks'
                .($rate !== '' ? ', '.$rate : '')
                .'. The objective is traffic, and landing-page views are not on this window.',
            'creative' => $who.' '.$span.': '.self::int((int) $facts['impressions']).' impressions'
                .($rate !== '' ? ', '.$rate : '')
                .', and almost no clicks toward '.$goal.'.',
            'page' => $results <= 0
                ? $who.' '.$span.': '.self::money((float) $facts['spend']).', '.self::int($clicks).' clicks'
                    .($rate !== '' ? ', '.$rate : '')
                    .', and 0 '.$goal.'.'
                : $who.' '.$span.': '.self::int($clicks).' clicks became '.self::decimal($results).' '.$goal
                    .($rate !== '' ? ' ('.$rate.')' : '').'.',
            'cost' => self::costBreakLine($facts),
            'scale' => 'Results support more budget: '.self::money((float) $facts['spend']).' spend'
                .($facts['roas'] === null ? '' : ', ROAS '.self::ratio((float) $facts['roas']))
                .'.',
            default => $who.' '.$span.': '.self::money((float) $facts['spend']).' spend, '.self::int($clicks).' clicks, '
                .self::decimal($results).' '.$goal.'.',
        };

        if (($facts['past_early'] ?? false) === true && $facts['break'] !== 'tracking') {
            return 'Spend '.self::money((float) $facts['spend']).' is past an early read. Leave the budget, but this is the break: '.$line;
        }

        return $line;
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function costBreakLine(array $facts): string
    {
        $parts = [];

        if ($facts['kind'] === 'traffic' && $facts['revenue_per_session'] !== null) {
            $parts[] = 'revenue per visit is '.self::money((float) $facts['revenue_per_session']);
        } elseif ($facts['unit_cost'] !== null && in_array($facts['kind'], ['subscriptions', 'leads', 'installs'], true)) {
            $label = match ($facts['kind']) {
                'subscriptions' => 'cost per subscriber',
                'leads' => 'cost per lead',
                default => 'cost per install',
            };
            $parts[] = $label.' is '.self::money((float) $facts['unit_cost']);
        } elseif ($facts['cpa'] !== null) {
            $parts[] = 'CPA is '.self::money((float) $facts['cpa']);
        }

        if ($facts['roas'] !== null) {
            $parts[] = 'ROAS is '.self::ratio((float) $facts['roas']);
        }

        $lead = $parts === []
            ? self::money((float) $facts['spend']).' spent'
            : implode(' and ', $parts).' on '.self::money((float) $facts['spend']).' spend';

        return $lead.' — '.$facts['goal'].' are arriving too expensive to buy more traffic.';
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function actionLine(array $facts, CampaignDecisionVerdict $verdict): ?string
    {
        if ($verdict === CampaignDecisionVerdict::DataIssue) {
            return 'Repair sync for this campaign before changing the ad or the page.';
        }

        $headline = $facts['headline'];
        $url = $facts['landing_url'];

        if ($facts['break'] === 'delivery') {
            return 'Restart delivery before changing the ad or the page. This campaign is not spending in this window.';
        }

        if ($facts['break'] === 'tracking') {
            $platformName = (string) ($facts['platform_name'] ?? 'Meta');

            return 'Confirm tracking before changing the ad or the page. '.$platformName.' and our own counts do not agree yet.';
        }

        if ($facts['break'] === 'visit') {
            $line = 'Landing-page views are far below the clicks. Check the link, redirects, page speed, and accidental clicks before rewriting the offer.';
            $flow = self::landingFlowLine($facts);

            return $flow !== null ? $line.' '.$flow : $line;
        }

        if ($facts['break'] === 'auction') {
            return self::auctionAction($facts);
        }

        if ($facts['break'] === 'traffic') {
            return null;
        }

        if ($facts['break'] === 'creative') {
            return self::designerBrief($facts);
        }

        if ($facts['break'] === 'page') {
            return self::landerBrief($facts);
        }

        if ($facts['break'] === 'cost') {
            $line = 'Do not buy more traffic until the cost comes inside the line.';

            if (is_string($url) && $url !== '' && is_string($headline) && $headline !== '') {
                $line .= ' On '.$url.', put the price on the first screen beside “'.$headline.'”.';
            } elseif (is_string($url) && $url !== '') {
                $line .= ' On '.$url.', put the price on the first screen.';
            } elseif (is_string($headline) && $headline !== '') {
                $line .= ' Put the price on the first screen beside “'.$headline.'”.';
            }

            return $line;
        }

        if ($facts['break'] === 'scale') {
            return 'Keep the current ad and page stable while the budget moves.';
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function auctionAction(array $facts): string
    {
        $ceiling = self::money((float) ($facts['max_cpc'] ?? config('campaign-decisions.defaults.max_cpc', 2)));
        $cpc = is_numeric($facts['cpc'] ?? null) ? self::money((float) $facts['cpc']) : 'the current CPC';
        $goal = (string) ($facts['goal'] ?? 'results');
        $audience = (string) ($facts['audience_mode'] ?? 'prospecting');
        $platformName = (string) ($facts['platform_name'] ?? 'Meta');

        if ($audience === 'retargeting') {
            return 'The '.$ceiling.' CPC figure is our internal target, not a '.$platformName.' setting. Clicks on a small retargeting pool stay expensive. Do not chase '.$ceiling.'. Widen the visitor window (for example 30 days to 60 or 90 days), exclude people who already converted, and judge whether those clicks become '.$goal.'.';
        }

        $parts = [
            'CTR is healthy, so do not rewrite the ad or the page first. The '.$ceiling.' CPC figure is our internal target, not a '.$platformName.' switch. Each click is '.$cpc.'.',
        ];
        $step = 1;

        if (($facts['bid_is_capped'] ?? false) === true) {
            $cap = is_numeric($facts['bid_amount'] ?? null) ? self::money((float) $facts['bid_amount']) : null;
            $parts[] = 'Step '.$step.': switch the bid to lowest cost (Highest volume)'
                .($cap !== null ? ', or raise the '.$cap.' cap' : '')
                .'.';
            $step++;
        }

        $placement = is_array($facts['costly_placement'] ?? null) ? $facts['costly_placement'] : null;
        $label = is_array($placement) && is_string($placement['label'] ?? null)
            ? trim((string) $placement['label'])
            : '';

        if ($label !== '') {
            $placementCpc = is_numeric($placement['cpc'] ?? null) ? ' at '.self::money((float) $placement['cpc']).' CPC' : '';
            $spend = is_numeric($placement['spend'] ?? null) ? self::money((float) $placement['spend']) : null;
            $parts[] = 'Step '.$step.': turn off '.$label
                .($spend !== null ? ' ('.$spend.' spend'.$placementCpc.' with no '.$goal.')' : '')
                .'. Keep the placements that still produce '.$goal.'.';
        } else {
            $consoleName = match ($platformName) {
                'LinkedIn' => 'Campaign Manager',
                'Google' => 'Google Ads',
                default => 'Ads Manager',
            };
            if ($platformName === 'Meta') {
                $parts[] = 'Step '.$step.': in '.$consoleName.', open Breakdown → Placement and turn off the placement with the highest CPC that has clicks and no '.$goal.'. Leave Advantage+ on for the rest.';
            } else {
                $parts[] = 'Step '.$step.': in '.$consoleName.', inspect placements or networks and exclude the placement with the highest CPC that has clicks and no '.$goal.'.';
            }
        }

        if (($facts['bid_is_capped'] ?? false) !== true && $platformName === 'Meta') {
            $parts[] = 'If the audience is a narrow saved list, turn Advantage+ audience on so Meta can bid in a larger pool.';
        }

        return implode(' ', $parts);
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function designerBrief(array $facts): string
    {
        $parts = ['Designer brief. The studio creates the image from the text prompt below.'];
        $headline = is_string($facts['headline'] ?? null) ? $facts['headline'] : '';
        $primary = is_string($facts['primary_text'] ?? null) ? $facts['primary_text'] : '';
        $cta = is_string($facts['cta'] ?? null) ? $facts['cta'] : '';
        $image = is_string($facts['image_url'] ?? null) ? $facts['image_url'] : '';
        $headlines = is_array($facts['headlines'] ?? null) ? $facts['headlines'] : [];
        $others = array_values(array_filter(
            $headlines,
            fn (mixed $line): bool => is_string($line) && $line !== '' && $line !== $headline,
        ));

        if ($headline !== '') {
            $parts[] = 'Control headline: “'.$headline.'”.';
        }

        if ($others !== []) {
            $parts[] = 'Other headlines on this ad: '.implode('; ', array_map(
                fn (string $line): string => '“'.$line.'”',
                array_slice($others, 0, 3),
            )).'.';
        }

        if ($primary !== '') {
            $parts[] = 'Primary text: “'.$primary.'”.';
        }

        if ($cta !== '') {
            $parts[] = 'Button: “'.self::buttonLabel($cta).'”.';
        }

        $parts[] = $image !== ''
            ? 'Image file: '.$image.'.'
            : 'Image file is not on this snapshot.';

        $platformName = (string) ($facts['platform_name'] ?? 'Meta');
        $parts[] = self::imagePrompt($headline, $primary, $image, $platformName);

        return implode(' ', $parts);
    }

    private static function imagePrompt(string $headline, string $primary, string $image, string $platformName = 'Meta'): string
    {
        $line = $headline !== '' ? $headline : 'the control promise';
        $ratio = match ($platformName) {
            'LinkedIn' => '1:1',
            'Google' => '1.91:1',
            default => '4:5',
        };
        $prompt = 'Image prompt (text only): '.$ratio.' '.$platformName.' feed still. Exact on-image line: “'.$line.'”.';

        if ($primary !== '') {
            $prompt .= ' One frame of this idea: “'.$primary.'”.';
        }

        $prompt .= ' High-contrast type, plain background, no extra slogans, no button on the image.';

        if ($image !== '') {
            $prompt .= ' Beat the control file at '.$image.'.';
        }

        return $prompt.' The studio makes the still. This app does not generate it.';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    public static function pageIsTheBreak(array $snapshot): bool
    {
        $diagnosis = is_array($snapshot['marketing_diagnosis'] ?? null) ? $snapshot['marketing_diagnosis'] : [];

        return (self::funnelFacts($snapshot, $diagnosis)['break'] ?? '') === 'page';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    public static function shouldReadLandingPages(array $snapshot): bool
    {
        $diagnosis = is_array($snapshot['marketing_diagnosis'] ?? null) ? $snapshot['marketing_diagnosis'] : [];
        $break = self::funnelFacts($snapshot, $diagnosis)['break'] ?? '';

        return in_array($break, ['page', 'visit'], true);
    }

    /**
     * @param  array<string, mixed>  $brief
     */
    public static function historyReason(array $brief): string
    {
        $issue = trim((string) ($brief['issue'] ?? ''));
        $actions = array_values(array_filter(
            is_array($brief['next_actions'] ?? null) ? $brief['next_actions'] : [],
            fn (mixed $line): bool => is_string($line) && trim($line) !== '',
        ));
        $parts = [];

        if ($issue !== '') {
            $parts[] = 'Issue: '.$issue;
        }

        if ($actions !== []) {
            $parts[] = 'What to do: '.implode(' ', $actions);
        }

        return $parts !== [] ? implode("\n", $parts) : trim((string) ($brief['scaling_stance'] ?? ''));
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    private static function trafficSteps(array $facts): array
    {
        $clicks = self::int((int) ($facts['clicks'] ?? 0));
        $cpc = is_numeric($facts['cpc'] ?? null) ? ' at '.self::money((float) $facts['cpc']).' each' : '';
        $platformName = (string) ($facts['platform_name'] ?? 'Meta');

        return [
            'Do not pause or rewrite the page yet. This is a traffic campaign. It is buying visits, not purchases. Landing-page views are missing, and there are '.$clicks.' clicks'.$cpc.'.',
            'In '.$platformName.', open this campaign and check Landing page views for the same dates.',
            'If those views are much lower than the clicks, pause the campaign, fix the link or the redirect, then turn it back on. If the views are close to the clicks, the page does not need a rewrite.',
        ];
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function awarenessSteps(array $snapshot): array
    {
        $diagnosis = is_array($snapshot['marketing_diagnosis'] ?? null) ? $snapshot['marketing_diagnosis'] : [];
        $facts = self::funnelFacts($snapshot, $diagnosis);
        $ctr = is_numeric($facts['ctr_percent'] ?? null) ? (float) $facts['ctr_percent'] : null;
        $cpc = is_numeric($facts['cpc'] ?? null) ? (float) $facts['cpc'] : null;
        $impressions = (int) ($facts['impressions'] ?? 0);
        $clicks = (int) ($facts['clicks'] ?? 0);

        if (($facts['thin'] ?? false) === true) {
            return ['Not enough delivery to judge this yet. Leave the budget as it is.'];
        }

        if ($impressions >= 500 && $ctr !== null && $ctr < 0.8) {
            return ['Traffic is limited by the ad. CTR is '.number_format($ctr, 2).'% across '.self::int((float) $impressions).' impressions. Leave the budget as it is until more people click.'];
        }

        if ($clicks < 8 && $impressions >= 200) {
            return ['Traffic is limited by the ad. '.self::int((float) $impressions).' impressions produced '.self::int((float) $clicks).' clicks. Leave the budget as it is.'];
        }

        $healthy = 'Delivery is healthy.';

        if ($ctr !== null) {
            $healthy .= ' CTR is '.number_format($ctr, 2).'%.';
        }

        if ($cpc !== null) {
            $healthy .= ' CPC is '.self::money($cpc).'.';
        }

        $healthy .= ' Nothing to change.';
        $steps = [$healthy];
        $cheaper = self::cheaperCpc($snapshot);

        if ($cheaper !== null) {
            $steps[] = 'Delivery got cheaper. The last 7 days cost '.self::money($cheaper['current']).' per click, down from '.self::money($cheaper['prior']).' in the 7 days before. That is cheaper traffic, not a higher chance of a subscription.';
        }

        return $steps;
    }

    /**
     * Last 7 days against the 7 days before, only when both weeks have enough clicks
     * and the later click is at least 10% cheaper.
     *
     * @param  array<string, mixed>  $snapshot
     * @return array{current: float, prior: float}|null
     */
    private static function cheaperCpc(array $snapshot): ?array
    {
        $current = data_get($snapshot, 'windows.7d');
        $wider = data_get($snapshot, 'windows.14d');

        if (! is_array($current) || ! is_array($wider)) {
            return null;
        }

        $currentClicks = (int) ($current['clicks'] ?? 0);
        $priorClicks = (int) ($wider['clicks'] ?? 0) - $currentClicks;
        $priorSpend = (float) ($wider['spend'] ?? 0) - (float) ($current['spend'] ?? 0);

        if ($currentClicks < 20 || $priorClicks < 20 || $priorSpend <= 0 || (float) ($current['spend'] ?? 0) <= 0) {
            return null;
        }

        $currentCpc = (float) $current['spend'] / $currentClicks;
        $priorCpc = $priorSpend / $priorClicks;

        if ($currentCpc >= $priorCpc * 0.9) {
            return null;
        }

        return ['current' => $currentCpc, 'prior' => $priorCpc];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function prospectingAwareness(array $snapshot): bool
    {
        $objective = strtolower((string) data_get($snapshot, 'campaign_profile.objective', data_get($snapshot, 'objective', '')));
        $name = strtolower((string) data_get($snapshot, 'campaign_profile.name', data_get($snapshot, 'campaign_name', '')));

        if (str_contains($objective, 'sale') || str_contains($objective, 'lead') || str_contains($objective, 'subscri')) {
            return false;
        }

        return str_contains($objective, 'awareness')
            || str_contains($objective, 'reach')
            || (str_contains($objective, 'traffic') && str_contains($name, 'brand awareness'));
    }

    /**
     * @return list<string>
     */
    private static function lagSteps(): array
    {
        return [
            'Wait for the internal count before changing the page. The reporting window has not closed.',
            'Leave the budget as it is until that count arrives.',
        ];
    }

    /**
     * A zero internal result is still inside the reporting lag, so it cannot name the page.
     *
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>|null  $outcome
     * @param  array<string, mixed>  $platform
     */
    private static function internalCountIsOpen(array $snapshot, ?array $outcome, array $platform): bool
    {
        $to = $outcome['to'] ?? $platform['to'] ?? null;

        if (! is_string($to) || $to === '') {
            return false;
        }

        $lag = (int) config('campaign-decisions.monitor.internal_reporting_lag_days', 2);

        return Carbon::parse($to)->startOfDay()->gt(now()->startOfDay()->subDays($lag));
    }

    /**
     * @return list<string>
     */
    private static function actionMarks(string $text): array
    {
        $marks = [];

        if (preg_match('/\b(first[- ]screen|first line|supporting text|set the (?:first )?heading|replace the first heading|button above the fold|button to)\b/i', $text) === 1) {
            $marks[] = 'page';
        }

        if (preg_match('/\b(set the (?:first )?heading|replace the first heading|set the line under|button above the fold|first line (?:states|to))\b/i', $text) === 1) {
            $marks[] = 'new_heading';
        }

        if (preg_match('/\b(image prompt|new ad|new creative|designer brief|draft a creative)\b/i', $text) === 1) {
            $marks[] = 'creative';
        }

        if (preg_match('/\bpause\b/i', $text) === 1 && preg_match('/\bdo not pause\b/i', $text) !== 1) {
            $marks[] = 'pause';
        }

        if (preg_match('/\b(increase the budget|raise the budget|scale up)\b/i', $text) === 1) {
            $marks[] = 'raise';
        }

        if (preg_match('/\b(decrease the (?:daily )?budget|reduce the (?:daily )?budget|cut the (?:daily )?budget|cut spend)\b/i', $text) === 1) {
            $marks[] = 'cut';
        }

        if (preg_match('/\b(budget unchanged|leave the budget|keep the budget|hold (?:the )?budget|0% change|do not raise or cut)\b/i', $text) === 1) {
            $marks[] = 'hold_budget';
        }

        return $marks;
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    private static function visitsLandedSteps(array $facts): array
    {
        $clicks = self::int((int) (($facts['link_clicks'] ?? null) !== null ? $facts['link_clicks'] : ($facts['clicks'] ?? 0)));
        $views = self::int((float) ($facts['landing_views'] ?? 0));
        $rate = is_numeric($facts['lpv_rate'] ?? null)
            ? ' ('.number_format((float) $facts['lpv_rate'] * 100, 0).'% of those clicks)'
            : '';

        return [
            'Do not pause this campaign, and do not rewrite the page. The objective is traffic. '.$clicks.' clicks opened '.$views.' landing-page views'.$rate.'.',
            'Leave the budget as it is. Score this campaign on visits and cost per visit, not on purchases.',
        ];
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function trafficMetric(array $facts): string
    {
        if (($facts['landing_views'] ?? null) === null) {
            return 'landing-page views are missing, so visits cannot be judged yet';
        }

        $line = self::int((float) $facts['landing_views']).' landing-page views';

        if ((float) ($facts['revenue'] ?? 0) > 0 && is_numeric($facts['revenue_per_session'] ?? null)) {
            $line .= '; revenue per visit '.self::money((float) $facts['revenue_per_session'])
                .' versus CPC '.self::money((float) ($facts['cpc'] ?? 0));
        }

        return $line;
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    private static function allowedMoves(array $facts, CampaignDecisionVerdict $verdict): array
    {
        $moves = self::breakMoves($facts);

        if (self::campaignPauseForbidden($verdict)) {
            $moves = array_values(array_diff($moves, ['pause']));
        }

        if (! in_array($verdict, [CampaignDecisionVerdict::Pause, CampaignDecisionVerdict::DecreaseBudget], true)) {
            return $moves;
        }

        $moves = array_values(array_diff($moves, ['hold_budget', 'restart_same_budget']));

        return $verdict === CampaignDecisionVerdict::Pause
            ? array_values(array_unique(['pause', ...$moves]))
            : $moves;
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    private static function breakMoves(array $facts): array
    {
        $heading = self::pageHeadingSaved($facts) ? ['new_heading'] : [];

        return match ($facts['break'] ?? '') {
            'page' => [
                ...(($facts['past_early'] ?? false) === true ? ['pause', 'restart_same_budget'] : ['hold_budget']),
                'fix_first_screen',
                ...$heading,
            ],
            'auction' => self::auctionMoves($facts),
            'traffic' => ['check_landing_views', 'hold_page', 'hold_budget'],
            'visits' => ['score_visits', 'hold_page', 'hold_budget'],
            'delivery' => ['restart_delivery', 'hold_budget'],
            'awareness' => ['cite_health', 'hold_budget'],
            'tracking' => ($facts['auction_expensive'] ?? false) === true
                ? ['fix_tracking', 'trim_expensive_placement', 'widen_audience', 'hold_ad', 'hold_page']
                : ['fix_tracking'],
            'creative' => ['new_creative', 'hold_budget'],
            'lag' => ['wait', 'hold_page', 'hold_budget'],
            'cost' => ['cite_cost', 'hold_budget'],
            'visit' => ['fix_link', 'hold_page'],
            default => ['hold_budget'],
        };
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    private static function auctionMoves(array $facts): array
    {
        if (($facts['audience_mode'] ?? '') === 'retargeting') {
            return ['widen_retargeting', 'exclude_converters', 'hold_ad', 'hold_page'];
        }

        $moves = ['trim_expensive_placement', 'widen_audience', 'hold_ad', 'hold_page'];

        if (($facts['bid_is_capped'] ?? false) === true) {
            array_unshift($moves, 'lowest_cost_bid');
        }

        return $moves;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function audienceModeFromSnapshot(array $snapshot): string
    {
        $fromStrategy = data_get($snapshot, 'performance_strategy.audience_mode');

        if (is_string($fromStrategy) && $fromStrategy !== '') {
            return $fromStrategy;
        }

        $type = strtolower(trim((string) data_get($snapshot, 'ad_set_optimization.ad_sets.0.audience.type', '')));

        if (in_array($type, ['retargeting', 'custom', 'lookalike'], true)) {
            return $type === 'lookalike' ? 'lookalike' : 'retargeting';
        }

        $name = strtolower((string) (data_get($snapshot, 'campaign_profile.name') ?? ''));

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

        return 'prospecting';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{bid_strategy: ?string, bid_amount: ?float, bid_is_capped: bool}
     */
    private static function bidFactsFromSnapshot(array $snapshot): array
    {
        $bid = is_array(data_get($snapshot, 'ad_set_optimization.ad_sets.0.bid'))
            ? data_get($snapshot, 'ad_set_optimization.ad_sets.0.bid')
            : [];
        $strategy = is_string($bid['bid_strategy'] ?? null) ? (string) $bid['bid_strategy'] : null;
        $amount = isset($bid['bid_amount']) && is_numeric($bid['bid_amount'])
            ? (float) $bid['bid_amount']
            : null;

        return [
            'bid_strategy' => $strategy,
            'bid_amount' => $amount,
            'bid_is_capped' => self::isCappedBid($strategy),
        ];
    }

    private static function isCappedBid(?string $strategy): bool
    {
        $value = strtoupper(trim((string) $strategy));

        if ($value === '' || str_contains($value, 'WITHOUT_CAP')) {
            return false;
        }

        return str_contains($value, 'COST_CAP')
            || str_contains($value, 'BID_CAP')
            || str_contains($value, 'TARGET_COST');
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{label: string, spend: float, cpc: ?float}|null
     */
    private static function costlyPlacementFromSnapshot(array $snapshot): ?array
    {
        $adSets = data_get($snapshot, 'ad_set_optimization.ad_sets');

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

        $best = null;
        $bestScore = -1.0;

        foreach ($adSets as $adSet) {
            if (! is_array($adSet)) {
                continue;
            }

            $rows = data_get($adSet, 'breakdowns.placements');

            if (! is_array($rows)) {
                continue;
            }

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

                $label = trim((string) ($row['label'] ?? $row['placement'] ?? ''));
                $spend = is_numeric($row['spend'] ?? null) ? (float) $row['spend'] : 0.0;
                $clicks = is_numeric($row['clicks'] ?? null)
                    ? (float) $row['clicks']
                    : (is_numeric($row['link_clicks'] ?? null) ? (float) $row['link_clicks'] : 0.0);
                $cpc = is_numeric($row['cpc'] ?? null)
                    ? (float) $row['cpc']
                    : ($clicks > 0 ? $spend / $clicks : null);
                $maxCpc = (float) config('campaign-decisions.defaults.max_cpc', 2);

                if ($label === '' || $spend <= 0 || $cpc === null || $cpc <= $maxCpc) {
                    continue;
                }

                $score = ($cpc * 100) + $spend;

                if ($score > $bestScore) {
                    $bestScore = $score;
                    $best = ['label' => $label, 'spend' => $spend, 'cpc' => $cpc];
                }
            }
        }

        return $best;
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function pageHeadingSaved(array $facts): bool
    {
        $headings = array_filter(
            is_array($facts['page_headings'] ?? null) ? $facts['page_headings'] : [],
            fn (mixed $heading): bool => is_string($heading) && trim($heading) !== '',
        );

        return $headings !== [];
    }

    /**
     * @param  array<string, mixed>  $facts
     * @return list<string>
     */
    private static function landerSteps(array $facts, CampaignDecisionVerdict $verdict): array
    {
        $goal = (string) ($facts['goal'] ?? 'results');
        $past = ($facts['past_early'] ?? false) === true;
        $steps = [];

        if ($past && self::campaignPauseForbidden($verdict)) {
            $steps[] = 'Hold the budget. '.self::money((float) ($facts['spend'] ?? 0)).' is already spent, and the page is still not producing '.$goal.'. Do not raise spend on the same page.';
        } elseif ($past) {
            $steps[] = 'Pause the campaign. '.self::money((float) ($facts['spend'] ?? 0)).' is already spent, and the page is still not producing '.$goal.'. Leaving it on spends more on the same page.';
        }

        $edit = self::landerBrief($facts);

        if ($edit !== '') {
            $steps[] = $edit;
        }

        if ($past) {
            $steps[] = 'After that first screen is live, turn the campaign back on at the same budget. Do not raise the budget on the restart.';
        }

        return $steps;
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function landerBrief(array $facts): string
    {
        $headline = is_string($facts['headline'] ?? null) ? $facts['headline'] : '';
        $url = is_string($facts['landing_url'] ?? null) ? $facts['landing_url'] : '';
        $title = is_string($facts['page_title'] ?? null) ? $facts['page_title'] : '';
        $text = is_string($facts['page_text'] ?? null) ? $facts['page_text'] : '';
        $headings = array_values(array_filter(
            is_array($facts['page_headings'] ?? null) ? $facts['page_headings'] : [],
            fn (mixed $heading): bool => is_string($heading) && $heading !== '',
        ));
        $flowLine = self::landingFlowLine($facts);

        $where = $url !== '' ? $url : 'the landing page';

        $goal = (string) ($facts['goal'] ?? 'results');
        $first = is_string($headings[0] ?? null) ? $headings[0] : '';
        $next = is_string($headings[1] ?? null) ? $headings[1] : '';

        if ($title === '' && $headings === [] && $text === '') {
            $views = $facts['landing_views'] ?? null;
            $arrived = is_numeric($views)
                ? self::int((float) $views).' landing-page views opened '.$where
                : self::int((float) ($facts['clicks'] ?? 0)).' clicks reached '.$where;
            $promise = $headline !== ''
                ? 'The ad says “'.$headline.'”.'
                : 'Open the page and read the first screen.';

            $line = 'Open '.$where.'. '.$promise.' '.$arrived.' and '.self::countText((float) ($facts['results'] ?? 0)).' '.$goal.' came back. Make the first screen ask for the '.$goal.' in the words on the ad.';

            return $flowLine !== null ? $line.' '.$flowLine : $line;
        }

        $seen = [];

        if ($title !== '') {
            $seen[] = 'The page title is “'.self::quoted($title).'”.';
        }

        if ($first !== '') {
            $seen[] = 'The first line is “'.self::quoted($first).'”.';
        }

        if ($next !== '') {
            $seen[] = 'Then the page asks “'.self::quoted($next).'”.';
        } elseif ($text !== '') {
            $seen[] = 'The page then says “'.self::quoted(mb_substr($text, 0, 120)).'”.';
        }

        $change = 'Change the first screen so it asks for the '.$goal;

        if ($headline !== '' && strcasecmp($first, $headline) !== 0) {
            $change .= ' and the first line states “'.$headline.'”';
        }

        if ($next !== '') {
            $change .= ' before “'.self::quoted($next).'”';
        }

        $seen[] = $change.'.';

        if ($flowLine !== null) {
            $seen[] = $flowLine;
        }

        return implode(' ', $seen);
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function landingFlowLine(array $facts): ?string
    {
        $flow = array_values(array_filter(
            is_array($facts['landing_flow'] ?? null) ? $facts['landing_flow'] : [],
            fn (mixed $step): bool => is_array($step),
        ));

        if (count($flow) > 1) {
            $parts = [];

            foreach ($flow as $step) {
                $number = (int) ($step['step'] ?? (count($parts) + 1));
                $heading = is_array($step['headings'] ?? null)
                    ? trim((string) ($step['headings'][0] ?? ''))
                    : '';
                $stepUrl = trim((string) ($step['url'] ?? ''));
                $parts[] = 'step '.$number
                    .($stepUrl !== '' ? ' '.$stepUrl : '')
                    .($heading !== '' ? ' “'.self::quoted($heading).'”' : '');
            }

            return 'The click path has '.count($flow).' screens ('.implode('; ', $parts).'). Judge the whole flow before a page rewrite.';
        }

        $url = is_string($facts['landing_url'] ?? null) ? trim($facts['landing_url']) : '';

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

        return 'Only the first landing URL is on file. Do not invent later screens or a What to do next page rewrite until those URLs are read.';
    }

    private static function quoted(string $value): string
    {
        return rtrim(trim($value), '.');
    }

    private static function buttonLabel(string $cta): string
    {
        $normalized = strtoupper(str_replace([' ', '-'], '_', trim($cta)));

        return match ($normalized) {
            'SEE_DETAILS', 'LEARN_MORE', 'GET_STARTED', 'SIGN_UP', 'SHOP_NOW', 'BOOK_NOW',
            'CONTACT_US', 'DOWNLOAD', 'APPLY_NOW', 'SUBSCRIBE', 'GET_OFFER', 'GET_QUOTE',
            'SEND_MESSAGE', 'CALL_NOW', 'WATCH_MORE' => ucfirst(strtolower(str_replace('_', ' ', $normalized))),
            default => trim($cta),
        };
    }

    /**
     * @param  array<string, mixed>  $facts
     * @param  array<string, mixed>|null  $budget
     */
    private static function scaleLine(CampaignDecisionVerdict $verdict, array $facts, ?array $budget): ?string
    {
        if ($verdict === CampaignDecisionVerdict::Pause) {
            if ((float) ($facts['results'] ?? 0) <= 0 || ($facts['break'] ?? '') === 'page') {
                return null;
            }

            return 'Restart this campaign only after '.$facts['goal'].' show up again.';
        }

        if ($verdict === CampaignDecisionVerdict::DataIssue) {
            return null;
        }

        if ($verdict === CampaignDecisionVerdict::ScaleUp) {
            if ($facts['roas'] !== null) {
                return 'Raise budget gradually — current ROAS is '.self::ratio((float) $facts['roas']).'.';
            }

            return is_string($budget['summary'] ?? null) && $budget['summary'] !== ''
                ? $budget['summary']
                : 'Raise budget gradually and re-check this campaign after the next spend period.';
        }

        if ($facts['kind'] === 'sales' && $facts['roas'] !== null) {
            return 'Scale this campaign only after ROAS clears '.self::ratio((float) $facts['min_roas']).' (it is '.self::ratio((float) $facts['roas']).' now).';
        }

        if (in_array($facts['kind'], ['subscriptions', 'leads', 'installs'], true) && $facts['unit_cost'] !== null) {
            return 'Scale only after cost per '.rtrim((string) $facts['goal'], 's').' falls under '.self::money((float) $facts['max_cpa']).' (it is '.self::money((float) $facts['unit_cost']).' now).';
        }

        return null;
    }

    private static function objectiveKind(string $objective): string
    {
        $lower = strtolower($objective);

        return match (true) {
            str_contains($lower, 'subscri') => 'subscriptions',
            str_contains($lower, 'lead') => 'leads',
            str_contains($lower, 'install') || str_contains($lower, 'app') => 'installs',
            str_contains($lower, 'traffic') || str_contains($lower, 'visit') => 'traffic',
            str_contains($lower, 'awareness') || str_contains($lower, 'reach') => 'awareness',
            $objective === '' => 'results',
            default => 'sales',
        };
    }

    private static function citesThisCampaign(string $text, array $snapshot): bool
    {
        $platform = self::platformWindow($snapshot);
        $needles = array_filter([
            $platform['spend'] > 0 ? number_format($platform['spend'], 2) : null,
            $platform['clicks'] > 0 ? (string) $platform['clicks'] : null,
            $platform['impressions'] > 0 ? (string) $platform['impressions'] : null,
            self::firstAdHeadline(is_array($snapshot['creative_context'] ?? null) ? $snapshot['creative_context'] : []),
            self::firstString(
                data_get($snapshot, 'creative_context.landing_url'),
                data_get($snapshot, 'creative_context.landing_urls.0'),
            ),
            self::firstString(data_get($snapshot, 'campaign_profile.name'), data_get($snapshot, 'campaign_name')),
            ...self::audienceNeedles($snapshot),
            ...self::pageNeedles($snapshot),
        ]);

        foreach ($needles as $needle) {
            if (is_string($needle) && $needle !== '' && str_contains($text, $needle)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function textInventsNumbers(string $text, array $snapshot): bool
    {
        $json = json_encode($snapshot, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: '{}';

        preg_match_all('/\$?\d+(?:\.\d+)?/', $text, $matches);

        foreach ($matches[0] as $raw) {
            $plain = ltrim((string) $raw, '$');

            if (str_contains($json, $plain)) {
                continue;
            }

            if (is_numeric($plain) && str_contains($json, (string) (0 + $plain))) {
                continue;
            }

            return true;
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function trackingMismatchLine(array $snapshot): ?string
    {
        $platform = self::platformWindow($snapshot);
        $outcome = self::outcomeWindow($snapshot);

        $kind = is_string(data_get($snapshot, 'performance_strategy.objective_kind'))
            ? (string) data_get($snapshot, 'performance_strategy.objective_kind')
            : self::objectiveKind(self::objectiveLabel($snapshot));

        if ($outcome === null
            || in_array($kind, ['traffic', 'awareness'], true)
            || CampaignPerformanceStrategy::isDownloadInstallFunnel($snapshot)) {
            return null;
        }

        $platformResults = $platform['conversions'];
        $internalResults = (float) ($outcome['orders'] ?? 0)
            + (float) ($outcome['subscriptions'] ?? 0)
            + (float) ($outcome['leads'] ?? 0)
            + (float) ($outcome['installs'] ?? 0);

        if ($internalResults <= 0 && (float) ($outcome['conversions'] ?? 0) > 0) {
            $internalResults = (float) $outcome['conversions'];
        }

        if ($platformResults === 0 && $internalResults <= 0) {
            return null;
        }

        if (abs($platformResults - $internalResults) < 0.5) {
            return null;
        }

        $platformName = self::platformName($snapshot);

        return 'Check tracking — '.$platformName.' reports '.self::int($platformResults).' conversions while internal shows '.self::decimal($internalResults).' results.';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function objectiveLabel(array $snapshot): string
    {
        $raw = self::firstString(
            data_get($snapshot, 'campaign_profile.objective'),
            data_get($snapshot, 'objective'),
            data_get($snapshot, 'profile.objective'),
        );

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

        if (CampaignPerformanceStrategy::isDownloadInstallFunnel($snapshot)) {
            return 'Downloads to installs';
        }

        $normalized = strtoupper(str_replace(['-', ' '], '_', $raw));

        return match (true) {
            str_contains($normalized, 'SUBSCRI') => 'Subscriptions',
            str_contains($normalized, 'SALE') || str_contains($normalized, 'PURCHASE') || str_contains($normalized, 'CONVERSION') => 'Sales / conversions',
            str_contains($normalized, 'LEAD') => 'Leads',
            str_contains($normalized, 'INSTALL') || str_contains($normalized, 'APP') => 'App installs',
            str_contains($normalized, 'TRAFFIC') || str_contains($normalized, 'LINK_CLICK') || str_contains($normalized, 'VISIT') => 'Traffic',
            str_contains($normalized, 'AWARENESS') || str_contains($normalized, 'REACH') || str_contains($normalized, 'IMPRESSION') => 'Awareness / reach',
            str_contains($normalized, 'ENGAGEMENT') || str_contains($normalized, 'VIDEO') => 'Engagement',
            default => str_replace('_', ' ', ucwords(strtolower($raw), '_')),
        };
    }

    private static function goalNoun(string $objective): string
    {
        $lower = strtolower($objective);

        return match (true) {
            $objective === '' => 'results',
            str_contains($lower, 'subscri') => 'subscribers',
            str_contains($lower, 'lead') => 'leads',
            str_contains($lower, 'install') || str_contains($lower, 'app') => 'installs',
            str_contains($lower, 'traffic') || str_contains($lower, 'visit') => 'landing visits',
            str_contains($lower, 'awareness') || str_contains($lower, 'reach') => 'reach',
            str_contains($lower, 'engagement') => 'engagement',
            default => 'conversions',
        };
    }

    /**
     * @param  array<string, mixed>  $creative
     */
    private static function firstAdHeadline(array $creative): ?string
    {
        foreach (['ads', 'creatives'] as $key) {
            $rows = $creative[$key] ?? null;

            if (! is_array($rows)) {
                continue;
            }

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

                $headline = self::firstString($row['headline'] ?? null, $row['name'] ?? null);

                if ($headline !== null) {
                    return mb_strlen($headline) > 80 ? mb_substr($headline, 0, 77).'…' : $headline;
                }
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $creative
     */
    private static function firstAdCta(array $creative): ?string
    {
        foreach (['ads', 'creatives'] as $key) {
            $rows = $creative[$key] ?? null;

            if (! is_array($rows)) {
                continue;
            }

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

                $cta = self::firstString($row['cta'] ?? null);

                if ($cta !== null) {
                    return $cta;
                }
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $creative
     * @return list<string>
     */
    private static function adHeadlines(array $creative): array
    {
        foreach (['ads', 'creatives'] as $key) {
            $rows = $creative[$key] ?? null;

            if (! is_array($rows)) {
                continue;
            }

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

                $headlines = $row['headlines'] ?? null;

                if (is_array($headlines)) {
                    $lines = array_values(array_filter($headlines, fn (mixed $line): bool => is_string($line) && trim($line) !== ''));

                    if ($lines !== []) {
                        return array_slice($lines, 0, 5);
                    }
                }
            }
        }

        $single = self::firstAdHeadline($creative);

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

    /**
     * @param  array<string, mixed>  $creative
     */
    private static function firstPrimaryText(array $creative): ?string
    {
        return self::firstAdField($creative, 'primary_text');
    }

    /**
     * @param  array<string, mixed>  $creative
     */
    private static function firstImageUrl(array $creative): ?string
    {
        return self::firstAdField($creative, 'image_url');
    }

    /**
     * @param  array<string, mixed>  $creative
     */
    private static function firstAdField(array $creative, string $field): ?string
    {
        foreach (['ads', 'creatives'] as $key) {
            $rows = $creative[$key] ?? null;

            if (! is_array($rows)) {
                continue;
            }

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

                $value = self::firstString($row[$field] ?? null);

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

        return null;
    }

    /**
     * @param  array<string, mixed>  $creative
     * @return list<string>
     */
    private static function pageHeadings(array $creative): array
    {
        $headings = data_get($creative, 'landing_page.headings');

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

        return array_slice(array_values(array_filter(
            $headings,
            fn (mixed $heading): bool => is_string($heading) && trim($heading) !== '',
        )), 0, 4);
    }

    private static function firstString(mixed ...$candidates): ?string
    {
        foreach ($candidates as $candidate) {
            if (! is_string($candidate)) {
                continue;
            }

            $trimmed = trim($candidate);

            if ($trimmed !== '') {
                return $trimmed;
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>|null  $budget
     */
    private static function scalingStance(CampaignDecisionVerdict $verdict, ?array $budget): string
    {
        return match ($verdict) {
            CampaignDecisionVerdict::ScaleUp => $budget['summary']
                ?? 'Performance supports a careful scale-up.',
            CampaignDecisionVerdict::DecreaseBudget => 'Hold or reduce budget while you strengthen the conversion path.',
            CampaignDecisionVerdict::Pause => 'Pause is safer than scaling — rebuild the offer path, then restart.',
            CampaignDecisionVerdict::Learning => 'Still learning — keep budget steady and prepare the next creative/page tests.',
            CampaignDecisionVerdict::InsufficientData => 'Not enough data to scale yet — keep gathering signal and prep the next test.',
            CampaignDecisionVerdict::DataIssue => 'Fix data quality first so the next recommendation is trustworthy.',
            CampaignDecisionVerdict::Watch => 'Mixed signals — hold budget and review again on the next run.',
            CampaignDecisionVerdict::Maintain => 'Performance looks acceptable — maintain budget and keep optimizing.',
        };
    }

    /**
     * @param  array<string, mixed>  $facts
     */
    private static function bottleneckLabel(?string $lever, CampaignDecisionVerdict $verdict, array $facts = []): string
    {
        if ($verdict === CampaignDecisionVerdict::DataIssue) {
            return 'Data quality';
        }

        if ($facts !== [] && ($facts['thin'] ?? false) === true) {
            return 'No delivery yet';
        }

        if ($facts !== []) {
            $specific = match ($facts['break'] ?? '') {
                'tracking' => 'Tracking',
                'visit' => 'Clicks are not landing',
                'auction' => 'Auction cost',
                'traffic' => 'Traffic delivery',
                'visits' => 'Visits are landing',
                'delivery' => 'Delivery',
                'paused' => 'Off on Meta',
                'archived' => 'Deleted on Meta',
                'awareness' => 'Named audience',
                'lag' => 'Count not in yet',
                'creative' => 'Creative',
                'page' => 'Landing page',
                'cost' => 'Offer cost',
                'thin' => 'No delivery yet',
                default => null,
            };

            if (is_string($specific) && $specific !== '') {
                return $specific;
            }
        }

        if ($verdict === CampaignDecisionVerdict::Learning || $verdict === CampaignDecisionVerdict::InsufficientData) {
            return match ($lever) {
                'improve_creative' => 'Creative',
                'fix_landing_page' => 'Landing page',
                default => 'Needs more delivery',
            };
        }

        return match ($lever) {
            'improve_creative' => 'Creative / CTR',
            'fix_landing_page' => 'Landing page / post-click conversion',
            'spend_more' => 'Budget (ready to scale carefully)',
            'hold' => 'Needs more evidence',
            default => match ($verdict) {
                CampaignDecisionVerdict::Pause, CampaignDecisionVerdict::DecreaseBudget => 'Efficiency / outcomes',
                CampaignDecisionVerdict::ScaleUp, CampaignDecisionVerdict::Maintain => 'None — delivery looks acceptable',
                default => 'Review needed',
            },
        };
    }

    /**
     * @param  array<string, mixed>  $diagnosis
     */
    /**
     * The diagnosis summary repeats "Fix the landing page" without the edit.
     * The next-action lines already carry the specific change.
     *
     * @param  list<string>  $nextActions
     * @param  array<string, mixed>  $facts
     */
    private static function summary(array $nextActions, array $facts): string
    {
        $specific = match ($facts['break'] ?? '') {
            'page' => self::landerBrief($facts),
            'creative' => self::designerBrief($facts),
            'auction' => self::auctionAction($facts),
            'tracking' => 'Confirm tracking before changing the ad or the page.',
            'visit' => 'Check redirects, page speed, and accidental clicks before rewriting the offer.',
            default => '',
        };

        if ($specific === '' || in_array($specific, $nextActions, true)) {
            return '';
        }

        return $specific;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function dataNotes(array $snapshot): array
    {
        $notes = [];
        $capabilities = is_array($snapshot['capabilities'] ?? null) ? $snapshot['capabilities'] : [];

        if (($capabilities['internal_revenue_available'] ?? false) !== true
            && ($snapshot['affiliate']['matched'] ?? false) !== true
            && ! is_array($snapshot['roi_performance'] ?? null)) {
            $notes[] = 'Internal outcome rows were not matched — treat revenue conclusions as incomplete.';
        }

        if (($capabilities['ingest_healthy'] ?? true) === false) {
            $notes[] = 'Platform ingest reported a problem for this account.';
        }

        $quality = data_get($snapshot, 'data_quality.status');

        if ($quality === 'BROKEN') {
            $notes[] = 'Data quality is marked broken for this evaluation.';
        }

        return $notes;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     spend: float,
     *     impressions: int,
     *     clicks: int,
     *     link_clicks: ?int,
     *     outbound_clicks: ?int,
     *     landing_page_views: ?int,
     *     explicit_landing_page_views: ?int,
     *     ctr: ?float,
     *     cpc: ?float,
     *     conversions: int,
     *     conversion_value: float,
     *     evidence_days: int,
     *     to: ?string
     * }
     */
    private static function platformWindow(array $snapshot): array
    {
        $picked = self::evidenceWindow($snapshot);
        $window = $picked['window'];
        $evidenceDays = $picked['days'];

        $spend = (float) ($window['spend'] ?? 0);
        $clicks = (int) ($window['clicks'] ?? 0);
        $impressions = (int) ($window['impressions'] ?? 0);
        $linkClicks = array_key_exists('link_clicks', $window) && $window['link_clicks'] !== null
            ? (int) $window['link_clicks']
            : null;
        $outboundClicks = array_key_exists('outbound_clicks', $window) && $window['outbound_clicks'] !== null
            ? (int) $window['outbound_clicks']
            : null;
        $explicitLandingPageViews = array_key_exists('landing_page_views', $window) && $window['landing_page_views'] !== null
            ? (int) $window['landing_page_views']
            : self::storedLandingPageViews($snapshot, $linkClicks, $outboundClicks, $evidenceDays);
        $landingPageViews = $explicitLandingPageViews ?? $outboundClicks;
        $ctrClicks = $linkClicks ?? $clicks;

        return [
            'spend' => $spend,
            'impressions' => $impressions,
            'clicks' => $clicks,
            'link_clicks' => $linkClicks,
            'outbound_clicks' => $outboundClicks,
            'landing_page_views' => $landingPageViews,
            'explicit_landing_page_views' => $explicitLandingPageViews,
            'ctr' => $impressions > 0 ? $ctrClicks / $impressions : (isset($window['ctr']) ? (float) $window['ctr'] : null),
            'cpc' => $ctrClicks > 0 ? $spend / $ctrClicks : (isset($window['cpc']) ? (float) $window['cpc'] : null),
            'conversions' => (int) ($window['conversions'] ?? 0),
            'conversion_value' => (float) ($window['conversion_value'] ?? 0),
            'evidence_days' => $evidenceDays,
            'to' => is_string($window['to'] ?? null) ? $window['to'] : null,
        ];
    }

    /**
     * Landing page views are not outbound clicks. Outbound is only a fallback when
     * it is clearly lower than link clicks.
     *
     * @param  array<string, mixed>  $snapshot
     */
    private static function storedLandingPageViews(array $snapshot, ?int $linkClicks, ?int $outboundClicks, int $evidenceDays = 7): ?int
    {
        $fromStrategy = data_get($snapshot, 'performance_strategy.delivery.landing_page_views');

        if (is_numeric($fromStrategy) && $evidenceDays === 7) {
            return (int) $fromStrategy;
        }

        $total = null;

        if ($evidenceDays === 7) {
            foreach (data_get($snapshot, 'ad_set_optimization.ad_sets', []) as $adSet) {
                if (! is_array($adSet)) {
                    continue;
                }

                $lpv = data_get($adSet, 'delivery.landing_page_views');

                if (! is_numeric($lpv)) {
                    continue;
                }

                $total = ($total ?? 0) + (int) $lpv;
            }
        }

        if ($total !== null) {
            return $total;
        }

        if ($outboundClicks !== null && $linkClicks !== null && $linkClicks > 0 && $outboundClicks < (int) round($linkClicks * 0.9)) {
            return $outboundClicks;
        }

        return null;
    }

    /**
     * Prefer the longest window that already has enough clicks or spend.
     *
     * @param  array<string, mixed>  $snapshot
     * @return array{window: array<string, mixed>, days: int}
     */
    private static function evidenceWindow(array $snapshot): array
    {
        $picked = null;

        foreach ([30, 15, 7, 3] as $days) {
            $window = data_get($snapshot, 'windows.'.$days.'d');

            if (! is_array($window)) {
                continue;
            }

            if ((int) ($window['clicks'] ?? 0) >= 8 || (float) ($window['spend'] ?? 0) >= 25) {
                $picked = ['window' => $window, 'days' => $days];
                break;
            }
        }

        if ($picked === null) {
            $fallback = data_get($snapshot, 'windows.7d');

            if (! is_array($fallback)) {
                $fallback = data_get($snapshot, 'last_7_days');
            }

            $picked = [
                'window' => is_array($fallback) ? $fallback : [],
                'days' => 7,
            ];
        }

        if ($picked['days'] === 7 || self::windowHasLandingPageViews($picked['window']) || ! self::adSetLandingPageViewsAreOnFile($snapshot)) {
            return $picked;
        }

        $seven = data_get($snapshot, 'windows.7d');

        if (is_array($seven) && ((int) ($seven['clicks'] ?? 0) >= 8 || (float) ($seven['spend'] ?? 0) >= 25)) {
            return ['window' => $seven, 'days' => 7];
        }

        return $picked;
    }

    /**
     * @param  array<string, mixed>  $window
     */
    private static function windowHasLandingPageViews(array $window): bool
    {
        return array_key_exists('landing_page_views', $window) && is_numeric($window['landing_page_views']);
    }

    /**
     * Ad-set and strategy LPVs are a 7-day grain. Do not mix them with a longer click window.
     *
     * @param  array<string, mixed>  $snapshot
     */
    private static function adSetLandingPageViewsAreOnFile(array $snapshot): bool
    {
        if (is_numeric(data_get($snapshot, 'performance_strategy.delivery.landing_page_views'))) {
            return true;
        }

        foreach (data_get($snapshot, 'ad_set_optimization.ad_sets', []) as $adSet) {
            if (is_array($adSet) && is_numeric(data_get($adSet, 'delivery.landing_page_views'))) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>|null
     */
    private static function outcomeWindow(array $snapshot): ?array
    {
        $outcome = data_get($snapshot, 'windows.outcome_7d');

        if (is_array($outcome) && ((float) ($outcome['orders'] ?? 0) > 0
            || (float) ($outcome['revenue'] ?? $outcome['net_revenue'] ?? 0) > 0
            || (float) ($outcome['platform_spend'] ?? $outcome['spend'] ?? 0) > 0)) {
            $spend = (float) ($outcome['platform_spend'] ?? $outcome['spend'] ?? 0);
            $orders = (float) ($outcome['orders'] ?? 0);
            $revenue = (float) ($outcome['revenue'] ?? $outcome['net_revenue'] ?? 0);

            return [
                'orders' => $orders,
                'revenue' => $revenue,
                'roas' => $outcome['roas'] ?? ($spend > 0 && $revenue > 0 ? $revenue / $spend : null),
                'cpa' => $outcome['cpa'] ?? ($orders > 0 ? $spend / $orders : null),
                'revenue_source' => $outcome['revenue_source'] ?? data_get($snapshot, 'affiliate.revenue_source'),
                'subscriptions' => (float) ($outcome['subscriptions'] ?? 0),
                'conversions' => (float) ($outcome['conversions'] ?? 0),
                'leads' => (float) ($outcome['leads'] ?? 0),
                'installs' => (float) ($outcome['installs'] ?? 0),
                'bookings' => (float) ($outcome['bookings'] ?? 0),
                'from' => $outcome['from'] ?? null,
                'to' => $outcome['to'] ?? null,
            ];
        }

        $affiliate = data_get($snapshot, 'affiliate.7d');

        if (is_array($affiliate) && ($snapshot['affiliate']['matched'] ?? false) === true) {
            $orders = (float) ($affiliate['orders'] ?? 0);
            $revenue = (float) ($affiliate['net_revenue'] ?? 0);
            $spend = (float) data_get($snapshot, 'windows.7d.spend', data_get($snapshot, 'last_7_days.spend', 0));

            return [
                'orders' => $orders,
                'revenue' => $revenue,
                'roas' => $spend > 0 && $revenue > 0 ? $revenue / $spend : null,
                'cpa' => $orders > 0 ? $spend / $orders : null,
                'revenue_source' => 'affiliate',
                'subscriptions' => 0.0,
                'conversions' => 0.0,
                'leads' => 0.0,
                'installs' => 0.0,
                'bookings' => 0.0,
                'from' => null,
                'to' => null,
            ];
        }

        $roi = $snapshot['roi_performance'] ?? null;

        if (is_array($roi)) {
            $spend = (float) ($roi['spent'] ?? 0);
            $orders = (float) ($roi['arb_orders'] ?? 0);
            $revenue = (float) ($roi['arb_sales_amount'] ?? 0);

            return [
                'orders' => $orders,
                'revenue' => $revenue,
                'roas' => $spend > 0 && $revenue > 0 ? $revenue / $spend : null,
                'cpa' => $orders > 0 ? $spend / $orders : null,
                'revenue_source' => 'roi_dashboard',
                'subscriptions' => (float) ($roi['subscriptions'] ?? 0),
                'conversions' => (float) ($roi['conversions'] ?? 0),
                'leads' => (float) ($roi['leads'] ?? 0),
                'installs' => (float) ($roi['installs'] ?? 0),
                'bookings' => (float) ($roi['bookings'] ?? 0),
                'from' => null,
                'to' => null,
            ];
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function windowLabel(array $snapshot): string
    {
        $picked = self::evidenceWindow($snapshot);
        $days = (int) $picked['days'];
        $from = $picked['window']['from'] ?? null;
        $to = $picked['window']['to'] ?? null;

        if (is_string($from) && $from !== '' && is_string($to) && $to !== '') {
            return 'last '.$days.' days ('.Carbon::parse($from)->toDateString().' → '.Carbon::parse($to)->toDateString().')';
        }

        return 'last '.$days.' days';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function internalWindowLabel(array $snapshot): ?string
    {
        $from = data_get($snapshot, 'windows.outcome_7d.from')
            ?? data_get($snapshot, 'affiliate.outcome_window.from');
        $to = data_get($snapshot, 'windows.outcome_7d.to')
            ?? data_get($snapshot, 'affiliate.outcome_window.to');
        $lag = data_get($snapshot, 'affiliate.lag_days');

        if (! is_string($from) || $from === '' || ! is_string($to) || $to === '') {
            return null;
        }

        $label = 'Internal lag window '.$from.' → '.$to;

        if (is_numeric($lag)) {
            $label .= ' ('.$lag.'-day reporting lag)';
        }

        return $label;
    }

    /**
     * @param  list<string>  $lines
     */
    private static function containsSimilar(array $lines, string $candidate): bool
    {
        $needle = strtolower(trim($candidate));

        foreach ($lines as $line) {
            if (strtolower(trim($line)) === $needle) {
                return true;
            }
        }

        return false;
    }

    private static function money(float $value): string
    {
        return '$'.number_format($value, 2);
    }

    private static function moneyOrDash(?float $value): string
    {
        return $value === null ? '—' : self::money($value);
    }

    private static function int(int|float $value): string
    {
        return number_format((int) $value);
    }

    private static function decimal(float $value): string
    {
        return number_format($value, 2);
    }

    private static function countText(float $value): string
    {
        return fmod($value, 1.0) === 0.0 ? self::int($value) : self::decimal($value);
    }

    private static function pct(?float $value): string
    {
        return $value === null ? '—' : number_format($value * 100, 2).'%';
    }

    private static function ratio(?float $value): string
    {
        return $value === null ? '—' : number_format($value, 2).'x';
    }
}
