<?php

namespace App\Services\AI;

use App\Campaigns\PerformanceAdvice;
use App\Library\CampaignDecision\CampaignAdRoster;
use App\Library\CampaignDecision\CampaignDecisionVerdict;
use App\Services\Meta\GraphApi;
use App\Support\PublicHttp;
use Closure;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Files\Image;
use Laravel\Ai\Providers\Tools\WebSearch;
use Throwable;

use function Laravel\Ai\agent;

class CampaignPerformanceAdvisor
{
    private const MAX_ATTEMPTS = 3;

    private const BRIEF_INSTRUCTIONS = <<<'TEXT'
You are a media buyer. You explain one next move for an advertising campaign. You cannot pause, enable, publish, or change the budget yourself. You only return JSON.
Use only the snapshot. Copy numbers from it; never invent numbers, URLs, or ad copy.
status must exactly equal the snapshot verdict (the PHP rules decision). Never change the budget verdict.
status must be one of: insufficient_data, data_issue, learning, watch, maintain, scale_up, decrease_budget, pause.
primary_lever must match marketing_diagnosis.primary_lever when that field is present.
When affiliate.matched is true or windows.outcome_7d is present, cite internal orders, revenue, ROAS, or CPA in the reason. Never treat missing internal rows as zero revenue.
campaign_review is the treated campaign. Write next_actions from its bottleneck and levels (tracking, traffic, funnel, economics, stability). Copy numbers from campaign_review or the snapshot.
marketing_diagnosis ranks three levers only when the bottleneck is the creative, the landing page, or scaling:
- spend_more means the creative and the page are not the constraint.
- improve_creative means people are not clicking, or one ad is clearly weaker. Do not tell the reader to spend more.
- fix_landing_page means clicks are arriving and downstream sales, leads, or other results are not. Do not tell the reader to spend more.
- hold means the bottleneck is tracking, delivery, traffic quality, lag, or missing evidence. Do not rewrite the ad or the page first. Write the next control for that bottleneck.
When creative_context.found is true, name the landing page and one concrete copy or page change from that context. When it is missing or false, say the creative and page text were not available. Do not invent them.
A creative change must cite the control headline, primary text, and CTA, and include a text-only studio image prompt the designer can shoot or composite without guessing. Never request an AI-generated image.
When landing_page headings are present, one next action must quote the current first heading and what the page asks next, then say the exact change on that first screen. You may set the first line to the ad headline when the two differ. Do not tell them to set the page button to the ad button. When that page text is empty, name the URL, what the ad says, and that the first screen must ask for the objective result. Do not say a heading is not saved, do not say not on file, do not say clearer offer, and do not hand the work to a page owner. When the objective is traffic and landing-page views are already present, do not change the heading, the supporting text, or the button.
When creative_context.landing_flow has more than one step, quote each step heading and URL before any page change. When it has one step or is missing, say later screens were not read and do not invent a What to do next page rewrite.
Landing page views are not outbound clicks. If link clicks and landing page views differ, name both counts. Do not write a 100% LPV rate in that case.
Ad-roster ads with live false, or status PAUSED, must not drive fatigue, winners, or What to do next. Name them as paused. Name each creative as Video ad or Image ad plus its Meta ad_id.
When the verdict is learning or insufficient_data: keep the budget unchanged unless improvement_brief.feasibility says the budget cannot learn. Never recommend a budget increase unless the verdict is scale_up or improvement_brief.allowed_moves includes raise_budget_to_learn.
improvement_brief and performance_strategy are PHP facts. Obey allowed_moves, forbidden_moves, must_say, and must_not_say. Write the recommendations yourself from the snapshot numbers — do not paste the must_say lines verbatim. Think like a media buyer: name the objective result (primary_result_label), what the metrics show, and the single next change that fits those facts. Walk tracking, traffic quality, funnel conversion, and unit economics in that order. On sales, leads, and subscriptions, CPA or ROAS is the business target; CPC is traffic quality. Identify one bottleneck before changing multiple variables.
PHP writes next_actions from performance_strategy.proposed_changes. Do not replace those steps with a pause of the whole campaign. Reason explains why those PHP steps are the next move. Copy and image live in the review, not in next_actions. When the verdict is watch, never write “Pause the campaign”. You may pause a named ad only when that ad’s roster label is pause or dead. When broken_step is delivery or delivery_state is not_delivering, do not say delivery is healthy.
next_actions is 2 to 4 original improvement points only when proposed_changes is empty. Each point must quote a metric, a saved interest or job title, a headline, ad name, or the landing URL from the snapshot. Stay inside allowed_moves and never do a forbidden_moves item. Traffic and awareness are scored on delivery and landing-page views, not purchases. Retargeting must not add cold interests. Do not invent GitHub or website placements. When placement_cost.gap is present, shift spend to the cheaper publisher and quote both cost-per-result figures. Do not invent a price, lifetime value, or page section. When delivery_state is paused, say the campaign is paused on the platform (Meta, LinkedIn, or Google) and do not treat it as a live delivery failure. When delivery_state is archived, say this row is not the live campaign. When delivery_state is not_delivering, say how to restart delivery before any creative test. If a cost cap is on file, name that cap and make switching to lowest cost (or raising the cap) step 1; do not list paused ads, rejected ads, or payment issues when the campaign is active. Do not raise budget until it spends. Do not treat the $2 CPC ceiling as an ad network limit on retargeting. When CPC is above the internal target, name the next control (cut the dearest placement with no result, widen the audience, or switch to lowest cost). Never leave bring CPC under $2 as the whole action. When creative_brand_mismatch is true, say which ad headline does not match the campaign brand. When download_install_funnel is true or objective_kind is installs, platform conversions are downloads and internal results are installs. Name the install rate and cost per install. Do not call that gap a pixel, CAPI, form, or CRM tracking mismatch. OUTCOME_LEADS with offsite conversions is a desktop-download buy, not a lead form. When tracking_mismatch is true, show platform_results and internal_results side by side. When broken_step is tracking, the first next_action must be to check Events Manager and a test conversion for primary_result_event. Do not recommend a new ad, a new image, or a landing rewrite until that event fires. Show CTR as a percent (for example 1.45%), never as 0.0145.
When affiliate.matched is true, you may cite affiliate orders and revenue as downstream results. Never call them platform clicks.
When daily_history.days_on_file is greater than 0, the first line of reason must state that lookup: how many of expected_days were on file, the from and to dates, and whether the decision used the last 7 days or the last 15 days. Copy those from daily_history and the plan. Do not say every expected day was on file when days_on_file is lower. platform_row false and a null spend mean that date has results but no delivery row. You may name one other date when that day changes the next move. Do not list the other days.
When daily_history is missing and window_comparison is present with 3d, 7d, and 15d, the first line of reason must compare those three windows using only window_comparison totals and days on file (buckets vs expected_buckets).
When marketing_diagnosis.plan is present, reason may be up to three short lines separated by newlines. Rephrase that plan only. Keep the same window, lever, and numbers. Do not add a fourth line or list the other levers.
When budget_recommendation is present, the action line must include that change: the percent, and the current and recommended daily budget when those amounts are present. Copy them from budget_recommendation. Do not omit the amount or choose a different percent.
Otherwise reason is exactly one sentence, under 240 characters. Name the primary lever and the single change to make. Copy numbers only from the snapshot. Do not explain the other levers.
If the verdict is pause or decrease_budget, do not soften it into a budget increase.
TEXT;

