<?php

namespace App\Library\CampaignDecision;

use Carbon\Carbon;

/**
 * PHP facts and constraints for campaign recommendations.
 * The model writes buyer-facing advice inside these bounds.
 */
class CampaignPerformanceStrategy
{
    public static function platformName(array $snapshot): string
    {
        $platform = strtolower((string) ($snapshot['platform'] ?? 'meta'));

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

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     objective_kind: string,
     *     primary_result_event: string,
     *     primary_result_label: string,
     *     meta_learning_stage: ?string,
     *     delivery_state: string,
     *     audience_mode: string,
     *     feasibility: string,
     *     broken_step: string,
     *     brand_tokens: list<string>,
     *     creative_brand_mismatch: bool,
     *     tracking_mismatch: bool,
     *     download_install_funnel: bool,
     *     platform_results: float,
     *     internal_results: float,
     *     delivery: array<string, mixed>,
     *     targets: array<string, float|null>,
     *     allowed_moves: list<string>,
     *     forbidden_moves: list<string>,
     *     must_say: list<string>,
     *     must_not_say: list<string>,
     *     metrics_required: list<string>
     * }
     */
    public static function fromSnapshot(array $snapshot, ?string $status = null): array
    {
        $downloadInstall = self::isDownloadInstallFunnel($snapshot);
        $platformName = self::platformName($snapshot);
        $objectiveKind = self::objectiveKind($snapshot);
        $primaryEvent = self::primaryResultEvent($snapshot, $objectiveKind);
        $delivery = self::deliveryFacts($snapshot);
        $learning = self::metaLearningStage($snapshot, $delivery);
        $audienceMode = self::audienceMode($snapshot);
        $platformResults = self::platformResults($snapshot, $objectiveKind, $primaryEvent, $delivery);
        $internalResults = self::internalResults($snapshot, $downloadInstall);
        $trackingMismatch = self::trackingMismatch($platformResults, $internalResults, $snapshot, $objectiveKind, $downloadInstall);
        $brandTokens = self::brandTokens($snapshot);
        $creativeMismatch = self::creativeBrandMismatch($snapshot, $brandTokens);
        $deliveryState = self::deliveryState($snapshot, $delivery, $learning);
        $feasibility = self::feasibility($snapshot, $objectiveKind, $platformResults, $delivery, $deliveryState);
        $brokenStep = self::brokenStep(
            $deliveryState,
            $learning,
            $feasibility,
            $creativeMismatch,
            $trackingMismatch,
            $audienceMode,
            $objectiveKind,
            $delivery,
            $platformResults,
            $status,
        );
        $targets = self::targets($objectiveKind);
        $audienceSaturated = self::audienceSaturated($snapshot, $delivery);
        $smallPool = self::smallRetargetingPool($audienceMode, $delivery);
        $ctaMismatch = self::retargetingCtaMismatch($snapshot, $audienceMode);
        $audienceSize = self::audienceSize($snapshot);
        $placementCost = PlacementPublisherCosts::fromSnapshot($snapshot, $objectiveKind);
        $allowed = self::allowedMoves($brokenStep, $audienceMode, $objectiveKind, $feasibility, $deliveryState, $delivery, $audienceSaturated, $ctaMismatch);
        $forbidden = self::forbiddenMoves($brokenStep, $audienceMode, $objectiveKind, $feasibility, $deliveryState, $learning, $ctaMismatch);
        if (is_array($placementCost['gap'] ?? null)) {
            $allowed = array_values(array_unique([...$allowed, 'shift_spend_to_cheaper_placement']));
            $forbidden = array_values(array_diff($forbidden, ['restrict_placements', 'hold_placements']));
        }
        $mustSay = self::mustSay($brokenStep, $learning, $feasibility, $trackingMismatch, $creativeMismatch, $delivery, $platformResults, $internalResults, $objectiveKind, $targets, $audienceMode, $audienceSaturated, $smallPool, $ctaMismatch, $audienceSize, $downloadInstall, $platformName);
        $placementLine = PlacementPublisherCosts::mustSay($placementCost);
        if ($placementLine !== null) {
            $mustSay[] = $placementLine;
        }
        $mustNotSay = self::mustNotSay($forbidden, $audienceMode, $objectiveKind, $deliveryState, $ctaMismatch, $downloadInstall, is_array($placementCost['gap'] ?? null), $platformName);

        $packet = [
            'objective_kind' => $objectiveKind,
            'primary_result_event' => $primaryEvent,
            'primary_result_label' => self::resultLabel($primaryEvent, $objectiveKind),
            'meta_learning_stage' => $learning,
            'delivery_state' => $deliveryState,
            'audience_mode' => $audienceMode,
            'feasibility' => $feasibility,
            'broken_step' => $brokenStep,
            'brand_tokens' => $brandTokens,
            'creative_brand_mismatch' => $creativeMismatch,
            'tracking_mismatch' => $trackingMismatch,
            'download_install_funnel' => $downloadInstall,
            'platform_results' => $platformResults,
            'internal_results' => $internalResults,
            'delivery' => $delivery,
            'targets' => $targets,
            'allowed_moves' => $allowed,
            'forbidden_moves' => $forbidden,
            'must_say' => $mustSay,
            'must_not_say' => $mustNotSay,
            'metrics_required' => self::metricsRequired($objectiveKind, $audienceMode),
            'audience_saturated' => $audienceSaturated,
            'small_retargeting_pool' => $smallPool,
            'cta_mismatch' => $ctaMismatch,
            'audience_size' => $audienceSize,
            'placement_cost' => $placementCost,
            'ad_roster' => CampaignAdRoster::fromSnapshot($snapshot, [
                'broken_step' => $brokenStep,
                'audience_mode' => $audienceMode,
                'delivery' => $delivery,
            ]),
        ];
        $packet['proposed_changes'] = in_array($deliveryState, ['paused', 'archived'], true)
            ? []
            : CampaignAdRoster::proposedChanges($packet['ad_roster']);
        $packet['live_ad_ids'] = array_values(array_filter(array_map(
            function (mixed $ad): string {
                if (! is_array($ad) || ! CampaignAdRoster::isLive($ad)) {
                    return '';
                }

                return trim((string) ($ad['ad_id'] ?? ''));
            },
            is_array($packet['ad_roster']['ads'] ?? null) ? $packet['ad_roster']['ads'] : [],
        )));

        return $packet;
    }

