<?php

namespace Tests\Unit\Services\AI;

use App\Campaigns\PerformanceAdvice;
use App\Campaigns\PerformanceVerdict;
use App\Services\AI\CampaignPerformanceAdvisor;
use App\Services\Meta\GraphApi;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Laravel\Ai\Files\Base64Image;
use Laravel\Ai\Files\RemoteImage;
use Laravel\Ai\Files\StoredImage;
use Laravel\Ai\Providers\Tools\WebSearch;
use Laravel\Ai\StructuredAnonymousAgent;
use Tests\TestCase;

class CampaignPerformanceAdvisorTest extends TestCase
{
    public function test_it_keeps_a_pause_reason_that_uses_snapshot_spend(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.skip_llm_while_learning' => false]);

        StructuredAnonymousAgent::fake([
            [
                'reason' => 'Pause this campaign after $12.10 spend and 0 clicks.',
                'confidence' => 'high',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame(PerformanceVerdict::Pause, $advice->status);
        $this->assertStringContainsString('$12.10', $advice->reason);
    }

    public function test_it_stores_the_model_status_without_replacing_the_php_verdict(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'status' => 'pause',
                'reason' => 'Pause this campaign because the lagged window shows no sales.',
                'confidence' => 'high',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame(PerformanceVerdict::NoAction, $advice->status);
        $this->assertSame('pause', $advice->aiStatus);
        $this->assertSame('llm', $advice->source);
    }

    public function test_an_unknown_ai_status_is_left_empty(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'status' => 'duplicate',
                'reason' => 'Keep watching this campaign.',
                'confidence' => 'low',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame(PerformanceVerdict::NoAction, $advice->status);
        $this->assertNull($advice->aiStatus);
        $this->assertSame('llm', $advice->source);
    }

    public function test_it_keeps_the_php_verdict_even_when_the_model_tries_to_change_it(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.skip_llm_while_learning' => false]);

        StructuredAnonymousAgent::fake([
            [
                'reason' => '$12.10 spend looks healthy so keep running.',
                'confidence' => 'high',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame(PerformanceVerdict::Pause, $advice->status);
    }

    public function test_the_brief_stores_next_actions_and_locks_the_snapshot_verdict(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'status' => 'pause',
                'primary_lever' => 'improve_creative',
                'reason' => 'Fix the Browser for Mac headline so it names the offer.',
                'confidence' => 'high',
                'next_actions' => [
                    'Rewrite the Browser for Mac headline to name the offer.',
                    'Keep the $12.10 spend unchanged while the new headline is tested.',
                ],
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['verdict'] = 'pause';

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainBrief($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame(PerformanceVerdict::Pause, $advice->status);
        $this->assertSame('pause', $advice->aiStatus);
        $this->assertSame('Fix the Browser for Mac headline so it names the offer.', $advice->reason);
        $this->assertSame([
            'Rewrite the Browser for Mac headline to name the offer.',
            'Keep the $12.10 spend unchanged while the new headline is tested.',
        ], $advice->nextActions);
        $this->assertNull($advice->review);
    }

    public function test_a_watch_brief_that_pauses_the_campaign_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.skip_llm_while_learning' => false]);

        StructuredAnonymousAgent::fake([
            [
                'status' => 'watch',
                'reason' => 'Pause the campaign until frequency drops on $80.00 spend.',
                'confidence' => 'medium',
                'next_actions' => [
                    'Pause the campaign until frequency drops.',
                    'Keep Lucos retargeting on $80.00 spend.',
                ],
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['verdict'] = 'watch';
        $snapshot['windows'] = ['7d' => ['spend' => 80, 'impressions' => 2000, 'clicks' => 40]];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'PHP watch reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainBrief($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP watch reason', $advice->reason);
    }

    public function test_the_brief_discards_a_two_sentence_reason_without_a_plan(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'Spend is low. Pause this campaign.', 'confidence' => 'high'],
            ['reason' => 'Spend is low. Pause this campaign.', 'confidence' => 'high'],
            ['reason' => 'Spend is low. Pause this campaign.', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainBrief($this->snapshot(), $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP pause reason', $advice->reason);
        $this->assertSame([], $advice->nextActions);
    }

    public function test_it_does_not_call_the_agent_when_llm_is_disabled(): void
    {
        config(['campaign-performance.llm_enabled' => false]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'should not run', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('php', $advice->source);
        StructuredAnonymousAgent::assertPromptedTimes(0);
    }

    public function test_an_invented_amount_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.skip_llm_while_learning' => false]);

        StructuredAnonymousAgent::fake([
            ['reason' => '$9999 spend. Pause this campaign.', 'confidence' => 'high'],
            ['reason' => '$9999 spend. Pause this campaign.', 'confidence' => 'high'],
            ['reason' => '$9999 spend. Pause this campaign.', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP pause reason', $advice->reason);
    }

    public function test_a_ctr_percent_is_kept_when_the_snapshot_stores_the_ratio(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'CTR: 4.17% and the campaign should pause.', 'confidence' => 'high'],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['windows']['15d']['ctr'] = 0.0417;

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('4.17%', $advice->reason);
    }

    public function test_a_ctr_percent_that_is_not_in_the_snapshot_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'CTR: 8.63% and the campaign should pause.', 'confidence' => 'high'],
            ['reason' => 'CTR: 8.63% and the campaign should pause.', 'confidence' => 'high'],
            ['reason' => 'CTR: 8.63% and the campaign should pause.', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP pause reason', $advice->reason);
    }

    public function test_a_price_read_from_the_page_is_kept(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'The public page offers the Pro plan at $19 a month. Pause this campaign.', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('$19', $advice->reason);
    }

    public function test_a_page_price_in_the_same_paragraph_as_spend_is_kept(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'The public page lists the Pro plan at $19 a month. Spend is 12.1 and the campaign should pause.', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('$19', $advice->reason);
    }

    public function test_a_lever_that_disagrees_with_the_marketing_call_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['status' => 'scale_up', 'primary_lever' => 'spend_more', 'reason' => 'Spend more because CTR is 6.06% and the page can wait.', 'confidence' => 'high'],
            ['status' => 'scale_up', 'primary_lever' => 'spend_more', 'reason' => 'Spend more because CTR is 6.06% and the page can wait.', 'confidence' => 'high'],
            ['status' => 'scale_up', 'primary_lever' => 'spend_more', 'reason' => 'Spend more because CTR is 6.06% and the page can wait.', 'confidence' => 'high'],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = [
            'primary_lever' => 'fix_landing_page',
            'summary' => 'Fix the landing page.',
            'signals' => ['ctr_percent' => 6.06],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP pause reason', $advice->reason);
    }

    public function test_a_one_sentence_reason_is_stored(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'Fix the Browser for Mac headline so it names the offer.',
                'confidence' => 'medium',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame('Fix the Browser for Mac headline so it names the offer.', $advice->reason);
    }

    public function test_a_three_line_plan_that_matches_the_lever_is_kept(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => "Checked the last 7 days.\nImprove the creative.\n800 impressions produced 0 clicks, so the landing page has not been tested.",
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = [
            'primary_lever' => 'improve_creative',
            'plan' => [
                'Checked the last 7 days.',
                'Improve the creative.',
                '800 impressions produced 0 clicks, so the landing page has not been tested.',
            ],
        ];

        $php = new PerformanceAdvice(
            PerformanceVerdict::Pause,
            implode("\n", $snapshot['marketing_diagnosis']['plan']),
            'php',
        );
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('Improve the creative.', $advice->reason);
        $this->assertStringContainsString('800 impressions', $advice->reason);
    }

    public function test_a_two_sentence_reason_is_kept(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'Spend is low. Pause this campaign.', 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('Spend is low.', $advice->reason);
        $this->assertStringContainsString('Pause this campaign.', $advice->reason);
    }

    public function test_an_overlong_reason_falls_back_to_php(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => str_repeat('a', 24001), 'confidence' => 'high'],
            ['reason' => str_repeat('a', 24001), 'confidence' => 'high'],
            ['reason' => str_repeat('a', 24001), 'confidence' => 'high'],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP pause reason', $advice->reason);
    }

    public function test_it_retries_until_a_window_comparison_answer_is_accepted(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => "Checked the last 7 days.\nImprove the creative.\n800 impressions produced 0 clicks.",
                'confidence' => 'medium',
            ],
            [
                'primary_lever' => 'improve_creative',
                'reason' => "3-day spend is $3.00 with 2 clicks.\n7-day spend is $8.00 with 4 clicks.\n15-day spend is $12.00 with 6 clicks.",
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = [
            'primary_lever' => 'improve_creative',
            'plan' => [
                'Checked the last 7 days.',
                'Improve the creative.',
                '800 impressions produced 0 clicks.',
            ],
        ];
        $snapshot['window_comparison'] = [
            '3d' => ['spend' => 3.0, 'clicks' => 2, 'impressions' => 100, 'conversions' => 0, 'conversion_value' => 0.0, 'buckets' => 3, 'expected_buckets' => 3],
            '7d' => ['spend' => 8.0, 'clicks' => 4, 'impressions' => 200, 'conversions' => 0, 'conversion_value' => 0.0, 'buckets' => 7, 'expected_buckets' => 7],
            '15d' => ['spend' => 12.0, 'clicks' => 6, 'impressions' => 300, 'conversions' => 0, 'conversion_value' => 0.0, 'buckets' => 11, 'expected_buckets' => 15],
        ];

        $php = new PerformanceAdvice(
            PerformanceVerdict::NoAction,
            implode("\n", $snapshot['marketing_diagnosis']['plan']),
            'php',
        );
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('15-day', $advice->reason);
        StructuredAnonymousAgent::assertPromptedTimes(2);
    }

    public function test_three_failed_attempts_fall_back_to_php_reason(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['primary_lever' => 'improve_creative', 'reason' => 'Missing windows.', 'confidence' => 'medium'],
            ['primary_lever' => 'improve_creative', 'reason' => 'Still missing windows.', 'confidence' => 'medium'],
            ['primary_lever' => 'improve_creative', 'reason' => 'Still not comparing windows.', 'confidence' => 'medium'],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = [
            'primary_lever' => 'improve_creative',
            'plan' => ['Line one.', 'Line two.', 'Line three.'],
        ];
        $snapshot['window_comparison'] = [
            '3d' => ['spend' => 3.0, 'clicks' => 2, 'impressions' => 100, 'conversions' => 0, 'conversion_value' => 0.0, 'buckets' => 3, 'expected_buckets' => 3],
            '7d' => ['spend' => 8.0, 'clicks' => 4, 'impressions' => 200, 'conversions' => 0, 'conversion_value' => 0.0, 'buckets' => 7, 'expected_buckets' => 7],
            '15d' => ['spend' => 12.0, 'clicks' => 6, 'impressions' => 300, 'conversions' => 0, 'conversion_value' => 0.0, 'buckets' => 11, 'expected_buckets' => 15],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'PHP fallback reason.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('PHP fallback reason.', $advice->reason);
        StructuredAnonymousAgent::assertPromptedTimes(3);
    }

    public function test_a_30_day_lookup_must_name_the_days_on_file_and_the_decision_window(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => "3-day spend is \$3.00.\n7-day spend is \$8.00.\n15-day spend is \$12.00.",
                'confidence' => 'medium',
            ],
            [
                'primary_lever' => 'improve_creative',
                'reason' => "Looked at 2 of the last 30 days, from 2026-08-24 to 2026-09-22, and decided from the last 7 days.\nImprove the creative.\n800 impressions produced 0 clicks.",
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = [
            'primary_lever' => 'improve_creative',
            'lookup_basis' => '7d',
            'plan' => [
                'Looked at 2 of the last 30 days, from 2026-08-24 to 2026-09-22, and decided from the last 7 days.',
                'Improve the creative.',
                '800 impressions produced 0 clicks.',
            ],
        ];
        $snapshot['daily_history'] = [
            'from' => '2026-08-24',
            'to' => '2026-09-22',
            'expected_days' => 30,
            'days_on_file' => 2,
        ];
        $snapshot['window_comparison'] = [
            '3d' => ['spend' => 3.0, 'clicks' => 2],
            '7d' => ['spend' => 8.0, 'clicks' => 4],
            '15d' => ['spend' => 12.0, 'clicks' => 6],
        ];

        $php = new PerformanceAdvice(
            PerformanceVerdict::NoAction,
            implode("\n", $snapshot['marketing_diagnosis']['plan']),
            'php',
        );
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('2 of the last 30 days', $advice->reason);
        StructuredAnonymousAgent::assertPromptedTimes(2);
    }

    public function test_it_keeps_the_ai_reason_when_the_verdict_is_no_action(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'reason' => 'Rename the Browser for Mac headline so it names the offer.',
                'confidence' => 'medium',
                'creatives' => [[
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The headline does not name the offer.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_cta' => 'Download',
                ]],
                'landing_problem' => 'The page does not name the offer.',
                'landing_flow' => 'Open with the offer, then one next step.',
                'landing_headline' => 'Browser for Mac search',
                'landing_section' => 'Search the web from the Mac browser.',
                'landing_cta' => 'Download',
                'landing_content' => 'Headline: Browser for Mac search. Button: Download.',
                'analysis' => $this->analysis('12.10', '800'),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['verdict'] = 'learning';
        $snapshot['creative_context'] = [
            'found' => true,
            'landing_url' => 'https://example.com/mac',
            'creatives' => [
                ['headline' => 'Browser for Mac'],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame(PerformanceVerdict::NoAction, $advice->status);
        $this->assertSame('Browser for Mac', $advice->review['creatives'][0]['current_headline']);
        $this->assertStringContainsString('1. Rewrite the first screen', $advice->reason);
    }

    public function test_a_landing_page_verdict_keeps_the_problem_flow_and_copy(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'fix_landing_page',
                'reason' => 'Fix the landing page because CTR is 3.5% on 21 clicks and lagged spend of 59.57 produced no results.',
                'confidence' => 'medium',
                'landing_problem' => 'The page opens on a logo and never states the offer.',
                'landing_flow' => 'Open with the risk, then the proof, then one next step.',
                'landing_headline' => 'See the risk before you merge',
                'landing_section' => 'Show the file change, then the time it would have cost.',
                'landing_cta' => 'Review my repo',
                'landing_content' => 'Headline: See the risk before you merge. Button: Review my repo.',
                'analysis' => $this->analysis('21', '3.5'),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = [
            'primary_lever' => 'fix_landing_page',
            'summary' => 'Fix the landing page.',
        ];
        $snapshot['creative_context'] = [
            'found' => true,
            'landing_page' => [
                'text' => 'The page opens on a logo and a single button.',
                'headings' => ['See the risk before you merge'],
            ],
        ];
        $snapshot['windows'] = [
            '7d' => ['clicks' => 21, 'ctr_percent' => 3.5],
        ];
        $snapshot['channels'] = ['outcome' => ['platform_spend' => 59.57]];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'Fix the landing page.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame('The page opens on a logo and never states the offer.', $advice->landingSuggestion['problem']);
        $this->assertSame('Open with the risk, then the proof, then one next step.', $advice->landingSuggestion['flow']);
        $this->assertSame('Headline: See the risk before you merge. Button: Review my repo.', $advice->landingSuggestion['content']);
        $this->assertSame('See the risk before you merge', $advice->landingSuggestion['headline']);
        $this->assertSame('Review my repo', $advice->landingSuggestion['cta']);
    }

    public function test_missing_creative_suggestions_are_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            ['reason' => 'Improve the creative.', 'confidence' => 'medium'],
            ['reason' => 'Improve the creative.', 'confidence' => 'medium'],
            ['reason' => 'Improve the creative.', 'confidence' => 'medium'],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'found' => true,
            'ads' => [
                ['ad_id' => '1', 'headline' => 'Browser for Mac', 'primary_text' => 'Search faster.'],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertNull($advice->review);
    }

    public function test_a_full_review_keeps_creative_and_landing_changes(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'fix_landing_page',
                'reason' => 'Clicks are arriving and the page is not converting. Fix the landing page before spending more.',
                'confidence' => 'high',
                'budget' => 'Keep the daily budget at 20.',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The headline names the product and not the offer.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_cta' => 'Download',
                ]],
                'landing_problem' => 'The page opens on a logo and never states the offer.',
                'landing_flow' => 'Open with the risk, then the proof, then one next step.',
                'landing_headline' => 'See the risk before you merge',
                'landing_section' => 'Show the file change, then the time it would have cost.',
                'landing_cta' => 'Review my repo',
                'landing_content' => 'Headline: See the risk before you merge. Button: Review my repo.',
                'landing_prompt' => 'This is an offsite sign-up page for a leads objective, not a download page. Open with the headline, then the first section, then the sign-up button.',
                'tests' => 'Replace the headline on ad 1 and watch CTR. Then replace the page headline and watch results.',
                'analysis' => $this->analysis('20', 'Browser for Mac search'),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = ['primary_lever' => 'fix_landing_page'];
        $snapshot['campaign_goals'] = ['objective' => 'OUTCOME_LEADS', 'optimization_goals' => ['OFFSITE_CONVERSIONS']];
        $snapshot['creative_context'] = [
            'found' => true,
            'ads' => [
                ['ad_id' => '1', 'headline' => 'Browser for Mac', 'primary_text' => 'Search faster.'],
            ],
            'landing_page' => [
                'text' => 'The page opens on a logo and a single button.',
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'Fix the landing page.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame('change', $advice->review['creatives'][0]['action']);
        $this->assertSame('Browser for Mac search', $advice->review['creatives'][0]['replacement_headline']);
        $this->assertSame('', $advice->review['creatives'][0]['image_prompt']);
        $this->assertSame('See the risk before you merge', $advice->review['landing']['headline']);
        $this->assertStringContainsString('offsite sign-up page', $advice->review['landing']['prompt']);
        $this->assertStringContainsString('1. Rewrite the first screen', $advice->reason);
        $this->assertArrayNotHasKey('do_not', $advice->review);
    }

    public function test_a_creative_change_keeps_the_image_prompt_secondary_text_and_snapshot_id(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'reason' => 'The picture does not show the offer.',
                'confidence' => 'medium',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The picture shows a logo and not the search.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_secondary_text' => 'Free on Mac.',
                    'replacement_cta' => 'Download',
                    'image_prompt' => 'Meta feed still, portrait crop, one frame. The studio makes the still. Current still is a logo on white. Change to a Mac laptop on a desk, over-the-shoulder, window light from the left, cool grey and one accent blue. Exact on-image line: "Browser for Mac search". High-contrast sans type in the top third. No extra slogans, no button chrome, no other-product logos.',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'found' => true,
            'ads' => [[
                'ad_id' => '1',
                'creative_id' => '925887686918149',
                'headline' => 'Browser for Mac',
                'primary_text' => 'Search faster.',
                'images' => [[
                    'ad_id' => '1',
                    'creative_id' => '925887686918149',
                    'url' => 'https://cdn.example/mac.jpg',
                    'kind' => 'image',
                ]],
            ]],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame('925887686918149', $advice->review['creatives'][0]['creative_id']);
        $this->assertSame('Free on Mac.', $advice->review['creatives'][0]['replacement_secondary_text']);
        $this->assertStringContainsString('Meta feed still', $advice->review['creatives'][0]['image_prompt']);
        $this->assertStringContainsString('Exact on-image line', $advice->review['creatives'][0]['image_prompt']);
        $this->assertStringContainsString('window light', $advice->review['creatives'][0]['image_prompt']);
    }

    public function test_a_creative_image_change_without_a_prompt_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'reason' => 'The picture does not show the offer.',
                'confidence' => 'medium',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The picture shows a logo and not the search.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_cta' => 'Download',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
            [
                'reason' => 'The picture does not show the offer.',
                'confidence' => 'medium',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The picture shows a logo and not the search.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_cta' => 'Download',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
            [
                'reason' => 'The picture does not show the offer.',
                'confidence' => 'medium',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Browser for Mac',
                    'action' => 'change',
                    'why' => 'The picture shows a logo and not the search.',
                    'replacement_headline' => 'Browser for Mac search',
                    'replacement_primary_text' => 'Search the web from the Mac browser.',
                    'replacement_cta' => 'Download',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'found' => true,
            'ads' => [[
                'ad_id' => '1',
                'creative_id' => '925887686918149',
                'headline' => 'Browser for Mac',
                'primary_text' => 'Search faster.',
                'images' => [[
                    'ad_id' => '1',
                    'creative_id' => '925887686918149',
                    'kind' => 'image',
                ]],
            ]],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertNull($advice->review);
    }

    public function test_a_leads_campaign_without_a_landing_page_prompt_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        $payload = [
            'primary_lever' => 'fix_landing_page',
            'reason' => 'Clicks are arriving and the page is not converting.',
            'confidence' => 'high',
            'landing_problem' => 'The page opens on a logo and never states the offer.',
            'landing_flow' => 'Open with the offer, then one next step.',
            'landing_headline' => 'See the risk before you merge',
            'landing_section' => 'Show the file change, then the time it would have cost.',
            'landing_cta' => 'Review my repo',
            'landing_content' => 'Headline: See the risk before you merge. Button: Review my repo.',
            'analysis' => $this->analysis('12.10', '800'),
        ];

        StructuredAnonymousAgent::fake([$payload, $payload, $payload]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = ['primary_lever' => 'fix_landing_page'];
        $snapshot['campaign_goals'] = ['objective' => 'OUTCOME_LEADS', 'optimization_goals' => ['OFFSITE_CONVERSIONS']];
        $snapshot['creative_context'] = [
            'found' => true,
            'landing_url' => 'https://example.com/mac',
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertNull($advice->review);
    }

    public function test_a_landing_page_verdict_without_a_rewrite_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'fix_landing_page',
                'reason' => 'Fix the landing page because clicks arrived and the page produced no results.',
                'confidence' => 'medium',
            ],
            [
                'primary_lever' => 'fix_landing_page',
                'reason' => 'Fix the landing page because clicks arrived and the page produced no results.',
                'confidence' => 'medium',
            ],
            [
                'primary_lever' => 'fix_landing_page',
                'reason' => 'Fix the landing page because clicks arrived and the page produced no results.',
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['marketing_diagnosis'] = ['primary_lever' => 'fix_landing_page'];
        $snapshot['creative_context'] = [
            'landing_page' => ['text' => 'The page opens on a logo and a single button.'],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'Fix the landing page.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertNull($advice->landingSuggestion);
    }

    public function test_a_detailed_review_longer_than_a_short_memo_is_kept(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        $analysis = str_repeat('The creative is earning the click but the page is not. ', 180);
        $analysis .= "\n1. Rewrite the first screen around the offer already on the page.\n2. Keep the ad that earns the click.\n3. Replace the weaker headline.\n4. Judge the next period on clicks and results.";

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'fix_landing_page',
                'reason' => 'The page is not converting the clicks the creative earns.',
                'analysis' => $analysis,
                'confidence' => 'medium',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::Pause, 'PHP pause reason', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        $this->assertGreaterThan(8000, mb_strlen($analysis));
        $this->assertSame('llm', $advice->source);
        $this->assertStringContainsString('earning the click', $advice->reason);
    }

    public function test_a_blocked_creative_image_is_left_for_the_model_to_fetch(): void
    {
        config(['campaign-performance.llm_enabled' => true]);
        Http::fake([
            'https://cdn.example/*' => Http::response('denied', 403),
        ]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'The headline does not match the offer on the page.',
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'images' => [
                ['ad_id' => 'ad-1', 'url' => 'https://cdn.example/shoe.jpg', 'kind' => 'image'],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        StructuredAnonymousAgent::assertPrompted(function (object $prompt): bool {
            return $prompt->attachments->count() === 1
                && $prompt->attachments[0] instanceof RemoteImage
                && $prompt->attachments[0]->url === 'https://cdn.example/shoe.jpg';
        });
    }

    public function test_an_expired_creative_image_is_replaced_from_meta(): void
    {
        config(['campaign-performance.llm_enabled' => true]);
        Http::fake([
            'https://cdn.example/old.jpg' => Http::response('URL signature expired', 403),
            'https://cdn.example/fresh.jpg' => Http::response('image-bytes', 200, ['Content-Type' => 'image/jpeg']),
        ]);

        $graph = \Mockery::mock(GraphApi::class);
        $graph->shouldReceive('creativeImageUrl')
            ->once()
            ->with('925887686918149', 'act_42')
            ->andReturn('https://cdn.example/fresh.jpg');
        $this->app->instance(GraphApi::class, $graph);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'The headline does not match the offer on the page.',
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['account_id'] = 'act_42';
        $snapshot['creative_context'] = [
            'images' => [
                [
                    'ad_id' => 'ad-1',
                    'creative_id' => '925887686918149',
                    'url' => 'https://cdn.example/old.jpg',
                    'kind' => 'image',
                ],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        StructuredAnonymousAgent::assertPrompted(function (object $prompt): bool {
            return $prompt->attachments->count() === 1
                && $prompt->attachments[0] instanceof Base64Image;
        });
    }

    public function test_the_recommendation_can_search_the_web(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.web_search' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'The headline does not match the offer on the page.',
                'confidence' => 'medium',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        StructuredAnonymousAgent::assertPrompted(function (object $prompt): bool {
            $search = collect($prompt->agent->tools())->first(fn (mixed $tool): bool => $tool instanceof WebSearch);

            return $search instanceof WebSearch && $search->maxSearches === 3 && $search->allowedDomains === [];
        });
    }

    public function test_the_search_reads_the_campaign_site_when_the_scrape_is_empty(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.web_search' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'The headline does not match the offer on the page.',
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'landing_url' => 'https://lucos.com/landing?utm_source=meta',
            'landing_page' => ['text' => ''],
            'website' => [
                'host' => 'www.lucos.com',
                'pages' => [
                    ['url' => 'https://lucos.com/', 'role' => 'homepage'],
                ],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        StructuredAnonymousAgent::assertPrompted(function (object $prompt): bool {
            $searches = collect($prompt->agent->tools())->filter(fn (mixed $tool): bool => $tool instanceof WebSearch)->values();
            $open = $searches->first(fn (WebSearch $tool): bool => $tool->allowedDomains === []);
            $site = $searches->first(fn (WebSearch $tool): bool => $tool->allowedDomains === ['lucos.com']);

            return $open instanceof WebSearch
                && $open->maxSearches === 3
                && $site instanceof WebSearch
                && $site->maxSearches === 3
                && str_contains($prompt->prompt, 'leave it out of the review')
                && str_contains($prompt->prompt, 'https://lucos.com/landing?utm_source=meta')
                && str_contains($prompt->prompt, 'https://lucos.com/');
        });
    }

    public function test_web_search_stays_off_when_it_is_disabled(): void
    {
        config(['campaign-performance.llm_enabled' => true, 'campaign-performance.web_search' => false]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'The headline does not match the offer on the page.',
                'confidence' => 'medium',
            ],
        ]);

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        (new CampaignPerformanceAdvisor)->explainReview($this->snapshot(), $php);

        StructuredAnonymousAgent::assertPrompted(function (object $prompt): bool {
            return collect($prompt->agent->tools())->contains(fn (mixed $tool): bool => $tool instanceof WebSearch) === false;
        });
    }

    public function test_it_attaches_still_images_and_includes_the_campaign_goal(): void
    {
        config(['campaign-performance.llm_enabled' => true]);
        Storage::fake('local');
        Storage::disk('local')->put('creatives/shoe.jpg', 'image-bytes');
        Http::fake([
            'https://cdn.example/*' => Http::response('image-bytes', 200, ['Content-Type' => 'image/jpeg']),
        ]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'improve_creative',
                'reason' => 'The shoe image does not show the offer on the page.',
                'confidence' => 'medium',
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['campaign_goals'] = [
            'objective' => 'OUTCOME_SALES',
            'optimization_goals' => ['OFFSITE_CONVERSIONS'],
        ];
        $snapshot['creative_context'] = [
            'images' => [
                ['ad_id' => 'ad-1', 'url' => 'https://cdn.example/shoe.jpg', 'kind' => 'image'],
                ['ad_id' => 'ad-2', 'url' => 'https://cdn.example/clip.mp4', 'kind' => 'image'],
                ['ad_id' => 'ad-3', 'disk' => 'local', 'path' => 'creatives/shoe.jpg', 'kind' => 'image'],
            ],
            'website' => [
                'host' => 'example.com',
                'pages' => [[
                    'url' => 'https://example.com/',
                    'role' => 'homepage',
                    'text' => 'We sell trail gear for long weekends.',
                ]],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Still learning.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        StructuredAnonymousAgent::assertPrompted(function (object $prompt): bool {
            return str_contains($prompt->prompt, 'OUTCOME_SALES')
                && str_contains($prompt->prompt, 'trail gear for long weekends')
                && str_contains($prompt->prompt, '1. ad ad-1 (image)')
                && str_contains($prompt->prompt, '2. ad ad-3 (image)')
                && $prompt->attachments->count() === 2
                && $prompt->attachments[0] instanceof Base64Image
                && $prompt->attachments[1] instanceof StoredImage
                && $prompt->attachments[1]->path === 'creatives/shoe.jpg';
        });
    }

    public function test_a_tracking_gate_keeps_ads_and_skips_the_landing_rewrite(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'hold',
                'reason' => 'The subscribe event is not firing after the recorded spend.',
                'confidence' => 'high',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Lucos vs Copilot vs Cursor',
                    'action' => 'change',
                    'why' => 'Write a new comparison ad.',
                    'replacement_headline' => 'Switch from Cursor',
                    'replacement_primary_text' => 'Keep the same price.',
                    'replacement_cta' => 'Sign up',
                ]],
                'landing_url' => 'https://lucos.example/signup',
                'analysis' => $this->rosterAnalysis(frozen: true),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'found' => true,
            'landing_url' => 'https://lucos.example/signup',
            'landing_page' => [
                'text' => 'Sign up for Lucos.',
                'headings' => ['Sign up'],
            ],
            'ads' => [[
                'ad_id' => '1',
                'headline' => 'Lucos vs Copilot vs Cursor',
                'primary_text' => 'Compare the tools.',
            ]],
        ];
        $snapshot['performance_strategy'] = [
            'broken_step' => 'tracking',
            'primary_result_label' => 'subscriptions',
            'ad_roster' => [
                'frozen' => true,
                'ads' => [[
                    'ad_id' => '1',
                    'label' => 'winner',
                    'llm_action' => 'keep',
                ]],
            ],
            'proposed_changes' => [[
                'action' => 'fix_tracking',
                'ad_id' => null,
                'text' => 'Check Events Manager and a test conversion for the optimization event before changing ads or the page.',
            ]],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Check tracking.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('llm', $advice->source);
        $this->assertSame('keep', $advice->review['creatives'][0]['action']);
        $this->assertSame('', $advice->review['creatives'][0]['replacement_headline']);
        $this->assertNull($advice->landingSuggestion);
        $this->assertStringContainsString('Ad-by-ad', $advice->review['analysis']);
        $this->assertStringContainsString('Proposed changes', $advice->review['analysis']);
    }

    public function test_a_roster_review_without_ad_by_ad_is_discarded(): void
    {
        config(['campaign-performance.llm_enabled' => true]);

        StructuredAnonymousAgent::fake([
            [
                'primary_lever' => 'hold',
                'reason' => 'The subscribe event is not firing after the recorded spend.',
                'confidence' => 'high',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Lucos vs Copilot vs Cursor',
                    'action' => 'keep',
                    'why' => 'Tracking is still broken.',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
            [
                'primary_lever' => 'hold',
                'reason' => 'The subscribe event is not firing after the recorded spend.',
                'confidence' => 'high',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Lucos vs Copilot vs Cursor',
                    'action' => 'keep',
                    'why' => 'Tracking is still broken.',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
            [
                'primary_lever' => 'hold',
                'reason' => 'The subscribe event is not firing after the recorded spend.',
                'confidence' => 'high',
                'creatives' => [[
                    'ad_id' => '1',
                    'current_headline' => 'Lucos vs Copilot vs Cursor',
                    'action' => 'keep',
                    'why' => 'Tracking is still broken.',
                ]],
                'analysis' => $this->analysis('12.10', '800'),
            ],
        ]);

        $snapshot = $this->snapshot();
        $snapshot['creative_context'] = [
            'found' => true,
            'ads' => [[
                'ad_id' => '1',
                'headline' => 'Lucos vs Copilot vs Cursor',
            ]],
        ];
        $snapshot['performance_strategy'] = [
            'broken_step' => 'tracking',
            'ad_roster' => [
                'frozen' => true,
                'ads' => [[
                    'ad_id' => '1',
                    'label' => 'winner',
                    'llm_action' => 'keep',
                ]],
            ],
        ];

        $php = new PerformanceAdvice(PerformanceVerdict::NoAction, 'Check tracking.', 'php');
        $advice = (new CampaignPerformanceAdvisor)->explainReview($snapshot, $php);

        $this->assertSame('php', $advice->source);
        $this->assertSame('Check tracking.', $advice->reason);
    }

    private function analysis(string ...$numbers): string
    {
        $listed = implode(' and ', $numbers);

        return <<<TEXT
Current performance
Spend and clicks in the snapshot include {$listed}.

What is working
The click rate shows the current message can earn the click.

The bottleneck
Results after the click are the constraint, so the next change is the page and a fresh creative angle.

1. Rewrite the first screen around the offer already in the snapshot.
2. Keep the ads that are earning clicks and write a new headline for the weaker one.
3. Put the price, the product proof, and one call to action above the fold.
4. Judge the next period on click rate and results, using the same window as this review.
TEXT;
    }

    private function rosterAnalysis(bool $frozen = false): string
    {
        $creative = $frozen
            ? "Creative not yet\nFix tracking before rewriting ads or the page."
            : "Creative\nKeep the winner and write a new headline for the weaker ad.";

        return <<<TEXT
Current performance
Subscribe is the optimization event. Spend and clicks in the snapshot include 12.10 and 800. Tracking is missing the event after this spend.

The bottleneck
Tracking is the constraint, so Events Manager is the next check before ads or the page change.

Ad-by-ad
Ad 1 is winner. Do not relabel it.

Fatigue
Per-ad frequency is not on file. Ranking is not on file.

{$creative}

Proposed changes
1. Check Events Manager and a test conversion for the subscribe event.
2. Keep ad 1 until the event fires.
3. Do not rewrite the landing page yet.
4. Judge the next period on the same subscribe event.
TEXT;
    }

    /**
     * @return array<string, mixed>
     */
    private function snapshot(): array
    {
        return [
            'campaign' => 'Italy packages',
            'platform' => 'meta',
            'platform_status' => 'ACTIVE',
            'daily_budget' => 20,
            'days_live' => 10,
            'learning_window_days' => 3,
            'max_test_spend' => 40,
            'last_7_days' => [
                'spend' => 12.1,
                'impressions' => 800,
                'clicks' => 0,
                'cpc' => null,
                'ctr' => null,
            ],
            'last_7_hours' => [
                'spend' => 3.5,
                'impressions' => 200,
                'clicks' => 0,
                'cpc' => null,
                'ctr' => null,
                'hours' => 5,
            ],
            'yesterday' => ['spend' => 12.1, 'impressions' => 400, 'clicks' => 0],
            'rules' => ['zero_click_spend_floor' => 10, 'max_cpc' => 2.0],
            'final_verdict' => 'pause',
            'final_reason' => '$12.10 spend and 0 clicks over 7 days. Suggestion: pause this campaign.',
            'allowed_verdicts' => ['no_action', 'continue', 'pause', 'stop', 'start', 'action_required'],
        ];
    }
}