    private const REVIEW_INSTRUCTIONS = <<<'TEXT'
You are a media buyer writing the full recommendation for one advertising campaign. You cannot pause, enable, publish, or change the budget yourself. You only return JSON.
Use only the snapshot. Copy numbers, URLs, and prices from it. Never invent a metric, a price, or a result.
status must be one of: insufficient_data, data_issue, learning, watch, maintain, scale_up, decrease_budget, pause.
primary_lever must match marketing_diagnosis.primary_lever when that field is present.
campaign_review is the treated campaign. Write the analysis from its levels. The bottleneck section must match campaign_review.bottleneck. Explain the actual business condition rather than reciting abstract framework buzzwords. When that bottleneck is tracking, delivery, traffic quality, or lag, do not rewrite the ad or the page first.
performance_strategy.ad_roster is the PHP verdict per ad. Copy each ad's label (winner, pause, too_early, dead, fatigued, watch). Do not relabel an ad. Keep winner and too_early ads. Say pause for pause and dead ads. Replace only fatigued ads, and only when ad_roster.frozen is false. When frozen is true, do not fill replacement copy or landing rewrite fields; the optimization event is missing.
When proposed_changes is present, Recommendations must follow that list in order. Use the ad_id values. Do not pause a winner. Do not skip fix_tracking when it is first. Numbered next steps come from PHP proposed_changes; you only explain why and fill copy or image fields. When the verdict is watch, never write “Pause the campaign”. When broken_step is delivery or delivery_state is not_delivering, do not say delivery is healthy.
When audience_saturated is true, say the pool is saturating and widen it. When small_retargeting_pool is true, say recheck frequency weekly. When cta_mismatch is true, change See details or Learn more to Sign up, Subscribe, or Get offer. Never recommend Learn more on retargeting. Never add GitHub placements.
performance_strategy and improvement_brief are PHP facts. Obey allowed_moves, forbidden_moves, must_say, and must_not_say. Write the memo yourself from the data — do not paste must_say as the whole recommendation. Judge success on primary_result_label (landing page views for traffic, installs for a download-to-install funnel, leads, subscriptions, or purchases). When download_install_funnel is true, platform conversions are downloads and internal results are installs — do not call that a tracking mismatch. Never judge a traffic campaign on conversions. Never say the platform can place ads on GitHub or Stack Overflow. Never add cold interests to retargeting. When placement_cost.gap is present, name both publishers' cost per result and shift spend to the cheaper one. Do not say keep Advantage+ placements unchanged. Prefer automated placements (Advantage+ on Meta, LinkedIn Audience Network on LinkedIn) on low budgets unless a placement clearly wastes spend against the real result. Prefer lowest cost to restart delivery; do not recommend a cost cap when delivery is failing on a small budget. Show CTR as a percent. Include CPM, reach, frequency, and landing page views when performance_strategy.delivery or ad_set_optimization has them.
The user-facing review is the analysis field. Write it as a media-buyer memo, not as a one-line status. When performance_strategy.ad_roster.ads is present, use these sections in this order, each separated by a blank line:
Current performance. Name the optimization event first (primary_result_label). Then list every metric the snapshot actually has, one per line, as Metric and the number. Use spend, impressions, link clicks, CTR as a percent, CPC, CPM, reach, frequency, landing page views, cost per landing page view, conversions, conversion value, orders, revenue, subscriptions, leads, installs, platform vs internal results, quality ranking when on file, prior 7-day CTR when on file, audience size when on file, and per-ad spend when those fields are present. If quality ranking or audience size is missing, write ranking not on file or audience size is not on file. Never invent bottom 35 percent or any ranking that is not in the snapshot. Include the from and to dates and platform learning stage. When daily_history is present, state how many of expected_days were on file. When window_comparison has 3d, 7d, and 15d and daily_history is missing, compare those three windows. When ad_roster.frozen is true, this section is tracking: the event is 0 or not on file after spend.
The bottleneck. Two or three direct, professional sentences identifying the single operational constraint (delivery, tracking, creative, landing page, lag, or unit economics). State the constraint immediately (e.g. delivery constraint, tracking mismatch, weak CTR, landing page drop-off), support it with the exact numbers (e.g. 58 impressions, 0 clicks, $0.00 spend), and state the immediate operational conclusion (e.g. why downstream conversion economics or creative quality cannot be judged until delivery resumes). Keep this section strictly on why the campaign is blocked; do not include web-search commentary, generic product category context, or landing-page critiques here. Never use prompt-meta phrases like "that is category context, not evidence", "the funnel has too little activity to assess, economics are inconclusive, and stability cannot be judged", or "at a level that supports a diagnosis".
Ad-by-ad. One short line per ad using the PHP roster label (winner, pause, too_early, dead, fatigued, watch). Copy the ad_id. Tag Video ad or Image ad from format. If status is paused, say paused and do not judge it as live. Do not relabel.
Fatigue. Use only live ads from performance_strategy.live_ad_ids. Frequency, CTR vs the prior 7 days when on file, duplicate copy, saturation. If frequency or ranking is missing, say not on file. Do not count paused ads in frequency or duplicate-copy fatigue.
Creative. Replacement copy only when ad_roster.frozen is false. When frozen, omit this section or write Creative not yet.
Proposed changes. Follow proposed_changes in order. Use the ad_id values. Do not skip fix_tracking when it is first.
When ad_roster is absent, still write Current performance, the bottleneck, and at least four numbered recommendations.
When ad_roster.frozen is true, numbered items must start with tracking (Events Manager, test conversion) and may only list roster labels — no new ads, no landing rewrite. When a change is allowed, give three to five new angles, and write replacement headline, primary text, and an objective-fit CTA (Subscribe, Sign Up, Get Offer, or Buy for subscribe/lead/sales; Learn More is fine for traffic). Name each ad by ad name and ad_id and its roster label. Do not keep a creative whose headline belongs to another brand. Do not judge a too_early ad. When landing page text is empty, do not rewrite the page — say the live final_url must be read first. Close with what to run next only if delivery is healthy enough to test; otherwise say fix the blocker first. When budget_recommendation is present, the budget item must use that percent and those dollar amounts.
Skip any metric the snapshot does not contain. Keep writing the recommendation from the metrics that are present. Do not say a page was missing, unreadable, unverified, or proposed.
reason is one sentence naming the bottleneck. The analysis field is the review the reader sees.
When ads are in the snapshot, also fill creatives with one object per ad_id. Copy that ad's ad_id, creative_id, ad name when present, and the current headline. Match only by ad_id, never by shared headline. For a change, fill replacement_headline, replacement_primary_text, and replacement_cta. When that ad has an image, image_prompt is a studio-ready still brief, four to eight short sentences, not a one-line caption. Cover: feed still image, portrait crop, one frame; what the attached still currently shows and what to change; subject, setting, camera, lighting, color, and mood in concrete words (not professional or clean); the exact on-image line copied from replacement_headline; type contrast and placement; what to leave out (other-product logos, extra slogans, a fake button, invented prices). The studio makes the still. This app does not generate it. Do not put a digit in image_prompt. Leave image_prompt empty when the action is keep or the ad has no image. When the change needs a second line, such as a link description, fill replacement_secondary_text. Leave replacement_secondary_text empty when the primary text is enough.
When a landing URL is in the snapshot and creative_context.landing_page text or headings are present, fill landing_problem, landing_flow, landing_headline, landing_section, landing_cta, landing_content, and landing_prompt. Quote the scraped final_url and the first heading. When creative_context.landing_flow has later screens, describe that path in landing_flow before recommending a rewrite. When only the first URL is on file, leave landing rewrite fields empty except landing_problem saying later screens must be read. When landing page text is empty, leave the landing rewrite fields empty and say in the analysis that the live page must be read before a rewrite. Do not put a digit in any landing field. Copy prices only into the analysis, and only when that exact number is in the snapshot.
campaign_goals and performance_strategy.primary_result_event decide what working means. Judge creatives and the page against that result.
creative_context.landing_page is the page the ad opens. When that text is present, quote it in landing_problem and base the replacement on it.
creative_context.website holds other pages on that same site, including the homepage. Use a page only when it has text. Leave an empty page out.
Marketing skill. Review the campaign the way a media buyer reviews the creative and the page. The campaign goal decides what working means: a traffic goal is won on the click, and a sales or lead goal is won after the click. When the page text is present, the image, the headline, the call to action, and the landing page must promise the same thing. Name the mismatch when they do not. If the page text is missing, do not quote the live page in the analysis. Still fill the landing fields with the words to publish, and do not put a digit in those fields. For the image and the words, say what is working and what is not, and name the replacement when something should change.
Web search. Use the open web search to see how products of this kind are marketed: the promise, the proof, the audience, and the call to action. Use the site search, or the URLs in the prompt, to read this campaign's own pages. Quote only text that comes back. If a search returns nothing, leave it out. Do not invent a competitor, a price, or a claim. Do not search for campaign metrics. Spend, impressions, clicks, CTR, CPC, conversions, orders, revenue, and budget come only from the snapshot.
One direction. Under Creative or Current performance (never inside The Bottleneck when delivery or tracking is failing), summarize the offer and intended audience from the campaign name, ads, and landing URL. Use web search findings only to identify how that product category is typically positioned, then provide one clear marketing direction for upcoming ad or landing page tests once delivery and tracking are sound. The budget line is the only spend decision, and it must match budget_recommendation when that field is present. Do not say pause or stop spend in one place and keep, hold, or leave the budget in another. Do not say decrease in one place and increase in another. The creative replacements, the landing fields, and any ad set change must all follow that same direction: what to change so this product is marketed the way that category is marketed, and what to leave alone.
creative_context.images lists the still images attached to this prompt, in the same order. kind image is the ad image. kind poster is a still frame from a video; do not review or request the video. For each attached image, say what the picture shows, what is working, and what is not, and whether it matches the goal and the ad copy. Compare an image to the page only when the page text is present. Do not repeat image URLs or file paths. If an image has no visible content, leave that image out.
When landing page text is present, base landing_problem on that text. Always fill landing_headline, landing_section, and landing_cta with the words to publish. None of the landing fields may contain a digit.
When affiliate.matched is true, cite affiliate orders and revenue as downstream results. Never call them platform clicks.
The budget sentence must match budget_recommendation and must not be contradicted by the creative, the landing page, or an ad set line. Phrase every other action as the next change that makes the product easier to understand and the result easier to count.
TEXT;

