<?php

namespace App\Library\CampaignDecision;

/**
 * Chooses the next marketing lever from numbers already on the decision snapshot.
 * Spend, creative, and landing page are ranked. The model explains this call; it does not replace it.
 */
class CampaignMarketingDiagnosis
{
    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     window_used: string,
     *     lookup_basis: string,
     *     plan: list<string>,
     *     signals: array<string, float|int|string|null>
     * }
     */
    public function fromSnapshot(array $snapshot): array
    {
        $verdict = (string) ($snapshot['verdict'] ?? $snapshot['final_verdict'] ?? '');
        $metricsAvailable = data_get($snapshot, 'capabilities.platform_metrics_available');

        if ($verdict === CampaignDecisionVerdict::DataIssue->value || $metricsAvailable === false) {
            $signals = [
                'ctr_percent' => null,
                'clicks' => 0,
                'impressions' => 0,
                'results' => 0.0,
                'outcome_spend' => 0.0,
                'revenue' => 0.0,
                'landing_pages' => 0,
            ];
            $call = $this->call(
                'hold',
                'no',
                'unknown',
                'unknown',
                'Do not spend more, and do not blame the creative or the landing page yet. Platform stats are missing, so there is no click or conversion evidence.',
                $signals,
            );

            return $this->withPlan($call, $snapshot, '7d', 'missing');
        }

        $window7 = $this->windowSlice($snapshot, '7d');
        $window15 = $this->windowSlice($snapshot, '15d');
        $sevenSubstantial = $this->isSubstantial($window7);
        $fifteenSubstantial = $this->isSubstantial($window15);
        $softPrep = $this->isSoftPrepVerdict($verdict);

        if (! $sevenSubstantial && ! $fifteenSubstantial) {
            if ($softPrep) {
                return $this->withPlan(
                    $this->softPrepFromSignals($snapshot, $window7),
                    $snapshot,
                    '7d',
                    'learning_prep',
                );
            }

            $call = $this->call(
                'hold',
                'no',
                'unknown',
                'unknown',
                'Do not spend more yet. There is not enough click and conversion evidence to choose between a new creative and a landing-page fix.',
                [
                    'ctr_percent' => null,
                    'clicks' => (int) ($window7['clicks'] ?? 0),
                    'impressions' => (int) ($window7['impressions'] ?? 0),
                    'results' => 0.0,
                    'outcome_spend' => 0.0,
                    'revenue' => 0.0,
                    'landing_pages' => count($this->landingPaths($snapshot)),
                ],
            );

            return $this->withPlan($call, $snapshot, '7d', 'thin');
        }

        $windowUsed = $sevenSubstantial ? '7d' : '15d';
        $day = $sevenSubstantial ? $window7 : $window15;
        $call = $this->diagnoseFromDay($snapshot, $day);

        if ($softPrep) {
            $call = $this->softenForLearning($call, $snapshot, $day);
        }

        return $this->withPlan($call, $snapshot, $windowUsed, $windowUsed === '15d' ? '15d' : '7d');
    }

    private function isSoftPrepVerdict(string $verdict): bool
    {
        return in_array($verdict, [
            CampaignDecisionVerdict::Learning->value,
            CampaignDecisionVerdict::InsufficientData->value,
        ], true);
    }

    /**
     * Provisional prep lever from early signals while budget stays locked.
     *
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $day
     * @return array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     signals: array<string, float|int|string|null>
     * }
     */
    private function softPrepFromSignals(array $snapshot, array $day): array
    {
        $outcome = $this->outcome($snapshot);
        $impressions = (int) ($day['impressions'] ?? 0);
        $clicks = (int) ($day['clicks'] ?? 0);
        $spend = (float) ($day['spend'] ?? 0);
        $ctr = $impressions > 0 ? $clicks / $impressions : null;
        $ctrPercent = $ctr === null ? null : round($ctr * 100, 2);
        $results = $this->countedResults($snapshot, $outcome, $day);
        $outcomeSpend = (float) ($outcome['platform_spend'] ?? $outcome['spend'] ?? $spend);
        $landingPaths = $this->landingPaths($snapshot);
        $weakCtr = (float) config('campaign-decisions.marketing.weak_ctr', 0.008);

        $signals = [
            'ctr_percent' => $ctrPercent,
            'clicks' => $clicks,
            'impressions' => $impressions,
            'results' => $results === null ? null : round($results, 2),
            'outcome_spend' => round($outcomeSpend, 2),
            'revenue' => round((float) ($outcome['revenue'] ?? $outcome['net_revenue'] ?? 0), 2),
            'landing_pages' => count($landingPaths),
            'soft_prep' => 1,
        ];

        if ($results === null) {
            return $this->call(
                'hold',
                'no',
                'unknown',
                'unknown',
                'While learning, keep the budget steady. This campaign buys visits, and landing-page views are not on this window, so do not rewrite the page yet.',
                $signals,
            );
        }

        if ($this->objectiveKind($snapshot) === 'traffic' && $results > 0) {
            return $this->call(
                'hold',
                'no',
                'not_the_constraint',
                'not_the_constraint',
                'While learning, keep the budget steady. The clicks are opening the page, so do not rewrite it. Score visits, not purchases.',
                $signals,
            );
        }

        if ($clicks === 0 && ($impressions > 0 || $spend > 0)) {
            return $this->call(
                'improve_creative',
                'no',
                'primary',
                'not_tested',
                'While learning, keep budget steady and draft 2–3 stronger creative hooks — impressions are arriving without clicks, so the page has not been tested yet.',
                $signals,
            );
        }

        if ($clicks > 0 && $results <= 0) {
            $shared = count($landingPaths) === 1 ? ' Page owner: start from '.$landingPaths[0].'.' : '';

            return $this->call(
                'fix_landing_page',
                'no',
                'not_the_constraint',
                'primary',
                'While learning, keep budget steady and prep a clearer above-the-fold offer + one CTA for the page owner — clicks arrive but lagged results are still missing.'.$shared,
                $signals,
            );
        }

        if ($ctr !== null && $impressions > 0 && $ctr < $weakCtr) {
            return $this->call(
                'improve_creative',
                'no',
                'primary',
                'unknown',
                'While learning, keep budget steady and draft stronger creative — early CTR is about '.$this->number($ctrPercent).'%.',
                $signals,
            );
        }

        return $this->call(
            'hold',
            'no',
            'unknown',
            'unknown',
            'While learning, keep budget steady and draft the next creative and landing-page tests so you can ship when volume arrives.',
            $signals,
        );
    }

    /**
     * @param  array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     signals: array<string, float|int|string|null>
     * }  $call
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $day
     * @return array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     signals: array<string, float|int|string|null>
     * }
     */
    private function softenForLearning(array $call, array $snapshot, array $day): array
    {
        $lever = (string) ($call['primary_lever'] ?? 'hold');
        $signals = is_array($call['signals'] ?? null) ? $call['signals'] : [];
        $signals['soft_prep'] = 1;

        if ($lever === 'spend_more') {
            return $this->call(
                'hold',
                'no',
                'not_the_constraint',
                'not_the_constraint',
                'While learning, keep budget steady even though early results look promising — draft the next creative and page tests, then scale after learning finishes.',
                $signals,
            );
        }

        if ($lever === 'hold') {
            return $this->softPrepFromSignals($snapshot, $day);
        }

        if ($lever === 'improve_creative') {
            return $this->call(
                'improve_creative',
                'no',
                (string) ($call['creative'] ?? 'primary'),
                (string) ($call['landing_page'] ?? 'unknown'),
                'While learning, keep budget steady and draft 2–3 stronger creative hooks so more people click through.',
                $signals,
            );
        }

        if ($lever === 'fix_landing_page') {
            $paths = $this->landingPaths($snapshot);
            $shared = count($paths) === 1 ? ' Hand off to the page owner starting from '.$paths[0].'.' : ' Hand off concrete page fixes to the page owner.';

            return $this->call(
                'fix_landing_page',
                'no',
                (string) ($call['creative'] ?? 'not_the_constraint'),
                'primary',
                'While learning, keep budget steady and prep a clearer offer + one CTA for the page owner — post-click results are the early blocker.'.$shared,
                $signals,
            );
        }

        $call['spend_more'] = 'no';
        $call['signals'] = $signals;

        return $call;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $day
     * @return array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     signals: array<string, float|int|string|null>
     * }
     */
    private function diagnoseFromDay(array $snapshot, array $day): array
    {
        $outcome = $this->outcome($snapshot);
        $impressions = (int) ($day['impressions'] ?? 0);
        $clicks = (int) ($day['clicks'] ?? 0);
        $ctr = $impressions > 0 ? $clicks / $impressions : null;
        $results = $this->countedResults($snapshot, $outcome, $day);
        $outcomeSpend = (float) ($outcome['platform_spend'] ?? $outcome['spend'] ?? $day['spend'] ?? 0);
        $revenue = (float) ($outcome['revenue'] ?? $outcome['net_revenue'] ?? 0);
        $minSpend = (float) config('campaign-decisions.defaults.minimum_spend', 25);
        $minRoas = (float) config('campaign-decisions.defaults.minimum_roas', 1.2);
        $weakCtr = (float) config('campaign-decisions.marketing.weak_ctr', 0.008);
        $strongCtr = (float) config('campaign-decisions.marketing.strong_ctr', 0.015);
        $minImpressions = (int) config('campaign-decisions.marketing.min_impressions_for_ctr', 500);
        $minClicks = (int) config('campaign-decisions.marketing.min_clicks_to_judge_page', 8);
        $zeroClickFloor = (float) config('campaign-decisions.defaults.zero_click_spend_floor', 10);
        $daySpend = (float) ($day['spend'] ?? 0);
        $landingPaths = $this->landingPaths($snapshot);
        $ctrPercent = $ctr === null ? null : round($ctr * 100, 2);

        $signals = [
            'ctr_percent' => $ctrPercent,
            'clicks' => $clicks,
            'impressions' => $impressions,
            'results' => $results === null ? null : round($results, 2),
            'outcome_spend' => round($outcomeSpend, 2),
            'revenue' => round($revenue, 2),
            'landing_pages' => count($landingPaths),
        ];

        $ctrIsWeak = $ctr !== null && $impressions >= $minImpressions && $ctr < $weakCtr;
        $ctrIsStrong = $ctr !== null && $impressions >= $minImpressions && $ctr >= $strongCtr;
        $pageWasTested = $clicks >= $minClicks || $outcomeSpend >= $minSpend;
        $noClicks = $clicks === 0 && ($impressions >= $minImpressions || $daySpend >= $zeroClickFloor);
        $kind = $this->objectiveKind($snapshot);

        if ($results === null) {
            return $this->call(
                'hold',
                'no',
                'unknown',
                'unknown',
                'Do not rewrite the page yet. This campaign buys visits, and landing-page views are not on this window.',
                $signals,
            );
        }

        if ($kind === 'traffic' && $results > 0) {
            return $this->call(
                'hold',
                'no',
                'not_the_constraint',
                'not_the_constraint',
                'Do not rewrite the landing page. This campaign buys visits, and the clicks are opening the page.',
                $signals,
            );
        }

        if ($noClicks) {
            return $this->call(
                'improve_creative',
                'no',
                'primary',
                'not_tested',
                sprintf(
                    'Do not spend more. Improve the creative first. %d impressions produced 0 clicks, so the landing page has not been tested.',
                    $impressions,
                ),
                $signals,
            );
        }

        if ($results <= 0 && $pageWasTested && ! $ctrIsWeak) {
            return $this->call(
                'fix_landing_page',
                'no',
                $ctrIsStrong ? 'not_the_constraint' : 'secondary',
                'primary',
                $this->landingSummary($clicks, $ctrPercent, $outcomeSpend, $landingPaths),
                $signals,
            );
        }

        if ($ctrIsWeak && $results > 0) {
            return $this->call(
                'improve_creative',
                'no',
                'primary',
                'not_the_constraint',
                sprintf(
                    'Do not spend more yet. CTR is %s%%, which is weak, while the page already produced %s results. A stronger creative should bring more of the clicks that already convert.',
                    $this->number($ctrPercent),
                    $this->number($results),
                ),
                $signals,
            );
        }

        $roas = $outcomeSpend > 0 ? $revenue / $outcomeSpend : null;

        if ($results > 0 && $roas !== null && $roas >= $minRoas && ($ctrIsStrong || $ctr === null || $impressions < $minImpressions)) {
            if ($this->creativeSpread($snapshot)) {
                return $this->call(
                    'improve_creative',
                    'only_after_reallocation',
                    'primary',
                    'not_the_constraint',
                    'Do not raise the campaign budget yet. One ad is earning clicks at about twice the rate of another. Shift spend to the stronger creative before buying more traffic.',
                    $signals,
                );
            }

            return $this->call(
                'spend_more',
                'yes',
                'not_the_constraint',
                'not_the_constraint',
                sprintf(
                    'Spend more. Lagged return is %s on %s spend, with %s results, which clears the minimum return. Creative and landing page are not the constraint.',
                    $this->number($roas),
                    $this->number($outcomeSpend),
                    $this->number($results),
                ),
                $signals,
            );
        }

        if ($results > 0 && $roas !== null && $roas < $minRoas && ! in_array($kind, ['leads', 'subscriptions', 'installs', 'traffic'], true)) {
            return $this->call(
                'fix_landing_page',
                'no',
                $ctrIsWeak ? 'secondary' : 'not_the_constraint',
                'primary',
                sprintf(
                    'Do not spend more. The page is producing results, but return is %s on %s spend, below the minimum. Fix the offer or the landing page before buying more traffic.',
                    $this->number($roas),
                    $this->number($outcomeSpend),
                ),
                $signals,
            );
        }

        return $this->call(
            'hold',
            'no',
            'unknown',
            'unknown',
            'Do not spend more yet. There is not enough click and conversion evidence to choose between a new creative and a landing-page fix.',
            $signals,
        );
    }

    /**
     * @param  array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     signals: array<string, float|int|string|null>
     * }  $call
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     window_used: string,
     *     lookup_basis: string,
     *     plan: list<string>,
     *     signals: array<string, float|int|string|null>
     * }
     */
    private function withPlan(array $call, array $snapshot, string $windowUsed, string $basis): array
    {
        $verdict = (string) ($snapshot['verdict'] ?? $snapshot['final_verdict'] ?? '');

        return array_merge($call, [
            'window_used' => $windowUsed,
            'lookup_basis' => $basis,
            'plan' => $this->buildPlan($call, $verdict, $windowUsed, $basis, $snapshot),
        ]);
    }

    /**
     * @param  array{primary_lever: string, summary: string}  $call
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private function buildPlan(array $call, string $verdict, string $windowUsed, string $basis, array $snapshot): array
    {
        $history = data_get($snapshot, 'daily_history');
        $lookup = is_array($history) ? self::lookupLine($history, $basis) : '';
        $line1 = $lookup !== '' ? $lookup : match ($basis) {
            '15d' => 'Last 7 days were too thin, so this uses the last 15 days. Results are still from the lagged 7-day window.',
            'thin' => 'Checked the last 7 days.',
            'learning_prep' => 'Checked the last 7 days for soft prep while learning — budget stays unchanged.',
            'missing' => 'Checked the last 7 days.',
            default => $windowUsed === '15d'
                ? 'Checked the last 15 days.'
                : 'Checked the last 7 days.',
        };

        $line2 = $this->planActionLine($call['primary_lever'], $verdict, $snapshot);
        $line3 = $this->planWhyLine($call['summary']);

        return array_values(array_filter([$line1, $line2, $line3], fn (string $line): bool => $line !== ''));
    }

    /**
     * One sentence naming the days actually on file and the window that chose the lever.
     *
     * @param  array<string, mixed>  $history
     */
    public static function lookupLine(array $history, string $basis): string
    {
        $onFile = (int) ($history['days_on_file'] ?? 0);
        $expected = (int) ($history['expected_days'] ?? 0);
        $from = is_string($history['from'] ?? null) ? $history['from'] : '';
        $to = is_string($history['to'] ?? null) ? $history['to'] : '';

        if ($onFile < 1 || $expected < 1 || $from === '' || $to === '') {
            return '';
        }

        $span = $onFile >= $expected
            ? 'Looked at the last '.$expected.' days, from '.$from.' to '.$to
            : 'Looked at '.$onFile.' of the last '.$expected.' days, from '.$from.' to '.$to;

        $decision = match ($basis) {
            '15d' => ', and decided from the last 15 days because the last 7 days were too thin',
            'thin' => ', and the last 7 days and the last 15 days were too thin to choose a lever',
            'learning_prep' => ', and chose soft prep from early signals while learning (budget unchanged)',
            'missing' => ', and the last 7 days could not choose a lever because platform stats were missing',
            default => ', and decided from the last 7 days',
        };

        return $span.$decision.'.';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function planActionLine(string $lever, string $verdict, array $snapshot): string
    {
        $learning = in_array($verdict, [
            CampaignDecisionVerdict::Learning->value,
            CampaignDecisionVerdict::InsufficientData->value,
        ], true);

        $marketingOnly = match ($lever) {
            'improve_creative' => $learning
                ? 'While learning, draft 2–3 new creative hooks (budget unchanged).'
                : 'Refresh the creative with 2–3 new hooks and visuals so more people click through.',
            'fix_landing_page' => $learning
                ? 'While learning, prep a clearer offer + one CTA for the page owner (budget unchanged).'
                : 'Improve the landing page: clearer offer above the fold, message match with the ad, and one strong CTA.',
            'spend_more' => 'Results support careful scaling once the next review confirms.',
            'hold' => $learning
                ? 'While learning, keep budget steady and draft the next creative and page tests.'
                : 'Keep watching until there is enough click and conversion evidence, and draft the next test meanwhile.',
            default => 'Keep watching and gather another day of signal.',
        };

        $budgetSummary = CampaignBudgetRecommendation::fromStored($verdict, $snapshot)['summary'] ?? null;

        if ($lever === 'spend_more' && $verdict === CampaignDecisionVerdict::ScaleUp->value && $budgetSummary !== null) {
            return $budgetSummary;
        }

        if ($lever === 'hold' && $budgetSummary !== null) {
            return $budgetSummary;
        }

        if (! in_array($lever, ['improve_creative', 'fix_landing_page'], true) || $budgetSummary === null) {
            return $marketingOnly;
        }

        if (! in_array($verdict, [
            CampaignDecisionVerdict::DecreaseBudget->value,
            CampaignDecisionVerdict::Pause->value,
            CampaignDecisionVerdict::ScaleUp->value,
        ], true)) {
            return $marketingOnly;
        }

        $lead = rtrim($budgetSummary, '.');

        if ($verdict === CampaignDecisionVerdict::ScaleUp->value) {
            $tail = match ($lever) {
                'fix_landing_page' => 'only after the landing page is fixed',
                'improve_creative' => 'only after the creative is improved',
                default => '',
            };

            return $tail === '' ? $budgetSummary : $lead.' '.$tail.'.';
        }

        $tail = match ($lever) {
            'fix_landing_page' => 'and fix the landing page before only cutting spend',
            'improve_creative' => 'and improve the creative before only cutting spend',
            default => '',
        };

        return $tail === '' ? $budgetSummary : $lead.', '.$tail.'.';
    }

    private function planWhyLine(string $summary): string
    {
        $why = trim($summary);
        $why = preg_replace('/^Do not spend more(?: yet)?\.\s*/i', '', $why) ?? $why;
        $why = preg_replace('/^Spend more\.\s*/i', '', $why) ?? $why;

        return trim($why);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>
     */
    private function windowSlice(array $snapshot, string $key): array
    {
        $window = data_get($snapshot, 'windows.'.$key);

        if (! is_array($window) || $window === []) {
            if ($key === '7d') {
                $window = data_get($snapshot, 'last_7_days', []);
            }
        }

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

    /**
     * @param  array<string, mixed>  $window
     */
    private function isSubstantial(array $window): bool
    {
        $impressions = (int) ($window['impressions'] ?? 0);
        $clicks = (int) ($window['clicks'] ?? 0);
        $spend = (float) ($window['spend'] ?? 0);
        $minImpressions = (int) config('campaign-decisions.marketing.min_impressions_for_ctr', 500);
        $minClicks = (int) config('campaign-decisions.marketing.min_clicks_to_judge_page', 8);
        $minSpend = (float) config('campaign-decisions.defaults.minimum_spend', 25);

        return $impressions >= $minImpressions
            || $clicks >= $minClicks
            || $spend >= $minSpend;
    }

    /**
     * @param  array<string, float|int|string|null>  $signals
     * @return array{
     *     primary_lever: string,
     *     summary: string,
     *     spend_more: string,
     *     creative: string,
     *     landing_page: string,
     *     signals: array<string, float|int|string|null>
     * }
     */
    private function call(
        string $lever,
        string $spendMore,
        string $creative,
        string $landingPage,
        string $summary,
        array $signals,
    ): array {
        return [
            'primary_lever' => $lever,
            'summary' => $summary,
            'spend_more' => $spendMore,
            'creative' => $creative,
            'landing_page' => $landingPage,
            'signals' => $signals,
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>
     */
    private function outcome(array $snapshot): array
    {
        $outcome = data_get($snapshot, 'channels.outcome');

        if (! is_array($outcome) || ($outcome['available'] ?? true) === false) {
            $window = data_get($snapshot, 'windows.outcome_7d', data_get($snapshot, 'affiliate.outcome_window', []));

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

        return $outcome;
    }

    /**
     * @param  array<string, mixed>  $outcome
     */
    private function objectiveKind(array $snapshot): string
    {
        return CampaignPerformanceStrategy::objectiveKind($snapshot);
    }

    /**
     * Objective result, or null when a traffic campaign has no landing-page views to count.
     * An empty objective keeps the old combined count.
     *
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $outcome
     * @param  array<string, mixed>  $day
     */
    private function countedResults(array $snapshot, array $outcome, array $day): ?float
    {
        $kind = $this->objectiveKind($snapshot);

        if ($kind === 'results') {
            return $this->results($outcome);
        }

        if ($kind === 'traffic') {
            if (! array_key_exists('outbound_clicks', $day) || $day['outbound_clicks'] === null) {
                return null;
            }

            return (float) $day['outbound_clicks'];
        }

        if ($kind === 'awareness') {
            return (float) ($day['impressions'] ?? 0);
        }

        return match ($kind) {
            'leads' => (float) ($outcome['leads'] ?? 0),
            'subscriptions' => (float) ($outcome['subscriptions'] ?? 0),
            'installs' => (float) ($outcome['installs'] ?? 0),
            default => max(
                (float) ($outcome['orders'] ?? 0),
                (float) ($outcome['arb_orders'] ?? 0),
                (float) ($outcome['conversions'] ?? 0),
            ),
        };
    }

    /**
     * @param  array<string, mixed>  $outcome
     */
    private function results(array $outcome): float
    {
        $orders = max((float) ($outcome['orders'] ?? 0), (float) ($outcome['arb_orders'] ?? 0));

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

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private function landingPaths(array $snapshot): array
    {
        $urls = data_get($snapshot, 'creative_context.landing_urls', []);

        if (! is_array($urls)) {
            $single = data_get($snapshot, 'creative_context.landing_url');
            $urls = is_string($single) && $single !== '' ? [$single] : [];
        }

        $paths = [];

        foreach ($urls as $url) {
            if (! is_string($url) || $url === '') {
                continue;
            }

            $parts = parse_url($url);
            $host = is_array($parts) ? (string) ($parts['host'] ?? '') : '';
            $path = is_array($parts) ? (string) ($parts['path'] ?? '') : '';
            $key = strtolower($host.$path);

            if ($key !== '') {
                $paths[$key] = $key;
            }
        }

        return array_values($paths);
    }

    /**
     * @param  list<string>  $landingPaths
     */
    private function landingSummary(int $clicks, ?float $ctrPercent, float $outcomeSpend, array $landingPaths): string
    {
        $shared = count($landingPaths) === 1 ? ' All live ads use '.$landingPaths[0].'.' : '';

        if ($ctrPercent !== null && $clicks > 0) {
            return sprintf(
                'Do not spend more. Fix the landing page. CTR is %s%% on %d clicks, so the creative is earning the click, and lagged spend of %s produced no sales, leads, or other results.%s',
                $this->number($ctrPercent),
                $clicks,
                $this->number($outcomeSpend),
                $shared,
            );
        }

        return sprintf(
            'Do not spend more. Fix the landing page. Lagged spend of %s produced no sales, leads, or other results.%s',
            $this->number($outcomeSpend),
            $shared,
        );
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function creativeSpread(array $snapshot): bool
    {
        $rows = data_get($snapshot, 'creative_context.ad_performance', []);

        if (! is_array($rows) || count($rows) < 2) {
            return false;
        }

        $rates = [];

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

            $impressions = (int) ($row['impressions'] ?? 0);
            $clicks = (int) ($row['clicks'] ?? 0);

            if ($impressions < 200) {
                continue;
            }

            $rates[] = $clicks / $impressions;
        }

        if (count($rates) < 2) {
            return false;
        }

        $low = min($rates);
        $high = max($rates);

        return $low > 0 && $high >= $low * 2;
    }

    private function number(float|int|null $value): string
    {
        if ($value === null) {
            return '0';
        }

        $rounded = round((float) $value, 2);

        return rtrim(rtrim(number_format($rounded, 2, '.', ''), '0'), '.');
    }
}