    /**
     * Listing shows live Meta campaigns only. Paused and archived stay off the board.
     *
     * @param  array<string, mixed>  $row
     */
    public static function appearsOnListing(array $row): bool
    {
        foreach ([
            $row['platform_status'] ?? null,
            data_get($row, 'snapshot.campaign_profile.platform_status'),
            data_get($row, 'snapshot.platform_status'),
        ] as $raw) {
            $status = strtoupper(trim((string) $raw));

            if ($status !== '' && (self::isPausedStatus($status) || self::isArchivedStatus($status))) {
                return false;
            }
        }

        return true;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    public static function objectiveKind(array $snapshot): string
    {
        $event = strtolower(trim((string) (
            data_get($snapshot, 'campaign_goals.optimization_event')
            ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.optimization_event')
            ?? ''
        )));
        $goal = strtolower(trim((string) (
            data_get($snapshot, 'campaign_goals.optimization_goals.0')
            ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.optimization_goal')
            ?? ''
        )));
        $objective = strtolower(trim((string) (
            data_get($snapshot, 'campaign_profile.objective')
            ?? data_get($snapshot, 'campaign_goals.objective')
            ?? ''
        )));

        if (str_contains($event, 'subscribe') || str_contains($goal, 'subscribe')) {
            return 'subscriptions';
        }

        if (str_contains($event, 'purchase') || str_contains($event, 'omni_purchase')) {
            return 'sales';
        }

        if (self::isDownloadInstallFunnel($snapshot)) {
            return 'installs';
        }

        if (str_contains($event, 'lead') || str_contains($event, 'complete_registration')) {
            return 'leads';
        }

        if (str_contains($goal, 'landing_page') || str_contains($objective, 'traffic') || str_contains($objective, 'visit')) {
            return 'traffic';
        }

        if (str_contains($objective, 'awareness') || str_contains($objective, 'reach') || str_contains($goal, 'reach') || str_contains($goal, 'impressions')) {
            return 'awareness';
        }

        if (str_contains($objective, 'lead')) {
            return 'leads';
        }

        if (str_contains($objective, 'sale') || str_contains($objective, 'conversion')) {
            $subs = (float) (data_get($snapshot, 'windows.outcome_7d.subscriptions')
                ?? data_get($snapshot, 'affiliate.7d.subscriptions')
                ?? 0);
            if ($subs > 0 || str_contains((string) data_get($snapshot, 'campaign_profile.name'), 'ubscri')) {
                return 'subscriptions';
            }

            return 'sales';
        }

        if (str_contains($objective, 'app') || str_contains($objective, 'install')) {
            return 'installs';
        }

        return 'results';
    }

    /**
     * Desktop download campaigns often use Meta Leads + offsite conversions
     * for the file-download pixel. Internal installs are the next step, not
     * the same event.
     *
     * @param  array<string, mixed>  $snapshot
     */
    public static function isDownloadInstallFunnel(array $snapshot): bool
    {
        $haystack = mb_strtolower(trim(implode(' ', array_filter([
            (string) data_get($snapshot, 'campaign_profile.name'),
            (string) data_get($snapshot, 'campaign_name'),
            (string) data_get($snapshot, 'creative_context.landing_url'),
            (string) data_get($snapshot, 'ad_set_optimization.ad_sets.0.name'),
        ], fn (string $part): bool => trim($part) !== ''))));

        foreach (['searchbrowser', 'search_browser', 'search browser'] as $needle) {
            if (str_contains($haystack, $needle)) {
                return true;
            }
        }

        if (str_contains($haystack, 'download') || str_contains($haystack, 'installer') || str_contains($haystack, '.exe')) {
            return true;
        }

        $objective = strtolower(trim((string) (
            data_get($snapshot, 'campaign_profile.objective')
            ?? data_get($snapshot, 'campaign_goals.objective')
            ?? ''
        )));

        if (! str_contains($objective, 'lead')) {
            return false;
        }

        $outcome = is_array(data_get($snapshot, 'windows.outcome_7d'))
            ? data_get($snapshot, 'windows.outcome_7d')
            : (is_array(data_get($snapshot, 'affiliate.7d')) ? data_get($snapshot, 'affiliate.7d') : []);
        $installs = (float) ($outcome['installs'] ?? 0);
        $leads = (float) ($outcome['leads'] ?? 0);
        $conversions = (float) (data_get($snapshot, 'windows.7d.conversions') ?? 0);

        return $installs > 0 && $leads <= 0 && $conversions >= 1;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function primaryResultEvent(array $snapshot, string $kind): string
    {
        $event = trim((string) (
            data_get($snapshot, 'campaign_goals.optimization_event')
            ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.optimization_event')
            ?? ''
        ));

        if ($kind === 'installs') {
            return 'install';
        }

        if ($event !== '') {
            return strtolower($event);
        }

        $goal = strtoupper(trim((string) (
            data_get($snapshot, 'campaign_goals.optimization_goals.0')
            ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.optimization_goal')
            ?? ''
        )));

        return match (true) {
            $goal === 'LANDING_PAGE_VIEWS' => 'landing_page_view',
            $kind === 'subscriptions' => 'subscribe',
            $kind === 'leads' => 'lead',
            $kind === 'sales' => 'purchase',
            $kind === 'traffic' => 'landing_page_view',
            $kind === 'awareness' => 'impression',
            $kind === 'installs' => 'app_install',
            default => 'conversion',
        };
    }

    private static function resultLabel(string $event, string $kind): string
    {
        return match (true) {
            str_contains($event, 'landing_page') => 'landing page views',
            str_contains($event, 'subscribe') || $kind === 'subscriptions' => 'subscriptions',
            str_contains($event, 'lead') || $kind === 'leads' => 'leads',
            str_contains($event, 'purchase') || $kind === 'sales' => 'purchases',
            str_contains($event, 'install') || $kind === 'installs' => 'installs',
            $kind === 'awareness' => 'impressions',
            default => 'results',
        };
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    /**
     * @param  array<string, mixed>  $delivery
     */
    private static function metaLearningStage(array $snapshot, array $delivery = []): ?string
    {
        $raw = strtoupper(trim((string) (
            data_get($snapshot, 'ad_set_optimization.ad_sets.0.learning_status')
            ?? data_get($snapshot, 'campaign_profile.platform_learning_label')
            ?? data_get($snapshot, 'delivery_status')
            ?? ''
        )));

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

        $stage = match (true) {
            in_array($raw, ['SUCCESS', 'LEARNING_SUCCESS'], true) => 'SUCCESS',
            in_array($raw, ['FAIL', 'LEARNING_FAIL'], true) => 'FAIL',
            in_array($raw, ['LEARNING_LIMITED', 'LIMITED'], true) => 'LEARNING_LIMITED',
            in_array($raw, ['LEARNING'], true) => 'LEARNING',
            default => $raw,
        };

        if ($stage === 'LEARNING' && self::costCapIsThrottling($snapshot, $delivery)) {
            return 'LEARNING_LIMITED';
        }

        return $stage;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $delivery
     */
    private static function costCapIsThrottling(array $snapshot, array $delivery = []): bool
    {
        $strategy = is_string($delivery['bid_strategy'] ?? null)
            ? (string) $delivery['bid_strategy']
            : (string) data_get($snapshot, 'ad_set_optimization.ad_sets.0.bid.bid_strategy', '');

        if (! self::isCostCap($strategy)) {
            return false;
        }

        $daily = (float) (
            data_get($snapshot, 'campaign_profile.daily_budget')
            ?? data_get($snapshot, 'campaign_goals.daily_budget')
            ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.bid.daily_budget')
            ?? 0
        );
        $spend = (float) ($delivery['spend_7d'] ?? data_get($snapshot, 'windows.7d.spend', 0));

        return $daily > 0 && $spend < ($daily * 7 * 0.4);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     spend_7d: float,
     *     impressions_7d: int,
     *     clicks_7d: int,
     *     link_clicks_7d: ?int,
     *     cpm: ?float,
     *     reach: ?int,
     *     frequency: ?float,
     *     landing_page_views: ?int,
     *     cost_per_lpv: ?float,
     *     ctr_percent: ?float,
     *     bid_strategy: ?string,
     *     bid_amount: ?float,
     *     cpc: ?float,
     *     platform_status: string
     * }
     */
    private static function deliveryFacts(array $snapshot): array
    {
        $window = is_array(data_get($snapshot, 'windows.7d'))
            ? data_get($snapshot, 'windows.7d')
            : (is_array(data_get($snapshot, 'last_7_days')) ? data_get($snapshot, 'last_7_days') : []);
        $adDelivery = is_array(data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery'))
            ? data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery')
            : [];

        $spend = (float) ($window['spend'] ?? $adDelivery['spend'] ?? 0);
        $impressions = (int) ($window['impressions'] ?? $adDelivery['impressions'] ?? 0);
        $clicks = (int) ($window['clicks'] ?? $adDelivery['clicks'] ?? 0);
        $linkClicks = isset($window['link_clicks']) ? (int) $window['link_clicks'] : (isset($adDelivery['outbound_clicks']) ? (int) $adDelivery['outbound_clicks'] : null);
        $cpm = isset($adDelivery['cpm']) && is_numeric($adDelivery['cpm']) ? (float) $adDelivery['cpm'] : null;
        $reach = isset($adDelivery['reach']) && is_numeric($adDelivery['reach']) ? (int) $adDelivery['reach'] : null;
        $frequency = isset($adDelivery['frequency']) && is_numeric($adDelivery['frequency']) ? (float) $adDelivery['frequency'] : null;
        $adLpv = isset($adDelivery['landing_page_views']) && is_numeric($adDelivery['landing_page_views'])
            ? (int) $adDelivery['landing_page_views']
            : null;
        $windowLpv = isset($window['landing_page_views']) && is_numeric($window['landing_page_views'])
            ? (int) $window['landing_page_views']
            : null;
        $lpv = ($adLpv !== null && $adLpv > 0) ? $adLpv : $windowLpv;
        $lpvSpend = $spend;

        if (($lpv === null || $lpv === 0) && $spend <= 0) {
            foreach ([15, 30] as $days) {
                $longer = data_get($snapshot, 'windows.'.$days.'d');

                if (! is_array($longer) || ! is_numeric($longer['landing_page_views'] ?? null)) {
                    continue;
                }

                $longerLpv = (int) $longer['landing_page_views'];

                if ($longerLpv <= 0) {
                    continue;
                }

                $lpv = $longerLpv;
                $lpvSpend = (float) ($longer['spend'] ?? 0);
                break;
            }
        }

        $costPerLpv = ($lpv !== null && $lpv > 0 && $lpvSpend > 0) ? round($lpvSpend / $lpv, 2) : null;
        $ctrBase = $linkClicks ?? $clicks;
        $ctrPercent = $impressions > 0 && $ctrBase > 0 ? round(($ctrBase / $impressions) * 100, 2) : null;

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

        $bid = is_array(data_get($snapshot, 'ad_set_optimization.ad_sets.0.bid'))
            ? data_get($snapshot, 'ad_set_optimization.ad_sets.0.bid')
            : [];
        $bidStrategy = is_string($bid['bid_strategy'] ?? null) ? (string) $bid['bid_strategy'] : null;
        $bidAmount = isset($bid['bid_amount']) && is_numeric($bid['bid_amount'])
            ? round((float) $bid['bid_amount'], 2)
            : null;
        $cpc = isset($window['cpc']) && is_numeric($window['cpc'])
            ? round((float) $window['cpc'], 2)
            : ($clicks > 0 && $spend > 0 ? round($spend / $clicks, 2) : null);
        $previous = is_array(data_get($snapshot, 'previous_7_days'))
            ? data_get($snapshot, 'previous_7_days')
            : (is_array(data_get($snapshot, 'windows.previous_7d')) ? data_get($snapshot, 'windows.previous_7d') : []);
        $previousImpressions = (int) ($previous['impressions'] ?? 0);
        $previousClicks = (int) ($previous['clicks'] ?? $previous['link_clicks'] ?? 0);
        $previousCtr = $previousImpressions > 0 && $previousClicks > 0
            ? round(($previousClicks / $previousImpressions) * 100, 2)
            : null;
        $ctrVsPrevious = ($ctrPercent !== null && $previousCtr !== null && $previousCtr > 0)
            ? round(($ctrPercent - $previousCtr) / $previousCtr, 4)
            : null;

        return [
            'spend_7d' => $spend,
            'impressions_7d' => $impressions,
            'clicks_7d' => $clicks,
            'link_clicks_7d' => $linkClicks,
            'cpm' => $cpm,
            'reach' => $reach,
            'frequency' => $frequency,
            'landing_page_views' => $lpv,
            'cost_per_lpv' => $costPerLpv,
            'ctr_percent' => $ctrPercent,
            'previous_7d_ctr_percent' => $previousCtr,
            'ctr_vs_previous_7d' => $ctrVsPrevious,
            'bid_strategy' => $bidStrategy,
            'bid_amount' => $bidAmount,
            'cpc' => $cpc,
            'platform_status' => self::platformStatus($snapshot),
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{lower: ?int, upper: ?int, on_file: bool}
     */
    private static function audienceSize(array $snapshot): array
    {
        $lower = null;
        $upper = null;
        $sets = data_get($snapshot, 'ad_set_optimization.ad_sets');

        if (is_array($sets)) {
            foreach ($sets as $set) {
                if (! is_array($set)) {
                    continue;
                }

                $setLower = data_get($set, 'audience.audience_size_lower');
                $setUpper = data_get($set, 'audience.audience_size_upper');

                if (is_numeric($setLower)) {
                    $lower = $lower === null ? (int) $setLower : min($lower, (int) $setLower);
                }

                if (is_numeric($setUpper)) {
                    $upper = $upper === null ? (int) $setUpper : max($upper, (int) $setUpper);
                }
            }
        }

        return [
            'lower' => $lower,
            'upper' => $upper,
            'on_file' => $lower !== null || $upper !== null,
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function audienceMode(array $snapshot): string
    {
        $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';
    }

    /**
     * CPM up while reach stays flat: the pool is saturating.
     *
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $delivery
     */
    private static function audienceSaturated(array $snapshot, array $delivery): bool
    {
        $seven = is_array(data_get($snapshot, 'windows.7d')) ? data_get($snapshot, 'windows.7d') : [];
        $fifteen = is_array(data_get($snapshot, 'windows.15d')) ? data_get($snapshot, 'windows.15d') : [];
        $cpmNow = isset($delivery['cpm']) && is_numeric($delivery['cpm'])
            ? (float) $delivery['cpm']
            : self::cpmFromWindow($seven);
        $cpmPrior = self::cpmFromWindow($fifteen);
        $lift = (float) config('campaign-decisions.defaults.saturation_cpm_lift', 0.15);
        $flat = (float) config('campaign-decisions.defaults.saturation_reach_flat', 0.10);

        if ($cpmNow === null || $cpmPrior === null || $cpmPrior <= 0 || $cpmNow < $cpmPrior * (1 + $lift)) {
            return false;
        }

        $reachNow = isset($delivery['reach']) && is_numeric($delivery['reach']) ? (int) $delivery['reach'] : null;
        $reachPrior = isset($fifteen['reach']) && is_numeric($fifteen['reach']) ? (int) $fifteen['reach'] : null;

        if ($reachNow !== null && $reachPrior !== null && $reachPrior > 0) {
            return abs($reachNow - $reachPrior) / $reachPrior <= $flat;
        }

        $imprNow = (int) ($seven['impressions'] ?? $delivery['impressions_7d'] ?? 0);
        $imprPrior = (int) ($fifteen['impressions'] ?? 0);

        if ($imprNow <= 0 || $imprPrior <= 0) {
            return false;
        }

        $expectedSeven = $imprPrior * 7 / 15;

        return $expectedSeven > 0 && abs($imprNow - $expectedSeven) / $expectedSeven <= $flat;
    }

    /**
     * @param  array<string, mixed>  $window
     */
    private static function cpmFromWindow(array $window): ?float
    {
        if (isset($window['cpm']) && is_numeric($window['cpm'])) {
            return (float) $window['cpm'];
        }

        $spend = (float) ($window['spend'] ?? 0);
        $impressions = (int) ($window['impressions'] ?? 0);

        if ($spend <= 0 || $impressions <= 0) {
            return null;
        }

        return round(($spend / $impressions) * 1000, 2);
    }

    /**
     * @param  array<string, mixed>  $delivery
     */
    private static function smallRetargetingPool(string $audienceMode, array $delivery): bool
    {
        if ($audienceMode !== 'retargeting') {
            return false;
        }

        $reach = isset($delivery['reach']) && is_numeric($delivery['reach']) ? (int) $delivery['reach'] : 0;
        $limit = (int) config('campaign-decisions.defaults.retargeting_small_pool_reach', 5000);

        return $reach > 0 && $reach < $limit;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function retargetingCtaMismatch(array $snapshot, string $audienceMode): bool
    {
        if ($audienceMode !== 'retargeting') {
            return false;
        }

        $ads = data_get($snapshot, 'creative_context.ads');
        if (! is_array($ads) || $ads === []) {
            $ads = data_get($snapshot, 'creative_context.creatives');
        }

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

        foreach ($ads as $ad) {
            if (is_array($ad) && CampaignAdRoster::isVagueCta($ad)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $delivery
     */
    private static function deliveryState(array $snapshot, array $delivery, ?string $learning): string
    {
        $spend = (float) ($delivery['spend_7d'] ?? 0);
        $impressions = (int) ($delivery['impressions_7d'] ?? 0);
        $status = self::platformStatus($snapshot);

        if (self::isArchivedStatus($status)) {
            return 'archived';
        }

        if (self::isPausedStatus($status)) {
            return 'paused';
        }

        if ($learning === 'FAIL' && $spend < 5 && $impressions < 100) {
            return 'not_delivering';
        }

        if ($spend <= 0 && $impressions <= 0) {
            $age = self::campaignAgeDays($snapshot);
            if ($age !== null && $age >= 3) {
                return 'not_delivering';
            }

            return 'not_delivering';
        }

        return 'delivering';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function platformStatus(array $snapshot): string
    {
        return strtoupper(trim((string) (
            data_get($snapshot, 'campaign_profile.platform_status')
            ?? data_get($snapshot, 'platform_status')
            ?? data_get($snapshot, 'campaign_profile.status')
            ?? data_get($snapshot, 'campaign_goals.status')
            ?? ''
        )));
    }

    private static function isPausedStatus(string $status): bool
    {
        return in_array($status, ['PAUSED', 'CAMPAIGN_PAUSED', 'ADSET_PAUSED'], true);
    }

    private static function isArchivedStatus(string $status): bool
    {
        return in_array($status, ['ARCHIVED', 'DELETED', 'REMOVED'], true);
    }

    private static function isCostCap(?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
     */
    private static function campaignAgeDays(array $snapshot): ?int
    {
        $started = data_get($snapshot, 'campaign_profile.started_at')
            ?? data_get($snapshot, 'started_at');

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

        try {
            return (int) Carbon::parse($started)->startOfDay()->diffInDays(now()->startOfDay());
        } catch (\Throwable) {
            return null;
        }
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $delivery
     */
    private static function feasibility(
        array $snapshot,
        string $kind,
        float $platformResults,
        array $delivery,
        string $deliveryState,
    ): string {
        if ($deliveryState === 'not_delivering') {
            return 'not_delivering';
        }

        if (in_array($kind, ['traffic', 'awareness'], true)) {
            $lpv = (int) ($delivery['landing_page_views'] ?? 0);
            $weeklyTarget = (int) config('campaign-decisions.defaults.meta_weekly_optimization_events', 50);

            if ($kind === 'traffic' && $lpv >= $weeklyTarget) {
                return 'ok';
            }

            return 'ok';
        }

        $budget = (float) (
            data_get($snapshot, 'campaign_profile.daily_budget')
            ?? data_get($snapshot, 'campaign_goals.daily_budget')
            ?? 0
        );
        $weeklyTarget = (float) config('campaign-decisions.defaults.meta_weekly_optimization_events', 50);
        $spend7 = (float) ($delivery['spend_7d'] ?? 0);

        if ($platformResults <= 0 && $spend7 >= (float) config('campaign-decisions.defaults.max_test_spend', 40)) {
            return 'underpowered_or_broken';
        }

        if ($platformResults > 0 && $platformResults < ($weeklyTarget * 0.25) && $budget > 0 && $budget <= 10) {
            return 'underpowered_budget';
        }

        if ($platformResults <= 0 && $budget > 0 && $budget <= 10) {
            return 'underpowered_budget';
        }

        return 'ok';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $delivery
     */
    private static function brokenStep(
        string $deliveryState,
        ?string $learning,
        string $feasibility,
        bool $creativeMismatch,
        bool $trackingMismatch,
        string $audienceMode,
        string $kind,
        array $delivery,
        float $platformResults,
        ?string $status,
    ): string {
        if ($deliveryState === 'archived') {
            return 'archived';
        }

        if ($deliveryState === 'paused') {
            return 'paused';
        }

        if ($creativeMismatch) {
            return 'creative_brand';
        }

        if ($deliveryState === 'not_delivering') {
            return 'delivery';
        }

        if (self::trackingGateOpen($kind, $delivery, $platformResults) || $trackingMismatch) {
            return 'tracking';
        }

        if ($feasibility === 'underpowered_budget' || $feasibility === 'underpowered_or_broken') {
            return 'volume';
        }

        if (in_array($learning, ['FAIL', 'LEARNING_LIMITED'], true) && $platformResults <= 0 && ! in_array($kind, ['traffic', 'awareness'], true)) {
            return 'volume';
        }

        if ($audienceMode === 'retargeting' && is_numeric($delivery['reach'] ?? null) && (int) $delivery['reach'] > 0 && (int) $delivery['reach'] < 800) {
            return 'reach_volume';
        }

        if ($status === CampaignDecisionVerdict::Learning->value && $learning === 'SUCCESS' && in_array($kind, ['traffic', 'awareness'], true)) {
            return 'none';
        }

        return 'review';
    }

    /**
     * Spend is well past the target CPA, people reached the page, and the
     * optimization event is still 0. Treat that as tracking or funnel
     * measurement, not a creative test.
     *
     * @param  array<string, mixed>  $delivery
     */
    private static function trackingGateOpen(string $kind, array $delivery, float $platformResults): bool
    {
        if (in_array($kind, ['traffic', 'awareness'], true)) {
            return false;
        }

        if ($platformResults > 0) {
            return false;
        }

        $spend = (float) ($delivery['spend_7d'] ?? 0);
        $target = (float) config('campaign-decisions.defaults.target_cpa', 50);
        $multiplier = (float) config('campaign-decisions.defaults.tracking_gate_spend_multiplier', 2);

        if ($spend < $target * $multiplier) {
            return false;
        }

        $lpv = (int) ($delivery['landing_page_views'] ?? 0);
        $clicks = (int) ($delivery['clicks_7d'] ?? 0);

        return $lpv > 0 || $clicks > 0;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $delivery
     */
    private static function platformResults(array $snapshot, string $kind, string $event, array $delivery = []): float
    {
        if (str_contains($event, 'landing_page') || $kind === 'traffic') {
            $lpv = $delivery['landing_page_views'] ?? data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery.landing_page_views');

            return is_numeric($lpv) ? (float) $lpv : (float) (data_get($snapshot, 'windows.7d.outbound_clicks') ?? 0);
        }

        $window = is_array(data_get($snapshot, 'windows.7d')) ? data_get($snapshot, 'windows.7d') : [];
        $adDelivery = is_array(data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery'))
            ? data_get($snapshot, 'ad_set_optimization.ad_sets.0.delivery')
            : [];
        $conversions = (float) ($window['conversions'] ?? $adDelivery['conversions'] ?? 0);
        $named = match (true) {
            str_contains($event, 'subscribe') || $kind === 'subscriptions' => (float) (
                $window['subscriptions'] ?? $adDelivery['subscriptions'] ?? 0
            ),
            str_contains($event, 'lead') || $kind === 'leads' => (float) (
                $window['leads'] ?? $adDelivery['leads'] ?? 0
            ),
            str_contains($event, 'purchase') || $kind === 'sales' => (float) (
                $window['purchases'] ?? $window['orders'] ?? $adDelivery['purchases'] ?? $adDelivery['orders'] ?? 0
            ),
            $kind === 'installs' => (float) ($window['installs'] ?? $adDelivery['installs'] ?? 0),
            default => 0.0,
        };

        return max($named, $conversions);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function internalResults(array $snapshot, bool $downloadInstall = false): float
    {
        $outcome = is_array(data_get($snapshot, 'windows.outcome_7d'))
            ? data_get($snapshot, 'windows.outcome_7d')
            : (is_array(data_get($snapshot, 'affiliate.7d')) ? data_get($snapshot, 'affiliate.7d') : []);

        if ($downloadInstall) {
            return (float) ($outcome['installs'] ?? 0);
        }

        return (float) ($outcome['leads'] ?? 0)
            + (float) ($outcome['subscriptions'] ?? 0)
            + (float) ($outcome['orders'] ?? 0)
            + (float) ($outcome['installs'] ?? 0);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function trackingMismatch(float $platform, float $internal, array $snapshot, string $kind = 'results', bool $downloadInstall = false): bool
    {
        if ($downloadInstall || in_array($kind, ['traffic', 'awareness'], true) || $platform < 1) {
            return false;
        }

        $outcome = data_get($snapshot, 'windows.outcome_7d') ?? data_get($snapshot, 'affiliate');

        if ($outcome === null) {
            return false;
        }

        return $internal + 0.5 < $platform;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private static function brandTokens(array $snapshot): array
    {
        $name = (string) (data_get($snapshot, 'campaign_profile.name') ?? '');
        $parts = preg_split('/[^a-zA-Z0-9]+/', $name) ?: [];
        $ignore = ['brand', 'awareness', 'retargeting', 'retarget', 'visitors', 'traffic', 'leads', 'sales', 'copy', 'image', 'video', 'lp', '30d', '7d', 'new', 'ad', 'ads', 'test', 'meta', 'google'];

        return array_values(array_filter(
            array_map(fn (string $part): string => strtolower($part), $parts),
            fn (string $part): bool => strlen($part) >= 4 && ! in_array($part, $ignore, true) && ! ctype_digit($part),
        ));
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  list<string>  $brandTokens
     */
    private static function creativeBrandMismatch(array $snapshot, array $brandTokens): bool
    {
        if ($brandTokens === []) {
            return false;
        }

        $products = [
            'lucos' => ['lucos', 'transform thoughts to code', 'one wrong file change', 'ai workspace', 'build and ship with lucos'],
            'attestpath' => ['attestpath', 'soc 2', 'soc2', 'compliance'],
            'cursor' => ['cursor'],
            'copilot' => ['copilot'],
        ];

        $campaignProducts = [];
        foreach ($products as $product => $needles) {
            foreach ($brandTokens as $token) {
                if ($token === $product || in_array($token, $needles, true)) {
                    $campaignProducts[] = $product;
                    break;
                }
            }
        }
        $campaignProducts = array_values(array_unique($campaignProducts));

        if ($campaignProducts === []) {
            return false;
        }

        $ads = is_array(data_get($snapshot, 'creative_context.ads')) ? data_get($snapshot, 'creative_context.ads') : [];

        foreach ($ads as $ad) {
            if (! is_array($ad)) {
                continue;
            }

            $text = strtolower(trim(implode(' ', array_filter([
                (string) ($ad['headline'] ?? ''),
                (string) ($ad['primary_text'] ?? ''),
            ]))));

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

            $mentionsOwn = false;
            foreach ($campaignProducts as $product) {
                foreach ($products[$product] as $needle) {
                    if (str_contains($text, $needle)) {
                        $mentionsOwn = true;
                        break 2;
                    }
                }
            }

            foreach ($products as $product => $needles) {
                if (in_array($product, $campaignProducts, true)) {
                    continue;
                }

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

        return false;
    }

    /**
     * @return array<string, float|null>
     */
    private static function targets(string $kind): array
    {
        return [
            'target_cpa' => (float) config('campaign-decisions.defaults.target_cpa', 50),
            'maximum_cpa' => (float) config('campaign-decisions.defaults.maximum_cpa', 75),
            'max_cpc' => (float) config('campaign-decisions.defaults.max_cpc', 2),
            'target_roas' => (float) config('campaign-decisions.defaults.target_roas', 2),
            'weekly_optimization_events' => (float) config('campaign-decisions.defaults.meta_weekly_optimization_events', 50),
            'min_ad_spend_to_judge' => (float) config('campaign-decisions.defaults.min_ad_spend_to_judge', 10),
        ];
    }

    /**
     * @param  array<string, mixed>  $delivery
     * @return list<string>
     */
    private static function allowedMoves(
        string $brokenStep,
        string $audienceMode,
        string $kind,
        string $feasibility,
        string $deliveryState,
        array $delivery = [],
        bool $audienceSaturated = false,
        bool $ctaMismatch = false,
    ): array {
        $moves = match ($brokenStep) {
            'delivery' => ['fix_delivery', 'lowest_cost_bid', 'raise_or_remove_cost_cap', 'hold_budget'],
            'paused' => ['cite_paused', 'hold_budget'],
            'archived' => ['cite_archived', 'hold_budget'],
            'creative_brand' => ['fix_creative_brand', 'hold_budget', 'hold_audience', 'hold_placements'],
            'tracking' => ['fix_tracking', 'hold_budget', 'hold_page_rewrite', 'hold_creative'],
            'volume' => ['raise_budget_to_learn', 'soften_optimization_event', 'hold_audience', 'advantage_plus_placements'],
            'reach_volume' => ['hold_audience', 'cite_reach'],
            'none' => ['maintain', 'optional_small_scale', 'fresh_creative_variants', 'hold_bid', 'hold_placements', 'hold_audience'],
            default => ['cite_metrics', 'objective_led_change', 'hold_invalid_placements'],
        };

        if ($audienceMode === 'retargeting') {
            $moves = array_values(array_unique([...$moves, 'widen_retargeting', 'exclude_converters', 'hold_cold_interests']));
        }

        if ($audienceSaturated && $audienceMode === 'retargeting') {
            $moves = array_values(array_unique([...$moves, 'widen_retargeting']));
        }

        if ($audienceSaturated && $audienceMode !== 'retargeting') {
            $moves = array_values(array_unique([...$moves, 'widen_audience']));
        }

        if ($ctaMismatch && $brokenStep !== 'tracking') {
            $moves = array_values(array_unique([...$moves, 'change_cta']));
        }

        $cpc = isset($delivery['cpc']) && is_numeric($delivery['cpc']) ? (float) $delivery['cpc'] : null;
        $ctr = isset($delivery['ctr_percent']) && is_numeric($delivery['ctr_percent']) ? (float) $delivery['ctr_percent'] : null;
        $maxCpc = (float) config('campaign-decisions.defaults.max_cpc', 2);

        if ($audienceMode !== 'retargeting' && $cpc !== null && $cpc > $maxCpc && $ctr !== null && $ctr >= 1.5) {
            $moves = array_values(array_unique([...$moves, 'trim_expensive_placement', 'widen_audience', 'lowest_cost_bid']));
        }

        return $moves;
    }

    /**
     * @return list<string>
     */
    private static function forbiddenMoves(
        string $brokenStep,
        string $audienceMode,
        string $kind,
        string $feasibility,
        string $deliveryState,
        ?string $learning,
        bool $ctaMismatch = false,
    ): array {
        $forbidden = ['invent_github_placements', 'invent_competitor_placements', 'invent_quality_ranking'];

        if ($audienceMode === 'retargeting') {
            $forbidden[] = 'add_cold_interests';
            $forbidden[] = 'enforce_cpc_ceiling';
            $forbidden[] = 'recommend_learn_more_on_retargeting';
        }

        if ($ctaMismatch) {
            $forbidden[] = 'keep_vague_cta';
        }

        if (in_array($deliveryState, ['paused', 'archived'], true) || in_array($brokenStep, ['paused', 'archived'], true)) {
            $forbidden[] = 'raise_budget';
            $forbidden[] = 'fix_delivery_as_if_live';
            $forbidden[] = 'test_plan_before_delivery_fix';
        }

        if (in_array($kind, ['traffic', 'awareness'], true)) {
            $forbidden[] = 'judge_on_conversions';
            $forbidden[] = 'hold_placements_for_conversion';
        }

        if ($deliveryState === 'not_delivering' || $brokenStep === 'delivery') {
            $forbidden[] = 'cost_cap_bid';
            $forbidden[] = 'restrict_placements';
            $forbidden[] = 'test_plan_before_delivery_fix';
        }

        if ($learning === 'SUCCESS' && $brokenStep === 'none') {
            $forbidden[] = 'restrict_placements';
            $forbidden[] = 'change_bid_strategy';
            $forbidden[] = 'change_audience';
            $forbidden[] = 'say_still_learning';
        }

        if ($feasibility === 'underpowered_budget') {
            $forbidden[] = 'keep_goal_unchanged_while_learning';
            $forbidden[] = 'say_monitoring_only';
        }

        if ($learning === 'LEARNING_LIMITED') {
            $forbidden[] = 'say_monitoring_only';
            $forbidden[] = 'say_still_learning';
        }

        if ($brokenStep === 'creative_brand') {
            $forbidden[] = 'keep_mismatched_creative';
        }

        if ($brokenStep === 'tracking') {
            $forbidden[] = 'rewrite_page_before_tracking';
            $forbidden[] = 'rewrite_creative_before_tracking';
            $forbidden[] = 'raise_budget';
            $forbidden[] = 'test_plan_before_tracking';
        }

        return array_values(array_unique($forbidden));
    }

    /**
     * @param  array<string, mixed>  $delivery
     * @param  array<string, float|null>  $targets
     * @param  array{lower?: ?int, upper?: ?int, on_file?: bool}  $audienceSize
     * @return list<string>
     */
    private static function mustSay(
        string $brokenStep,
        ?string $learning,
        string $feasibility,
        bool $trackingMismatch,
        bool $creativeMismatch,
        array $delivery,
        float $platformResults,
        float $internalResults,
        string $kind,
        array $targets,
        string $audienceMode,
        bool $audienceSaturated = false,
        bool $smallPool = false,
        bool $ctaMismatch = false,
        array $audienceSize = [],
        bool $downloadInstall = false,
        string $platformName = 'Meta',
    ): array {
        $lines = [];

        if ($learning !== null) {
            $lines[] = $platformName.' learning stage is '.$learning.'.';
        }

        if ($brokenStep === 'paused') {
            $lines[] = 'Campaign is paused on '.$platformName.'. Resume it before judging delivery, budget, or creatives.';
        }

        if ($brokenStep === 'archived') {
            $lines[] = 'This campaign is archived on '.$platformName.'. Do not treat this row as the live campaign; review the live copy.';
        }

        if ($brokenStep === 'delivery') {
            $lines[] = self::deliveryMustSay($delivery, $platformName);
        }

        if ($creativeMismatch) {
            $lines[] = 'At least one ad headline or copy does not match this campaign brand. Fix that creative before restarting spend.';
        }

        if ($downloadInstall) {
            $rate = $platformResults > 0 ? round(100 * $internalResults / $platformResults, 1) : 0.0;
            $spend = (float) ($delivery['spend_7d'] ?? 0);
            $lines[] = 'This is a download-to-install funnel. Meta conversions are file downloads. Internal results are installs. OUTCOME_LEADS with offsite conversions is the usual Meta setup for a desktop download, not a CRM lead form.';
            $lines[] = 'Meta reports '.$platformResults.' downloads and internal records show '.$internalResults.' installs'
                .($platformResults > 0 ? ' ('.$rate.'% install rate)' : '')
                .'. That gap is expected. Do not treat it as a pixel, CAPI, form, or CRM mismatch.';
            if ($internalResults > 0 && $spend > 0) {
                $lines[] = 'Judge this campaign on cost per install ($'.number_format($spend / $internalResults, 2).'), not cost per lead.';
            } else {
                $lines[] = 'Judge this campaign on cost per install, not cost per lead.';
            }
        }

        if ($trackingMismatch) {
            $lines[] = 'Platform results are '.$platformResults.' and internal results are '.$internalResults.'. Treat this as a tracking mismatch before rewriting the page.';
        }

        if ($brokenStep === 'tracking' && ! $trackingMismatch) {
            $spend = round((float) ($delivery['spend_7d'] ?? 0), 2);
            $lpv = (int) ($delivery['landing_page_views'] ?? 0);
            $line = 'Spent $'.number_format($spend, 2).' against '.self::resultLabel((string) ($kind === 'subscriptions' ? 'subscribe' : $kind), $kind).' with 0 results';
            if ($lpv > 0) {
                $line .= ' after '.$lpv.' landing page views';
            }
            $trackingTool = match ($platformName) {
                'LinkedIn' => 'LinkedIn Insight Tag and conversions',
                'Google' => 'Google Tag and conversions',
                default => 'Events Manager',
            };
            $lines[] = $line.'. Check '.$trackingTool.' and a test conversion before changing ads or the page. Use cost per landing page view as the stand-in metric only.';
        }

        if ($feasibility === 'underpowered_budget') {
            $lines[] = 'Daily budget is too low to reliably finish '.$platformName.' learning for this conversion goal (about '.(int) ($targets['weekly_optimization_events'] ?? 50).' results a week). Say raise budget or use an easier event.';
        }

        if ($brokenStep !== 'delivery'
            && $learning === 'LEARNING_LIMITED'
            && self::isCostCap(is_string($delivery['bid_strategy'] ?? null) ? (string) $delivery['bid_strategy'] : null)) {
            $lines[] = self::deliveryMustSay($delivery);
        }

        if ($kind === 'traffic' && ($delivery['landing_page_views'] ?? null) !== null) {
            $lines[] = 'Judge this campaign on landing page views'
                .($delivery['cost_per_lpv'] !== null ? ' and cost per landing page view ($'.$delivery['cost_per_lpv'].')' : '')
                .'.';
        }

        foreach (['cpm' => 'CPM', 'reach' => 'reach', 'frequency' => 'frequency'] as $key => $label) {
            if (isset($delivery[$key]) && $delivery[$key] !== null) {
                $lines[] = $label.' is '.(is_float($delivery[$key]) ? number_format((float) $delivery[$key], 2) : (string) $delivery[$key]).'.';
            }
        }

        if (($delivery['ctr_percent'] ?? null) !== null) {
            $lines[] = 'Link-click CTR is '.number_format((float) $delivery['ctr_percent'], 2).'%.';
        }

        $cpc = isset($delivery['cpc']) && is_numeric($delivery['cpc']) ? (float) $delivery['cpc'] : null;
        $ctr = isset($delivery['ctr_percent']) && is_numeric($delivery['ctr_percent']) ? (float) $delivery['ctr_percent'] : null;
        $maxCpc = (float) ($targets['max_cpc'] ?? 2);

        if ($audienceMode !== 'retargeting' && $cpc !== null && $cpc > $maxCpc && $ctr !== null && $ctr >= 1.5) {
            $lines[] = 'CPC is above the internal $'.number_format($maxCpc, 2).' target. Name the next control: turn off the highest-CPC placement that has clicks and no result, widen the audience, or switch to lowest cost if a cap is on. Do not leave bring CPC under $2 as the whole action.';
        }

        if ($audienceSaturated) {
            $lines[] = 'CPM is rising while reach is flat. The audience is saturating — widen the pool. Do not add GitHub or other invented placements.';
        }

        if ($smallPool) {
            $lines[] = 'This retargeting pool is under about '.(int) config('campaign-decisions.defaults.retargeting_small_pool_reach', 5000).' reach. Recheck frequency weekly. Fatigue will come fast.';
        }

        if ($ctaMismatch) {
            $lines[] = 'At least one retargeting ad uses a vague CTA such as See details or Learn more. These people already visited the page — use Sign up, Subscribe, or Get offer.';
        }

        if (($audienceSize['on_file'] ?? false) === true) {
            $lower = $audienceSize['lower'] ?? null;
            $upper = $audienceSize['upper'] ?? null;
            $range = match (true) {
                is_numeric($lower) && is_numeric($upper) && (int) $lower !== (int) $upper => number_format((int) $lower).' to '.number_format((int) $upper),
                is_numeric($lower) => number_format((int) $lower),
                is_numeric($upper) => number_format((int) $upper),
                default => null,
            };

            if ($range !== null) {
                $lines[] = 'Audience size on file is '.$range.'.';
            }
        } else {
            $lines[] = 'Audience size is not on file. Do not invent a pool size.';
        }

        if (($delivery['previous_7d_ctr_percent'] ?? null) !== null && ($delivery['ctr_percent'] ?? null) !== null) {
            $lines[] = 'Last 7-day CTR is '.number_format((float) $delivery['ctr_percent'], 2)
                .'% vs '.number_format((float) $delivery['previous_7d_ctr_percent'], 2).'% in the prior 7 days.';
        }

        return $lines;
    }

    /**
     * @param  list<string>  $forbidden
     * @return list<string>
     */
    private static function mustNotSay(array $forbidden, string $audienceMode, string $kind, string $deliveryState, bool $ctaMismatch = false, bool $downloadInstall = false, bool $cheaperPlacement = false, string $platformName = 'Meta'): array
    {
        $lines = [];

        if ($cheaperPlacement) {
            $lines[] = 'Do not say keep Advantage+ placements unchanged when a cheaper publisher is on file.';
        }

        if ($downloadInstall) {
            $lines[] = 'Do not describe this as a leads campaign, a broken pixel, or a CRM tracking mismatch.';
            $lines[] = 'Do not tell the buyer to check Events Manager, the Conversions API, the form, or the CRM because Meta downloads exceed internal installs.';
        }

        if (in_array('invent_github_placements', $forbidden, true) && $platformName === 'Meta') {
            $lines[] = 'Do not say Meta can show ads on GitHub, Stack Overflow, or VS Code as placements.';
        }

        if (in_array('invent_quality_ranking', $forbidden, true)) {
            $lines[] = 'Do not invent a quality ranking such as bottom 35 percent. If ranking is missing, say ranking not on file.';
        }

        if (in_array('add_cold_interests', $forbidden, true) || $audienceMode === 'retargeting') {
            $lines[] = 'Do not add cold interest audiences to a retargeting ad set.';
        }

        if (in_array('enforce_cpc_ceiling', $forbidden, true) || $audienceMode === 'retargeting') {
            $lines[] = 'Do not treat the $2 CPC ceiling as a '.$platformName.' limit or the first action on a small retargeting pool. Judge whether clicks become the objective result.';
        }

        if (in_array('judge_on_conversions', $forbidden, true)) {
            $lines[] = 'Do not judge placements or ads on conversions for a traffic or awareness campaign.';
        }

        if (in_array('cost_cap_bid', $forbidden, true)) {
            $lines[] = 'Do not recommend a cost cap to restart delivery on a low budget.';
        }

        if (in_array('say_still_learning', $forbidden, true) || in_array('say_monitoring_only', $forbidden, true)) {
            $lines[] = 'Do not say the campaign is still learning or monitoring only when '.$platformName.' learning succeeded or delivery is broken or the budget cannot learn.';
        }

        if (in_array('keep_mismatched_creative', $forbidden, true)) {
            $lines[] = 'Do not keep a creative whose headline belongs to another product.';
        }

        if (in_array('rewrite_page_before_tracking', $forbidden, true)) {
            $lines[] = 'Do not rewrite the landing page until tracking is checked.';
        }

        if (in_array('rewrite_creative_before_tracking', $forbidden, true)) {
            $lines[] = 'Do not replace ads or write new creative tests until the optimization event is firing.';
        }

        if (in_array('recommend_learn_more_on_retargeting', $forbidden, true) || $ctaMismatch) {
            $lines[] = 'Do not recommend Learn more or See details as the CTA on retargeting. Use Sign up, Subscribe, or Get offer.';
        }

        if ($deliveryState === 'not_delivering') {
            $lines[] = 'Do not propose a creative or page test plan until delivery restarts.';
            $lines[] = 'Do not say ads are paused, rejected, or that payment failed unless platform status says so. Name a cost cap when one is on file.';
        }

        if (in_array($deliveryState, ['paused', 'archived'], true)) {
            $lines[] = 'Do not treat this as a live delivery failure or recommend bid, budget, or creative tests until the campaign is resumed.';
        }

        $lines[] = 'Do not use paused ads or paused ad sets when judging live delivery, fatigue, or What to do next. Name them as paused.';
        $lines[] = 'Landing page views are not outbound clicks or link clicks. Do not write a 100% LPV rate when link clicks and landing page views differ.';
        $lines[] = 'Name the bid strategy with the Ads Manager option (Highest volume, Cost per result goal, or Bid cap) and what it does. Do not print the API constant as if it were the Ads Manager label.';

        return $lines;
    }

    /**
     * @param  array<string, mixed>  $delivery
     */
    private static function deliveryMustSay(array $delivery, string $platformName = 'Meta'): string
    {
        $strategy = is_string($delivery['bid_strategy'] ?? null) ? (string) $delivery['bid_strategy'] : null;
        $cap = isset($delivery['bid_amount']) && is_numeric($delivery['bid_amount'])
            ? round((float) $delivery['bid_amount'], 2)
            : null;
        $costPerLpv = isset($delivery['cost_per_lpv']) && is_numeric($delivery['cost_per_lpv'])
            ? round((float) $delivery['cost_per_lpv'], 2)
            : null;

        if (self::isCostCap($strategy)) {
            $line = 'The bid is a cost cap'
                .($cap !== null ? ' of $'.number_format($cap, 2) : '')
                .' per result.';

            if ($costPerLpv !== null) {
                $line .= ' Cost per landing page view on file is $'.number_format($costPerLpv, 2).'.';
                if ($cap !== null && $costPerLpv >= $cap * 0.8) {
                    $line .= ' The cap is too close to actual cost, so '.$platformName.' is not spending.';
                }
            } else {
                $line .= ' The cap is blocking spend.';
            }

            return $line.' Step 1: switch to lowest cost (Highest volume) or raise the cap. Do not raise the budget until the campaign spends almost the full daily amount.';
        }

        return 'Campaign is not delivering. Prefer lowest cost to restart. Check the bid limit and audience size. Do not assume ads are paused, rejected, or that payment failed unless status says so.';
    }

    /**
     * @return list<string>
     */
    private static function metricsRequired(string $kind, string $audienceMode): array
    {
        $metrics = ['spend', 'impressions', 'link_clicks', 'ctr_percent', 'cpm', 'reach', 'frequency'];

        if ($kind === 'traffic') {
            $metrics[] = 'landing_page_views';
            $metrics[] = 'cost_per_lpv';
        }

        if (in_array($kind, ['leads', 'subscriptions', 'sales', 'installs'], true)) {
            $metrics[] = 'platform_results';
            $metrics[] = 'internal_results';
            $metrics[] = 'cost_per_result';
        }

        if ($kind === 'installs') {
            $metrics[] = 'cost_per_install';
            $metrics[] = 'install_rate';
        }

        if ($audienceMode === 'retargeting') {
            $metrics[] = 'reach';
            $metrics[] = 'frequency';
        }

        return array_values(array_unique($metrics));
    }
}