    // Five ads, a landing-page rewrite, and the performance memo together
    // run past 8,000 characters. A review that long was discarded and the
    // campaign kept the short rules sentence.
    private const MAX_REVIEW_LENGTH = 24000;

    private const MIN_ANALYSIS_LENGTH = 400;

    private const MAX_REASON_LENGTH = 240;

    private const MAX_PLAN_REASON_LENGTH = 480;

    /**
     * Short next-move brief for the campaign performance page.
     *
     * @param  array<string, mixed>  $snapshot
     */
    public function explainBrief(array $snapshot, PerformanceAdvice $php): PerformanceAdvice
    {
        return $this->runAdvisor(
            $snapshot,
            $php,
            self::BRIEF_INSTRUCTIONS,
            [],
            [],
            fn (JsonSchema $schema): array => $this->briefSchema($schema),
            fn (array $payload, array $snapshot, PerformanceAdvice $php): ?string => $this->rejectionReasonBrief($payload, $snapshot, $php),
            fn (array $payload, array $snapshot, PerformanceAdvice $php): ?PerformanceAdvice => $this->acceptedBrief($payload, $snapshot, $php),
        );
    }

    /**
     * Full creative and landing review stored for chat and recommendation cards.
     *
     * @param  array<string, mixed>  $snapshot
     */
    public function explainReview(array $snapshot, PerformanceAdvice $php): PerformanceAdvice
    {
        return $this->runAdvisor(
            $snapshot,
            $php,
            self::REVIEW_INSTRUCTIONS,
            $this->advisorTools($snapshot),
            $this->preparedStillImages($snapshot),
            fn (JsonSchema $schema): array => $this->reviewSchema($schema),
            fn (array $payload, array $snapshot, PerformanceAdvice $php): ?string => $this->rejectionReasonReview($payload, $snapshot, $php),
            fn (array $payload, array $snapshot, PerformanceAdvice $php): ?PerformanceAdvice => $this->acceptedReview($payload, $snapshot, $php),
        );
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  list<WebSearch>  $tools
     * @param  list<array{ad_id: string, creative_id: string, kind: string, file: Image}>  $stillImages
     * @param  Closure(JsonSchema): array<string, mixed>  $schema
     * @param  Closure(array<string, mixed>, array<string, mixed>, PerformanceAdvice): ?string  $rejectionReason
     * @param  Closure(array<string, mixed>, array<string, mixed>, PerformanceAdvice): ?PerformanceAdvice  $accepted
     */
    private function runAdvisor(
        array $snapshot,
        PerformanceAdvice $php,
        string $instructions,
        array $tools,
        array $stillImages,
        Closure $schema,
        Closure $rejectionReason,
        Closure $accepted,
    ): PerformanceAdvice {
        if ($this->shouldSkip($snapshot, $php)) {
            return $php;
        }

        $rejectionFeedback = null;
        $droppedImages = false;

        for ($attempt = 1; $attempt <= self::MAX_ATTEMPTS; $attempt++) {
            try {
                $response = agent(
                    instructions: $instructions,
                    tools: $tools,
                    schema: $schema,
                )->prompt(
                    $this->promptForAttempt($snapshot, $rejectionFeedback, $stillImages),
                    array_map(fn (array $image): Image => $image['file'], $stillImages),
                    provider: TextProviderFailover::providers(),
                    model: (string) config('campaign-performance.text_model', 'gpt-6.1-sol'),
                );

                $payload = $response->toArray();
                $rejection = $rejectionReason($payload, $snapshot, $php);

                if ($rejection === null) {
                    $acceptedAdvice = $accepted($payload, $snapshot, $php);

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

                    $rejectionFeedback = 'Advisor output was discarded.';
                } else {
                    $rejectionFeedback = $rejection;
                }
            } catch (Throwable $exception) {
                Log::warning('Campaign performance advisor failed', [
                    'platform' => $snapshot['platform'] ?? null,
                    'campaign' => $snapshot['campaign'] ?? null,
                    'attempt' => $attempt,
                    'error' => $exception->getMessage(),
                ]);

                if (! $droppedImages && $stillImages !== []) {
                    $droppedImages = true;
                    $stillImages = [];
                }

                if ($attempt >= self::MAX_ATTEMPTS) {
                    return new PerformanceAdvice(
                        status: $php->status,
                        reason: $php->reason,
                        source: 'php',
                        lastError: mb_substr($exception->getMessage(), 0, 2000),
                    );
                }
            }
        }

        return $this->rejected($php, $rejectionFeedback ?? 'Advisor output was discarded.');
    }

    /**
     * @return array<string, mixed>
     */
    private function briefSchema(JsonSchema $schema): array
    {
        return [
            ...$this->sharedSchema($schema),
            'next_actions' => $schema->array()->items($schema->string())->min(2)->max(4),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function reviewSchema(JsonSchema $schema): array
    {
        return [
            ...$this->sharedSchema($schema),
            'analysis' => $schema->string()->description('Full recommendation with Current performance, Bottleneck, Ad-by-ad, Fatigue, Creative (omit when frozen), and Proposed changes. Name the optimization event first. Include page copy only when the page text is present.')->required(),
            'budget' => $schema->string()->description('The rules budget change, with the percent and dollar amounts from the snapshot.'),
            'creatives' => $schema->array()->items(
                $schema->object([
                    'ad_id' => $schema->string()->description('Meta ad_id copied from the snapshot, or empty.'),
                    'creative_id' => $schema->string()->description('creative_id copied from the snapshot, or empty.'),
                    'format' => $schema->string()->description('video or image from the roster, or empty.'),
                    'current_headline' => $schema->string()->description('Current headline copied from the snapshot.'),
                    'action' => $schema->string()->enum(['keep', 'change'])->required(),
                    'why' => $schema->string()->required(),
                    'replacement_headline' => $schema->string(),
                    'replacement_primary_text' => $schema->string(),
                    'replacement_secondary_text' => $schema->string()->description('Second line under the primary text when the ad needs one. Empty when the primary text is enough.'),
                    'replacement_cta' => $schema->string(),
                    'image_prompt' => $schema->string()->description('Studio-ready still brief when the action is change and the ad has an image: format, current still vs change, scene, lighting, exact on-image words, and what to leave out. Empty otherwise. No digits.'),
                ])
            )->description('One entry for every ad in the snapshot.'),
            'landing_problem' => $schema->string()->description('One short sentence. No digits.'),
            'landing_flow' => $schema->string()->description('Page order in one sentence. No digits.'),
            'landing_headline' => $schema->string()->description('Headline to publish. No digits.'),
            'landing_section' => $schema->string()->description('First section to publish. No digits.'),
            'landing_cta' => $schema->string()->description('Button label to publish. No digits.'),
            'landing_content' => $schema->string()->description('Headline and button together. No digits.'),
            'landing_prompt' => $schema->string()->description('Page brief. First sentence names the type from campaign_goals: offsite sign-up, instant lead form, download, purchase, or visit. Then the headline, first section, button, and page order. No digits.'),
            'tests' => $schema->string()->description('What to run next and which metrics to judge.'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function sharedSchema(JsonSchema $schema): array
    {
        return [
            'status' => $schema->string()->enum(array_map(
                fn (CampaignDecisionVerdict $verdict): string => $verdict->value,
                CampaignDecisionVerdict::cases(),
            ))->required(),
            'primary_lever' => $schema->string()->enum([
                'spend_more',
                'improve_creative',
                'fix_landing_page',
                'hold',
            ])->required(),
            'reason' => $schema->string()->description('One sentence naming the bottleneck.')->required(),
            'confidence' => $schema->string()->required(),
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @param  list<array{ad_id: string, creative_id: string, kind: string, file: Image}>  $stillImages
     */
    private function promptForAttempt(array $snapshot, ?string $rejectionFeedback, array $stillImages = []): string
    {
        $treated = is_array($snapshot['campaign_review'] ?? null)
            ? $snapshot['campaign_review']
            : (is_array(data_get($snapshot, 'improvement_brief.campaign_review'))
                ? data_get($snapshot, 'improvement_brief.campaign_review')
                : null);
        $prompt = '';

        if (is_array($treated) && $treated !== []) {
            $prompt .= "Treated campaign (PHP facts). Write the suggestion from this bottleneck and these levels. Copy numbers from here or the snapshot; never invent them.\n"
                .json_encode($treated, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
                ."\n\n";
        }

        $prompt .= "Snapshot:\n".json_encode($snapshot, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $lines = [];

        foreach ($stillImages as $index => $image) {
            $line = ((int) $index + 1).'. ad '.$image['ad_id'].' ('.$image['kind'].')';

            if ($image['creative_id'] !== '') {
                $line .= ' creative '.$image['creative_id'];
            }

            $lines[] = $line;
        }

        if ($lines !== []) {
            $prompt .= "\n\nAttached still images, in order:\n".implode("\n", $lines);
        }

        $pages = $this->pagesToRead($snapshot);

        if ($pages !== []) {
            $prompt .= "\n\nYou may read these URLs. Quote a page only when its words come back. If a page returns nothing, leave it out of the review:\n".implode("\n", $pages);
        }

        if ($rejectionFeedback !== null && $rejectionFeedback !== '') {
            $prompt .= "\n\nYour previous answer was rejected. Fix it.\n".$rejectionFeedback;
        }

        return $prompt;
    }

    /**
     * Still images for the vision pass. A stored CDN link that no longer
     * downloads is replaced from Graph when the creative id is known.
     * Video files are not attached.
     *
     * @param  array<string, mixed>  $snapshot
     * @return list<array{ad_id: string, creative_id: string, kind: string, file: Image}>
     */
    private function preparedStillImages(array $snapshot): array
    {
        $images = data_get($snapshot, 'creative_context.images', []);

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

        $accountId = trim((string) ($snapshot['account_id'] ?? ''));
        $still = [];
        $limit = max(0, (int) config('campaign-performance.creative_image_limit', 6));

        foreach ($images as $image) {
            if (count($still) >= $limit) {
                break;
            }

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

            $file = $this->stillImageFile($image, $accountId !== '' ? $accountId : null);

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

            $still[] = [
                'ad_id' => trim((string) ($image['ad_id'] ?? '')),
                'creative_id' => trim((string) ($image['creative_id'] ?? '')),
                'kind' => trim((string) ($image['kind'] ?? 'image')) ?: 'image',
                'file' => $file,
            ];
        }

        return $still;
    }

    /**
     * @param  array<string, mixed>  $image
     */
    private function stillImageFile(array $image, ?string $accountId = null): ?Image
    {
        $url = trim((string) ($image['url'] ?? ''));

        if ($url !== '') {
            return $this->downloadedImage($url, trim((string) ($image['creative_id'] ?? '')), $accountId);
        }

        $path = trim((string) ($image['path'] ?? ''));
        $disk = trim((string) ($image['disk'] ?? ''));

        if ($path === '' || $disk === '' || $this->isVideoPath($path)) {
            return null;
        }

        try {
            if (! Storage::disk($disk)->exists($path)) {
                return null;
            }
        } catch (Throwable) {
            return null;
        }

        return Image::fromStorage($path, $disk);
    }

    private function downloadedImage(string $url, string $creativeId = '', ?string $accountId = null): ?Image
    {
        if ($this->isVideoPath((string) parse_url($url, PHP_URL_PATH)) || ! PublicHttp::isPublicUrl($url)) {
            return null;
        }

        $image = $this->imageFromUrl($url);

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

        $fresh = $this->refreshedCreativeUrl($creativeId, $accountId);

        if ($fresh !== null && $fresh !== $url) {
            $image = $this->imageFromUrl($fresh);

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

            return Image::fromUrl($fresh);
        }

        return Image::fromUrl($url);
    }

    /**
     * The signed address stored with the creative, replaced when it no longer
     * returns an image. A missing token or a refused account leaves the
     * original link for the model to fetch.
     */
    private function refreshedCreativeUrl(string $creativeId, ?string $accountId): ?string
    {
        if ($creativeId === '') {
            return null;
        }

        try {
            return app(GraphApi::class)->creativeImageUrl($creativeId, $accountId);
        } catch (Throwable) {
            return null;
        }
    }

    private function imageFromUrl(string $url): ?Image
    {
        try {
            $response = PublicHttp::send(
                Http::connectTimeout(3)->timeout(8),
                $url,
            );
        } catch (Throwable) {
            return null;
        }

        $mime = strtolower(trim(strtok((string) $response->header('Content-Type'), ';') ?: ''));

        if ($response->successful() && str_starts_with($mime, 'image/') && strlen($response->body()) <= 2_000_000) {
            return Image::fromBase64(base64_encode($response->body()), $mime);
        }

        return null;
    }

    private function isVideoPath(string $path): bool
    {
        $path = strtolower($path);

        foreach (['.mp4', '.mov', '.webm', '.m3u8', '.m4v'] as $extension) {
            if (str_ends_with($path, $extension)) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function shouldSkip(array $snapshot, PerformanceAdvice $php): bool
    {
        if (! config('campaign-performance.llm_enabled', true)) {
            return true;
        }

        $platformStatus = strtolower((string) ($snapshot['platform_status'] ?? ''));
        $spend = (float) data_get($snapshot, 'last_7_days.spend', 0);

        return config('campaign-performance.skip_llm_when_paused_zero_spend', true)
            && in_array($platformStatus, ['paused', 'campaign_paused'], true)
            && $spend < 0.01;
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function rejectionReasonBrief(array $payload, array $snapshot, PerformanceAdvice $php): ?string
    {
        if ($this->acceptedBrief($payload, $snapshot, $php) !== null) {
            return null;
        }

        $reason = trim((string) ($payload['reason'] ?? ''));
        $usesPlan = is_array(data_get($snapshot, 'marketing_diagnosis.plan'))
            && data_get($snapshot, 'marketing_diagnosis.plan') !== [];

        if ($reason === '') {
            return 'Reason was empty.';
        }

        if (! $this->reasonShapeIsValid($reason, $usesPlan)) {
            return 'Reason must be one sentence, or up to three short lines when a plan is present.';
        }

        $maxLength = $usesPlan ? self::MAX_PLAN_REASON_LENGTH : self::MAX_REASON_LENGTH;

        if (mb_strlen($reason) > $maxLength) {
            return 'Reason was too long.';
        }

        return $this->sharedRejection($payload, $snapshot, $reason);
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function rejectionReasonReview(array $payload, array $snapshot, PerformanceAdvice $php): ?string
    {
        if ($this->acceptedReview($payload, $snapshot, $php) !== null) {
            return null;
        }

        $combined = $this->combinedText($payload);

        if (trim((string) ($payload['reason'] ?? '')) === '') {
            return 'Reason was empty.';
        }

        if (mb_strlen($combined) > self::MAX_REVIEW_LENGTH) {
            return 'Review was too long.';
        }

        $shared = $this->sharedRejection($payload, $snapshot, $combined);

        if ($shared !== 'Advisor output was discarded.') {
            return $shared;
        }

        if ($this->reviewableAds($snapshot) !== [] && $this->creativeSuggestions($payload, $snapshot) === null) {
            return 'Include one creatives entry for every ad. Copy its ad_id, creative_id, and current headline. A change needs replacement_headline and replacement_primary_text. A change for an ad with an image also needs a studio-ready image_prompt (format, scene, lighting, exact on-image words, what to leave out), with no digits. Add replacement_secondary_text only when a second line is needed. Do not add numbers that are not in the snapshot.';
        }

        $landing = $this->requiresLandingSuggestion($snapshot) ? $this->landingSuggestion($payload, $snapshot) : null;

        if ($this->requiresLandingSuggestion($snapshot) && $landing === null) {
            return 'Fill landing_problem, landing_flow, landing_headline, landing_section, landing_cta, and landing_content. The headline, first section, and button are the words to put on the page. Do not add numbers that are not in the snapshot.';
        }

        if (is_array($landing) && $this->requiresLandingPrompt($snapshot) && trim((string) ($landing['prompt'] ?? '')) === '') {
            return 'landing_prompt must name the page type from campaign_goals, then the headline, first section, button, and page order. Use offsite sign-up for a leads objective with an offsite conversion, instant lead form for a lead-form goal, download for app promotion or installs, purchase for sales, or visit for traffic. Do not add a digit.';
        }

        if ($this->analysisIsRequired($snapshot) && $this->analysisText($payload, $snapshot) === null) {
            return $this->hasRosterAds($snapshot)
                ? 'analysis must use these sections in order: Current performance (name the event first), Bottleneck, Ad-by-ad (cite roster labels), Fatigue, Creative (omit or say not yet when frozen), Proposed changes (the PHP list). Do not rewrite ads while frozen. Use only numbers from the snapshot.'
                : 'analysis must be the full recommendation: current metrics, what is working, the bottleneck, and at least four numbered changes. Leave out any page or result the snapshot does not contain. Use only numbers from the snapshot.';
        }

        return 'Advisor output was discarded.';
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function sharedRejection(array $payload, array $snapshot, string $text): string
    {
        $expectedVerdict = strtolower(trim((string) ($snapshot['verdict'] ?? '')));
        $status = strtolower(trim((string) ($payload['status'] ?? '')));

        if ($expectedVerdict !== '' && $status !== '' && $status !== $expectedVerdict) {
            return 'status must equal the snapshot verdict ('.$expectedVerdict.').';
        }

        $expectedLever = data_get($snapshot, 'marketing_diagnosis.primary_lever');
        $lever = strtolower(trim((string) ($payload['primary_lever'] ?? '')));

        if (is_string($expectedLever) && $expectedLever !== '' && $lever !== '' && $lever !== $expectedLever) {
            return 'primary_lever must match marketing_diagnosis.primary_lever ('.$expectedLever.').';
        }

        if ($this->inventsNumbers($text, $snapshot)) {
            return 'Review included a number that is not in the snapshot.';
        }

        if ($this->requiresLookup($snapshot) && ! $this->mentionsLookup($text, $snapshot)) {
            return 'Reason must state how many of the last 30 days were on file, the from and to dates, and whether the decision used 7 days or 15 days.';
        }

        if (! $this->requiresLookup($snapshot) && $this->requiresWindowComparison($snapshot) && ! $this->mentionsWindowComparison($text)) {
            return 'Reason must compare the 3-day, 7-day, and 15-day windows using window_comparison.';
        }

        if ($this->contradictsPhpFacts($snapshot, $text)) {
            return 'Review contradicted the PHP verdict or delivery facts.';
        }

        return 'Advisor output was discarded.';
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function acceptedBrief(array $payload, array $snapshot, PerformanceAdvice $php): ?PerformanceAdvice
    {
        $reason = trim((string) ($payload['reason'] ?? ''));
        $confidence = strtolower(trim((string) ($payload['confidence'] ?? '')));
        $usesPlan = is_array(data_get($snapshot, 'marketing_diagnosis.plan'))
            && data_get($snapshot, 'marketing_diagnosis.plan') !== [];

        if ($reason === '' || ! $this->reasonShapeIsValid($reason, $usesPlan)) {
            return null;
        }

        $maxLength = $usesPlan ? self::MAX_PLAN_REASON_LENGTH : self::MAX_REASON_LENGTH;

        if (mb_strlen($reason) > $maxLength) {
            return null;
        }

        $actionsText = implode(' ', $this->nextActionsFromPayload($payload));
        $checked = trim($reason.' '.$actionsText);

        if ($this->sharedAcceptanceFails($payload, $snapshot, $checked)) {
            return null;
        }

        if (! in_array($confidence, ['low', 'medium', 'high'], true)) {
            $confidence = 'medium';
        }

        $expectedVerdict = strtolower(trim((string) ($snapshot['verdict'] ?? '')));
        $status = strtolower(trim((string) ($payload['status'] ?? '')));
        $lockedStatus = CampaignDecisionVerdict::tryFrom($expectedVerdict)?->value
            ?? CampaignDecisionVerdict::tryFrom($status)?->value;

        return new PerformanceAdvice(
            status: $php->status,
            reason: mb_substr($reason, 0, $maxLength),
            source: 'llm',
            confidence: $confidence,
            model: (string) config('campaign-performance.text_model', 'gpt-6.1-sol'),
            aiStatus: $lockedStatus,
            nextActions: $this->nextActionsFromPayload($payload),
        );
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function acceptedReview(array $payload, array $snapshot, PerformanceAdvice $php): ?PerformanceAdvice
    {
        $summary = trim((string) ($payload['reason'] ?? ''));
        $confidence = strtolower(trim((string) ($payload['confidence'] ?? '')));
        $combined = $this->combinedText($payload);

        if ($summary === '' || mb_strlen($combined) > self::MAX_REVIEW_LENGTH) {
            return null;
        }

        if ($this->sharedAcceptanceFails($payload, $snapshot, $combined)) {
            return null;
        }

        $creatives = $this->creativeSuggestions($payload, $snapshot);

        if ($this->reviewableAds($snapshot) !== [] && $creatives === null) {
            return null;
        }

        $landingSuggestion = null;

        if ($this->requiresLandingSuggestion($snapshot)) {
            $landingSuggestion = $this->landingSuggestion($payload, $snapshot);

            if ($landingSuggestion === null) {
                return null;
            }

            if ($this->requiresLandingPrompt($snapshot) && trim((string) ($landingSuggestion['prompt'] ?? '')) === '') {
                return null;
            }
        }

        $analysis = $this->analysisText($payload, $snapshot);

        if ($this->analysisIsRequired($snapshot) && $analysis === null) {
            return null;
        }

        if (! in_array($confidence, ['low', 'medium', 'high'], true)) {
            $confidence = 'medium';
        }

        $budget = trim((string) ($payload['budget'] ?? ''));
        $tests = trim((string) ($payload['tests'] ?? ''));
        $review = $this->reviewPayload($summary, $analysis, $budget, $creatives ?? [], $landingSuggestion, $tests);
        $reason = $analysis ?? $this->compose($summary, $budget, $creatives ?? [], $landingSuggestion, $tests);

        return new PerformanceAdvice(
            status: $php->status,
            reason: mb_substr($reason, 0, self::MAX_REVIEW_LENGTH),
            source: 'llm',
            confidence: $confidence,
            model: (string) config('campaign-performance.text_model', 'gpt-6.1-sol'),
            aiStatus: CampaignDecisionVerdict::tryFrom(strtolower(trim((string) ($payload['status'] ?? ''))))?->value,
            landingSuggestion: $landingSuggestion,
            review: $review,
        );
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function sharedAcceptanceFails(array $payload, array $snapshot, string $text): bool
    {
        $expectedVerdict = strtolower(trim((string) ($snapshot['verdict'] ?? '')));
        $status = strtolower(trim((string) ($payload['status'] ?? '')));

        if ($expectedVerdict !== '' && $status !== '' && $status !== $expectedVerdict) {
            return true;
        }

        $expectedLever = data_get($snapshot, 'marketing_diagnosis.primary_lever');
        $lever = strtolower(trim((string) ($payload['primary_lever'] ?? '')));

        if (is_string($expectedLever) && $expectedLever !== '' && $lever !== '' && $lever !== $expectedLever) {
            return true;
        }

        if ($this->inventsNumbers($text, $snapshot)) {
            return true;
        }

        if ($this->requiresLookup($snapshot) && ! $this->mentionsLookup($text, $snapshot)) {
            return true;
        }

        if ($this->contradictsPhpFacts($snapshot, $text)) {
            return true;
        }

        return ! $this->requiresLookup($snapshot)
            && $this->requiresWindowComparison($snapshot)
            && ! $this->mentionsWindowComparison($text);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function contradictsPhpFacts(array $snapshot, string $text): bool
    {
        $verdict = strtolower(trim((string) ($snapshot['verdict'] ?? '')));
        $step = (string) data_get($snapshot, 'performance_strategy.broken_step');
        $state = (string) data_get($snapshot, 'performance_strategy.delivery_state');

        if ($verdict === CampaignDecisionVerdict::Watch->value && preg_match('/pause the campaign/i', $text) === 1) {
            return true;
        }

        return ($step === 'delivery' || $state === 'not_delivering')
            && preg_match('/\bhealthy\b/i', $text) === 1;
    }

    private function rejected(PerformanceAdvice $php, string $error): PerformanceAdvice
    {
        return new PerformanceAdvice(
            status: $php->status,
            reason: $php->reason,
            source: 'php',
            lastError: $error,
        );
    }

    /**
     * Web search for the recommendation. The marketing chat tools are not included:
     * those can change a live campaign, and this call only writes advice.
     *
     * When the campaign has a site, search is limited to that host so the model
     * reads the landing page instead of a third-party writeup.
     *
     * @param  array<string, mixed>  $snapshot
     * @return list<WebSearch>
     */
    private function advisorTools(array $snapshot): array
    {
        if (! config('campaign-performance.web_search', true)) {
            return [];
        }

        $tools = [(new WebSearch)->max(3)];
        $host = $this->campaignSiteHost($snapshot);

        if ($host !== null) {
            $tools[] = (new WebSearch)->max(3)->allow([$host]);
        }

        return $tools;
    }

    /**
     * Pages the model should open when the scrape came back empty.
     *
     * @param  array<string, mixed>  $snapshot
     * @return list<string>
     */
    private function pagesToRead(array $snapshot): array
    {
        $text = data_get($snapshot, 'creative_context.landing_page.text');

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

        $urls = [];

        foreach ([
            data_get($snapshot, 'creative_context.landing_url'),
            ...array_map(
                fn (mixed $page): mixed => is_array($page) ? ($page['url'] ?? null) : null,
                is_array(data_get($snapshot, 'creative_context.website.pages'))
                    ? data_get($snapshot, 'creative_context.website.pages')
                    : [],
            ),
        ] as $url) {
            $url = trim((string) $url);

            if ($url === '' || ! str_starts_with($url, 'http') || isset($urls[$url])) {
                continue;
            }

            $urls[$url] = $url;

            if (count($urls) >= 4) {
                break;
            }
        }

        return array_values($urls);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function campaignSiteHost(array $snapshot): ?string
    {
        $host = strtolower(trim((string) data_get($snapshot, 'creative_context.website.host')));

        if ($host === '') {
            $host = strtolower((string) parse_url((string) data_get($snapshot, 'creative_context.landing_url'), PHP_URL_HOST));
        }

        $host = preg_replace('/^www\./', '', $host) ?? $host;

        if ($host === '' || ! str_contains($host, '.')) {
            return null;
        }

        return $host;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function requiresLookup(array $snapshot): bool
    {
        $history = data_get($snapshot, 'daily_history');

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

        return (int) ($history['days_on_file'] ?? 0) > 0
            && (int) ($history['expected_days'] ?? 0) > 0
            && is_string($history['from'] ?? null) && $history['from'] !== ''
            && is_string($history['to'] ?? null) && $history['to'] !== ''
            && is_array(data_get($snapshot, 'marketing_diagnosis.plan'))
            && data_get($snapshot, 'marketing_diagnosis.plan') !== [];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function mentionsLookup(string $reason, array $snapshot): bool
    {
        $history = data_get($snapshot, 'daily_history');

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

        $onFile = (string) (int) ($history['days_on_file'] ?? 0);
        $expected = (string) (int) ($history['expected_days'] ?? 0);
        $from = (string) ($history['from'] ?? '');
        $to = (string) ($history['to'] ?? '');
        $basis = (string) data_get($snapshot, 'marketing_diagnosis.lookup_basis', '7d');
        $lower = strtolower($reason);
        $hasFifteen = str_contains($lower, '15-day')
            || str_contains($lower, '15 day')
            || str_contains($lower, '15 days');
        $hasSeven = str_contains($lower, '7-day')
            || str_contains($lower, '7 day')
            || str_contains($lower, '7 days');
        $hasWindow = $basis === '15d' ? $hasFifteen : $hasSeven;

        return str_contains($reason, $onFile)
            && str_contains($reason, $expected)
            && str_contains($reason, $from)
            && str_contains($reason, $to)
            && $hasWindow;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function requiresWindowComparison(array $snapshot): bool
    {
        $comparison = data_get($snapshot, 'window_comparison');

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

        foreach (['3d', '7d', '15d'] as $key) {
            if (! isset($comparison[$key]) || ! is_array($comparison[$key])) {
                return false;
            }
        }

        return is_array(data_get($snapshot, 'marketing_diagnosis.plan'))
            && data_get($snapshot, 'marketing_diagnosis.plan') !== [];
    }

    private function mentionsWindowComparison(string $reason): bool
    {
        $lower = strtolower($reason);

        $hasThree = str_contains($lower, '3-day')
            || str_contains($lower, '3 day')
            || str_contains($lower, '3d');
        $hasSeven = str_contains($lower, '7-day')
            || str_contains($lower, '7 day')
            || str_contains($lower, '7d');
        $hasFifteen = str_contains($lower, '15-day')
            || str_contains($lower, '15 day')
            || str_contains($lower, '15d');

        return $hasThree && $hasSeven && $hasFifteen;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function requiresLandingSuggestion(array $snapshot): bool
    {
        if (CampaignAdRoster::creativeAdviceFrozen($snapshot)) {
            return false;
        }

        $url = trim((string) (data_get($snapshot, 'creative_context.landing_url') ?? ''));
        $text = data_get($snapshot, 'creative_context.landing_page.text');

        return $url !== '' || (is_string($text) && trim($text) !== '');
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     * @return array{problem: string, flow: string, content: string, headline: string, section: string, cta: string, prompt: string}|null
     */
    private function landingSuggestion(array $payload, array $snapshot): ?array
    {
        $prompt = trim((string) ($payload['landing_prompt'] ?? ''));
        $fields = [
            'problem' => trim((string) ($payload['landing_problem'] ?? '')),
            'flow' => trim((string) ($payload['landing_flow'] ?? '')),
            'headline' => trim((string) ($payload['landing_headline'] ?? '')),
            'section' => trim((string) ($payload['landing_section'] ?? '')),
            'cta' => trim((string) ($payload['landing_cta'] ?? '')),
            'content' => trim((string) ($payload['landing_content'] ?? '')),
        ];

        foreach ($fields as $value) {
            if ($value === '') {
                return null;
            }
        }

        if ($this->inventsNumbers(implode(' ', $fields), $snapshot)) {
            return null;
        }

        return [
            'problem' => mb_substr($fields['problem'], 0, 800),
            'flow' => mb_substr($fields['flow'], 0, 800),
            'headline' => mb_substr($fields['headline'], 0, 300),
            'section' => mb_substr($fields['section'], 0, 800),
            'cta' => mb_substr($fields['cta'], 0, 200),
            'content' => mb_substr($fields['content'], 0, 800),
            'prompt' => mb_substr($prompt, 0, 2000),
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function requiresLandingPrompt(array $snapshot): bool
    {
        if (! $this->requiresLandingSuggestion($snapshot)) {
            return false;
        }

        return trim((string) data_get($snapshot, 'campaign_goals.objective', '')) !== '';
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    private function combinedText(array $payload): string
    {
        $parts = [trim((string) ($payload['reason'] ?? '')), trim((string) ($payload['analysis'] ?? '')), trim((string) ($payload['budget'] ?? '')), trim((string) ($payload['tests'] ?? ''))];

        foreach (['landing_problem', 'landing_flow', 'landing_headline', 'landing_section', 'landing_cta', 'landing_content', 'landing_prompt'] as $key) {
            $parts[] = trim((string) ($payload[$key] ?? ''));
        }

        foreach (is_array($payload['creatives'] ?? null) ? $payload['creatives'] : [] as $creative) {
            if (! is_array($creative)) {
                continue;
            }

            foreach (['why', 'replacement_headline', 'replacement_primary_text', 'replacement_secondary_text', 'replacement_cta', 'image_prompt', 'current_headline'] as $key) {
                $parts[] = trim((string) ($creative[$key] ?? ''));
            }
        }

        return trim(implode("\n", array_filter($parts, fn (string $part): bool => $part !== '')));
    }

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

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

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

        $rows = [];

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

            $headline = trim((string) ($ad['headline'] ?? ''));
            $primary = trim((string) ($ad['primary_text'] ?? ''));
            $id = trim((string) ($ad['ad_id'] ?? ''));

            if ($headline === '' && $primary === '' && $id === '') {
                continue;
            }

            $rows[] = $ad;
        }

        return $rows;
    }

    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     * @return list<array<string, string>>|null
     */
    private function creativeSuggestions(array $payload, array $snapshot): ?array
    {
        $expected = $this->reviewableAds($snapshot);

        if ($expected === []) {
            return [];
        }

        $given = $payload['creatives'] ?? null;

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

        $normalized = [];

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

            $action = strtolower(trim((string) ($row['action'] ?? '')));
            $why = trim((string) ($row['why'] ?? ''));
            $headline = trim((string) ($row['replacement_headline'] ?? ''));
            $primary = trim((string) ($row['replacement_primary_text'] ?? ''));
            $secondary = trim((string) ($row['replacement_secondary_text'] ?? ''));
            $imagePrompt = trim((string) ($row['image_prompt'] ?? ''));
            $matched = $this->matchedAd($row, $expected);

            if ($matched === null || $why === '' || ! in_array($action, ['keep', 'change'], true)) {
                continue;
            }

            $adSpend = (float) (
                data_get($matched, 'last_7_days.spend')
                ?? data_get($matched, 'spend_7d')
                ?? data_get($matched, 'spend')
                ?? 0
            );
            $minAdSpend = (float) data_get($snapshot, 'performance_strategy.targets.min_ad_spend_to_judge', config('campaign-decisions.defaults.min_ad_spend_to_judge', 10));

            if ($action === 'change' && $adSpend > 0 && $adSpend < $minAdSpend) {
                $action = 'keep';
                $why = 'Spend is only $'.number_format($adSpend, 2).' in the recent window — too little to judge this ad. '.$why;
            }

            $roster = CampaignAdRoster::rowForAd($snapshot, trim((string) ($matched['ad_id'] ?? $row['ad_id'] ?? '')));
            $rosterAction = is_array($roster) ? (string) ($roster['llm_action'] ?? 'keep') : null;
            $rosterLabel = is_array($roster) ? (string) ($roster['label'] ?? '') : '';
            $paused = is_array($roster) && ! CampaignAdRoster::isLive($roster);

            if ($paused) {
                $action = 'keep';
                $why = 'Paused on Meta. Listed for reference only. '.$why;
            }

            if (CampaignAdRoster::creativeAdviceFrozen($snapshot) || ($rosterAction !== null && $rosterAction !== 'change') || $paused) {
                $action = 'keep';
                $headline = '';
                $primary = '';
                $secondary = '';
                $imagePrompt = '';
            }

            if ($rosterLabel !== '' && ! str_contains(strtolower($why), str_replace('_', ' ', $rosterLabel)) && ! str_contains(strtolower($why), $rosterLabel)) {
                $why = 'Roster '.$rosterLabel.': '.$why;
            }

            if ($action === 'change' && ($headline === '' || $primary === '')) {
                continue;
            }

            if ($action === 'change' && $this->adHasImage($matched) && $imagePrompt === '') {
                continue;
            }

            if ($action !== 'change') {
                $secondary = '';
                $imagePrompt = '';
            }

            $normalized[] = [
                'ad_id' => trim((string) ($row['ad_id'] ?? '')),
                'creative_id' => $this->creativeIdFor($matched),
                'format' => is_array($roster) ? (string) ($roster['format'] ?? '') : '',
                'current_headline' => trim((string) ($row['current_headline'] ?? '')),
                'action' => $action,
                'why' => mb_substr($why, 0, 500),
                'replacement_headline' => mb_substr($headline, 0, 300),
                'replacement_primary_text' => mb_substr($primary, 0, 800),
                'replacement_secondary_text' => mb_substr($secondary, 0, 500),
                'replacement_cta' => mb_substr(trim((string) ($row['replacement_cta'] ?? '')), 0, 80),
                'image_prompt' => mb_substr($imagePrompt, 0, 2000),
            ];
        }

        foreach ($expected as $ad) {
            $id = trim((string) ($ad['ad_id'] ?? ''));
            $headline = trim((string) ($ad['headline'] ?? ''));
            $covered = false;

            foreach ($normalized as $row) {
                if ($id !== '' && $row['ad_id'] === $id) {
                    $covered = true;
                }

                if ($headline !== '' && $row['current_headline'] === $headline) {
                    $covered = true;
                }
            }

            if (! $covered) {
                return null;
            }
        }

        return $normalized;
    }

    /**
     * @param  array<string, mixed>  $row
     * @param  list<array<string, mixed>>  $ads
     * @return array<string, mixed>|null
     */
    private function matchedAd(array $row, array $ads): ?array
    {
        $adId = trim((string) ($row['ad_id'] ?? ''));

        if ($adId !== '') {
            foreach ($ads as $ad) {
                if ($adId === trim((string) ($ad['ad_id'] ?? ''))) {
                    return $ad;
                }
            }

            // Wrong ad_id must not fall back to a shared headline — that duplicated creative ids.
            return null;
        }

        $headline = trim((string) ($row['current_headline'] ?? ''));
        $matches = [];

        foreach ($ads as $ad) {
            if ($headline !== '' && $headline === trim((string) ($ad['headline'] ?? ''))) {
                $matches[] = $ad;
            }
        }

        if (count($matches) === 1) {
            return $matches[0];
        }

        return count($ads) === 1 ? $ads[0] : null;
    }

    /**
     * @param  array<string, mixed>|null  $ad
     */
    private function adHasImage(?array $ad): bool
    {
        if ($ad === null) {
            return false;
        }

        $images = $ad['images'] ?? [];

        return is_array($images) && $images !== [];
    }

    /**
     * @param  array<string, mixed>|null  $ad
     */
    private function creativeIdFor(?array $ad): string
    {
        if ($ad === null) {
            return '';
        }

        $id = trim((string) ($ad['creative_id'] ?? ''));

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

        foreach (is_array($ad['images'] ?? null) ? $ad['images'] : [] as $image) {
            if (! is_array($image)) {
                continue;
            }

            $id = trim((string) ($image['creative_id'] ?? ''));

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

        return '';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function requiresAnalysis(array $snapshot): bool
    {
        return $this->reviewableAds($snapshot) !== [] || $this->requiresLandingSuggestion($snapshot);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function analysisIsRequired(array $snapshot): bool
    {
        return $this->requiresAnalysis($snapshot) || $this->hasRosterAds($snapshot);
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    /**
     * @param  array<string, mixed>  $payload
     * @param  array<string, mixed>  $snapshot
     */
    private function analysisText(array $payload, array $snapshot = []): ?string
    {
        $analysis = trim((string) ($payload['analysis'] ?? ''));

        if (mb_strlen($analysis) < self::MIN_ANALYSIS_LENGTH || ! str_contains($analysis, '1.')) {
            return null;
        }

        if ($this->missingRequiredAnalysisSections($analysis, $snapshot)) {
            return null;
        }

        return $analysis;
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function hasRosterAds(array $snapshot): bool
    {
        $ads = data_get($snapshot, 'performance_strategy.ad_roster.ads');

        return is_array($ads) && $ads !== [];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function missingRequiredAnalysisSections(string $analysis, array $snapshot): bool
    {
        if (! $this->hasRosterAds($snapshot)) {
            return false;
        }

        $frozen = CampaignAdRoster::creativeAdviceFrozen($snapshot);
        $found = $this->analysisSectionHeadings($analysis);
        $required = ['current performance', 'bottleneck', 'ad-by-ad', 'fatigue', 'proposed changes'];

        foreach ($required as $heading) {
            if (! in_array($heading, $found, true)) {
                return true;
            }
        }

        if ($frozen) {
            $opening = mb_strtolower(mb_substr($analysis, 0, 800));

            if (! str_contains($opening, 'track')) {
                return true;
            }

            if (in_array('creative', $found, true) && ! preg_match('/creative[^\n]*not yet/i', $analysis)) {
                return true;
            }
        } elseif (! in_array('creative', $found, true)) {
            return true;
        }

        return false;
    }

    /**
     * @return list<string>
     */
    private function analysisSectionHeadings(string $analysis): array
    {
        $found = [];

        foreach (preg_split('/\R/', $analysis) ?: [] as $line) {
            $lower = strtolower(trim($line));

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

            foreach ([
                'current performance' => 'current performance',
                'the bottleneck' => 'bottleneck',
                'bottleneck' => 'bottleneck',
                'ad-by-ad' => 'ad-by-ad',
                'ad by ad' => 'ad-by-ad',
                'fatigue' => 'fatigue',
                'creative' => 'creative',
                'proposed changes' => 'proposed changes',
            ] as $prefix => $key) {
                if ($lower === $prefix || str_starts_with($lower, $prefix.'.') || str_starts_with($lower, $prefix.' ')) {
                    $found[] = $key;
                }
            }
        }

        return array_values(array_unique($found));
    }

    /**
     * @param  list<array<string, string>>  $creatives
     * @param  array{problem: string, flow: string, content: string, headline: string, section: string, cta: string}|null  $landing
     * @return array<string, mixed>|null
     */
    private function reviewPayload(string $summary, ?string $analysis, string $budget, array $creatives, ?array $landing, string $tests): ?array
    {
        if ($analysis === null && $budget === '' && $creatives === [] && $landing === null && $tests === '') {
            return null;
        }

        return array_filter([
            'summary' => $summary,
            'analysis' => $analysis,
            'budget' => $budget !== '' ? $budget : null,
            'creatives' => $creatives !== [] ? $creatives : null,
            'landing' => $landing,
            'tests' => $tests !== '' ? $tests : null,
        ], fn (mixed $value): bool => $value !== null);
    }

    /**
     * @param  list<array<string, string>>  $creatives
     * @param  array{problem: string, flow: string, content: string, headline?: string, section?: string, cta?: string}|null  $landing
     */
    private function compose(string $summary, string $budget, array $creatives, ?array $landing, string $tests): string
    {
        $parts = [$summary];

        if ($budget !== '') {
            $parts[] = 'Budget: '.$budget;
        }

        foreach ($creatives as $creative) {
            $name = $creative['current_headline'] !== '' ? $creative['current_headline'] : ($creative['ad_id'] !== '' ? $creative['ad_id'] : 'Ad');
            $line = 'Creative '.$name.': '.$creative['action'].'. '.$creative['why'];

            if ($creative['replacement_headline'] !== '') {
                $line .= ' Replacement headline: '.$creative['replacement_headline'].'.';
            }

            if ($creative['replacement_primary_text'] !== '') {
                $line .= ' Primary text: '.$creative['replacement_primary_text'].'.';
            }

            if (($creative['replacement_secondary_text'] ?? '') !== '') {
                $line .= ' Secondary text: '.$creative['replacement_secondary_text'].'.';
            }

            if ($creative['replacement_cta'] !== '') {
                $line .= ' Call to action: '.$creative['replacement_cta'].'.';
            }

            if (($creative['image_prompt'] ?? '') !== '') {
                $line .= ' Image prompt: '.$creative['image_prompt'].'.';
            }

            if (($creative['creative_id'] ?? '') !== '') {
                $line .= ' Creative id: '.$creative['creative_id'].'.';
            }

            $parts[] = $line;
        }

        if ($landing !== null) {
            $parts[] = 'Landing page: '.$landing['problem'].' Flow: '.$landing['flow'].' Headline: '.($landing['headline'] ?? '').' Section: '.($landing['section'] ?? '').' Call to action: '.($landing['cta'] ?? '').' '.($landing['content'] ?? '').(((string) ($landing['prompt'] ?? '')) !== '' ? ' Prompt: '.$landing['prompt'] : '');
        }

        if ($tests !== '') {
            $parts[] = 'Tests: '.$tests;
        }

        return implode("\n\n", array_values(array_filter($parts, fn (string $part): bool => trim($part) !== '')));
    }

    private function reasonShapeIsValid(string $reason, bool $usesPlan): bool
    {
        if ($usesPlan) {
            $lines = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $reason) ?: [])));

            if ($lines === [] || count($lines) > 3) {
                return false;
            }

            foreach ($lines as $line) {
                if (! $this->isSingleSentence($line)) {
                    return false;
                }
            }

            return true;
        }

        return $this->isSingleSentence($reason);
    }

    private function isSingleSentence(string $reason): bool
    {
        $masked = preg_replace('/\$\d+(?:\.\d+)?/', '0', $reason) ?? $reason;
        $masked = preg_replace('/\d+\.\d+/', '0', $masked) ?? $masked;

        return preg_match_all('/[.!?](?:\s|$)/', $masked) <= 1;
    }

    /**
     * @param  array<string, mixed>  $payload
     * @return list<string>
     */
    private function nextActionsFromPayload(array $payload): array
    {
        $rows = $payload['next_actions'] ?? null;

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

        $lines = [];

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

            $trimmed = trim($row);

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

        return $lines;
    }

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

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

        foreach ($matches[0] as [$raw, $offset]) {
            if ($this->numberAppearsInSnapshot((string) $raw, $json, $reason, (int) $offset)) {
                continue;
            }

            // A price or count read from the public site is not a campaign
            // result. Spend, clicks, and the other snapshot metrics still have
            // to match the numbers we measured.
            if ($this->numberIsCampaignMetric($reason, (int) $offset, strlen((string) $raw))) {
                return true;
            }
        }

        return false;
    }

    /**
     * CTR is stored as a ratio (0.0349) and may be written as a percent (3.49%).
     */
    private function numberAppearsInSnapshot(string $raw, string $json, string $reason, int $offset): bool
    {
        $plain = ltrim($raw, '$');

        if (str_contains($json, $plain)) {
            return true;
        }

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

        $after = substr($reason, $offset + strlen($raw), 1);

        if ($after !== '%' || ! is_numeric($plain)) {
            return false;
        }

        $ratio = rtrim(rtrim(number_format(((float) $plain) / 100, 8, '.', ''), '0'), '.');

        return $ratio !== '' && str_contains($json, $ratio);
    }

    private function numberIsCampaignMetric(string $reason, int $offset, int $length): bool
    {
        $start = max(0, $offset - 24);
        $window = strtolower(substr($reason, $start, $length + 48));
        $number = preg_quote(strtolower(substr($reason, $offset, $length)), '/');
        $metric = 'spend|impressions?|clicks?|ctr|cpc|cpa|roas|conversions?|orders?|revenue|budget|installs?';

        return preg_match('/(?:'.$metric.')[^a-z0-9]{0,12}'.$number.'|'.$number.'[^a-z0-9]{0,12}(?:'.$metric.')/', $window) === 1;
    }
}
