<?php

namespace Tests\Unit;

use App\Library\CampaignDecision\CampaignPerformanceBrief;
use Tests\TestCase;

class CampaignPerformanceBriefTest extends TestCase
{
    public function test_it_builds_a_short_brief_with_scaling_stance_and_internal_metrics(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'decrease_budget',
            'reason' => 'ROAS is below minimum but orders are still coming in.',
            'recommended_budget_change_percent' => -10,
            'daily_budget' => 50,
            'campaign_profile' => [
                'objective' => 'OUTCOME_SALES',
            ],
            'windows' => [
                '7d' => [
                    'spend' => 299.87,
                    'impressions' => 18317,
                    'clicks' => 173,
                    'ctr' => 0.0094,
                    'cpc' => 1.73,
                    'conversions' => 3,
                ],
                'outcome_7d' => [
                    'platform_spend' => 299.87,
                    'orders' => 3,
                    'revenue' => 17.97,
                    'roas' => 0.06,
                    'cpa' => 99.96,
                    'revenue_source' => 'affiliate',
                    'from' => '2026-10-08',
                    'to' => '2026-10-14',
                ],
            ],
            'affiliate' => [
                'matched' => true,
                'lag_days' => 2,
                'revenue_source' => 'affiliate',
            ],
            'marketing_diagnosis' => [
                'primary_lever' => 'fix_landing_page',
                'summary' => 'Do not spend more. Fix the landing page before buying more traffic.',
                'plan' => [
                    'Checked the last 7 days.',
                    'Fix the landing page.',
                    'Clicks arrive but results are expensive.',
                ],
            ],
            'capabilities' => [
                'internal_revenue_available' => true,
                'ingest_healthy' => true,
            ],
        ], 'decrease_budget');

        $this->assertSame(21, $brief['version']);
        $this->assertSame('decrease_budget', $brief['verdict']);
        $this->assertSame('Sales / conversions', $brief['objective']);
        $this->assertStringContainsString('budget', strtolower($brief['scaling_stance']));
        $this->assertSame('Offer cost', $brief['primary_bottleneck']);
        $this->assertNotEmpty($brief['short_lines']);
        $this->assertLessThanOrEqual(6, count($brief['next_actions']));
        $this->assertTrue(collect($brief['metrics'])->contains(
            fn (array $metric): bool => $metric['label'] === 'CPA' && $metric['group'] === 'internal',
        ));
        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('99.96', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringContainsString('0.06', $joined);
        $this->assertStringContainsString('scale this campaign only after', $joined);
        $this->assertStringContainsString('underperforming', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringContainsString('Performance: Poor', implode(' ', $brief['insights']));
        $this->assertStringContainsString('ROAS is below', implode(' ', $brief['insights']));
        $this->assertStringContainsString('0.06', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringContainsString('Internal lag window', (string) $brief['internal_window_label']);
    }

    public function test_landing_howto_stays_brief_and_objective_led_while_learning(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'reason' => 'Campaign is still in the learning period.',
            'campaign_profile' => [
                'objective' => 'OUTCOME_LEADS',
            ],
            'creative_context' => [
                'found' => true,
                'landing_url' => 'https://example.com/offer',
                'ads' => [
                    [
                        'headline' => 'Why pay $100+ for AI coding tools?',
                        'cta' => 'Get Started',
                    ],
                ],
            ],
            'marketing_diagnosis' => [
                'primary_lever' => 'fix_landing_page',
                'summary' => 'Clicks arrive but results are weak after the page.',
                'plan' => [
                    'Checked the last 7 days.',
                    'Fix the landing page.',
                    'Clicks arrive but results are expensive.',
                ],
                'signals' => ['ctr_percent' => 1.2],
            ],
            'windows' => [
                '7d' => ['spend' => 20, 'impressions' => 1000, 'clicks' => 12, 'ctr' => 0.012, 'cpc' => 1.6, 'conversions' => 0],
            ],
            'affiliate' => ['matched' => false],
            'capabilities' => ['internal_revenue_available' => false, 'ingest_healthy' => true],
        ], 'learning');

        $this->assertSame('learning', $brief['verdict']);
        $this->assertSame('Leads', $brief['objective']);
        $this->assertStringContainsString('Landing page', $brief['primary_bottleneck']);
        $this->assertStringContainsString('not turning them into leads', $brief['scaling_stance']);
        $this->assertLessThanOrEqual(6, count($brief['next_actions']));
        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('why pay $100+', $joined);
        $this->assertStringContainsString('https://example.com/offer', $joined);
        $this->assertStringContainsString('make the first screen ask for the leads', $joined);
        $this->assertStringNotContainsString('set the first heading', $joined);
        $this->assertStringNotContainsString('get started', $joined);
        $this->assertStringNotContainsString('savings, proof', $joined);
        $this->assertStringNotContainsString('page owner', $joined);
        $insightText = strtolower(implode(' ', $brief['insights']));
        $this->assertStringContainsString('underperforming', $insightText);
        $this->assertStringContainsString('performance:', $insightText);
        $this->assertStringNotContainsString('still learning — keep budget steady', $insightText);
        $this->assertFalse(collect($brief['next_actions'])->contains(
            fn (string $action): bool => strtolower(trim($action)) === 'fix the landing page.',
        ));
    }

    public function test_it_notes_missing_internal_data_without_treating_it_as_zero_revenue(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'reason' => 'Platform hour metrics are weak.',
            'windows' => [
                '7d' => [
                    'spend' => 40,
                    'impressions' => 2000,
                    'clicks' => 20,
                    'ctr' => 0.01,
                    'cpc' => 2,
                    'conversions' => 0,
                ],
            ],
            'affiliate' => ['matched' => false],
            'capabilities' => [
                'internal_revenue_available' => false,
                'ingest_healthy' => true,
            ],
            'marketing_diagnosis' => [
                'primary_lever' => 'hold',
                'summary' => 'Hold until there is clearer evidence.',
                'plan' => [],
            ],
        ], 'watch');

        $this->assertSame('watch', $brief['verdict']);
        $this->assertTrue(collect($brief['insights'])->contains(
            fn (string $line): bool => str_contains($line, 'Internal outcomes are not matched'),
        ));
        $this->assertTrue(collect($brief['data_notes'])->contains(
            fn (string $note): bool => str_contains($note, 'Internal outcome rows were not matched'),
        ));
        $this->assertFalse(collect($brief['metrics'])->contains(
            fn (array $metric): bool => $metric['group'] === 'internal',
        ));
    }

    public function test_for_display_reuses_a_stored_v4_brief(): void
    {
        $stored = [
            'version' => 21,
            'short_lines' => ['Stored line'],
            'scaling_stance' => 'Stored stance',
            'objective' => 'Sales / conversions',
            'verdict' => 'maintain',
            'verdict_label' => 'Maintain',
            'primary_bottleneck' => 'None',
            'primary_lever' => null,
            'metrics' => [],
            'insights' => [],
            'next_actions' => [],
            'summary' => '',
            'data_notes' => [],
            'window_label' => 'last 7 days',
            'internal_window_label' => null,
        ];

        $brief = CampaignPerformanceBrief::forDisplay([
            'status' => 'maintain',
            'brief' => $stored,
        ]);

        $this->assertSame(['Stored line'], $brief['short_lines']);
        $this->assertSame('Stored stance', $brief['scaling_stance']);
    }

    public function test_zero_clicks_names_this_campaigns_ctr_instead_of_a_page_fix(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => ['spend' => 12.1, 'impressions' => 800, 'clicks' => 0, 'ctr' => 0, 'cpc' => null, 'conversions' => 0],
            ],
            'creative_context' => [
                'ads' => [['headline' => 'Ship code faster']],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'hold'],
        ], 'learning');

        $joined = strtolower(implode(' ', [$brief['scaling_stance'], ...$brief['insights'], ...$brief['next_actions']]));
        $this->assertStringContainsString('0 clicks', $joined);
        $this->assertStringContainsString('ship code faster', $joined);
        $this->assertStringNotContainsString('landing page', $joined);
    }

    public function test_thin_delivery_is_a_single_line(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => ['spend' => 1.5, 'impressions' => 20, 'clicks' => 0, 'conversions' => 0],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'hold'],
        ], 'learning');

        $this->assertStringContainsString('too small to name a problem', $brief['scaling_stance']);
        $this->assertStringContainsString('Not yet ready to judge', $brief['insights'][0]);
        $this->assertStringContainsString('Performance: Inconclusive', $brief['insights'][1]);
        $this->assertStringContainsString('Too few impressions and clicks to decide yet', $brief['insights'][1]);
        $this->assertStringContainsString('1.50', $brief['insights'][1]);
    }

    public function test_model_steps_replace_php_lines_only_when_they_cite_this_campaign(): void
    {
        $snapshot = [
            'verdict' => 'decrease_budget',
            'windows' => [
                '7d' => ['spend' => 299.87, 'impressions' => 1000, 'clicks' => 40, 'conversions' => 1],
            ],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'decrease_budget');

        $rejected = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Hold budget on every campaign.',
            'Fix the landing page.',
        ], $snapshot);
        $this->assertSame($brief['next_actions'], $rejected['next_actions']);

        $holding = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Hold budget — CPA is high on $299.87 spend.',
            '40 clicks are not turning into sales on this page.',
        ], $snapshot);
        $this->assertSame($brief['next_actions'], $holding['next_actions']);

        $accepted = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Cut the budget — CPA is high on $299.87 spend.',
            '40 clicks are not turning into sales on this page.',
        ], $snapshot);
        $this->assertSame('llm', $accepted['next_actions_source']);
        $this->assertStringContainsString('299.87', $accepted['next_actions'][0]);
    }

    public function test_model_steps_that_only_say_bring_cpc_under_are_rejected(): void
    {
        $snapshot = [
            'verdict' => 'learning',
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 2.5,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'learning');

        $rejected = CampaignPerformanceBrief::applyModelSteps($brief, [
            'CTR is 2.00% on $100.00 spend. Bring CPC under $2.00.',
            'Leave the budget as it is on this campaign.',
        ], $snapshot);

        $this->assertSame($brief['next_actions'], $rejected['next_actions']);
        $this->assertStringContainsString('placement', strtolower(implode(' ', $brief['next_actions'])));
        $this->assertStringNotContainsString('bring cpc under', strtolower(implode(' ', $rejected['next_actions'])));
    }

    public function test_healthy_ctr_with_expensive_cpc_is_not_a_page_break(): void
    {
        $snapshot = [
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 2.5,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ];

        $this->assertFalse(CampaignPerformanceBrief::pageIsTheBreak($snapshot));
    }

    public function test_zero_click_traffic_names_zero_clicks(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'windows' => [
                '7d' => [
                    'spend' => 42,
                    'impressions' => 700,
                    'clicks' => 0,
                    'ctr' => 0,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'hold'],
        ], 'watch');

        $joined = strtolower(implode(' ', $brief['insights']));
        $this->assertStringContainsString('0 clicks', $joined);
        $this->assertStringNotContainsString('weak — ad or audience', implode(' ', $brief['insights']));
    }

    public function test_a_pause_verdict_always_tells_the_buyer_to_pause(): void
    {
        $snapshot = [
            'verdict' => 'pause',
            'campaign_profile' => ['name' => 'Italy packages'],
            'windows' => [
                '7d' => ['spend' => 12.10, 'impressions' => 150, 'clicks' => 0, 'conversions' => 0],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'improve_creative'],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'pause');

        $this->assertSame(['Pause the campaign and stop all spend.'], $brief['next_actions']);
        $this->assertContains('pause', $brief['allowed_moves']);
        $this->assertNotContains('hold_budget', $brief['allowed_moves']);

        $modelSteps = CampaignPerformanceBrief::applyModelSteps(
            [...$brief, 'allowed_moves' => ['pause', 'new_creative']],
            ['Replace the ad for Italy packages.', 'Write a new image for Italy packages.'],
            $snapshot,
        );

        $this->assertSame('llm', $modelSteps['next_actions_source']);
        $this->assertSame('Pause the campaign and stop all spend.', $modelSteps['next_actions'][0]);
    }

    public function test_large_spend_with_no_results_is_named_as_past_an_early_read(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'creative_context' => [
                'ads' => [['headline' => 'One Wrong File Change Can Cost You 20 Minutes']],
                'landing_url' => 'https://lucos.com/landing',
            ],
            'windows' => [
                '30d' => [
                    'spend' => 267.03,
                    'impressions' => 3045,
                    'clicks' => 136,
                    'ctr' => 0.0447,
                    'cpc' => 1.96,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $this->assertSame('learning', $brief['verdict']);
        $this->assertStringContainsString('Landing page', $brief['primary_bottleneck']);
        $joined = implode(' ', $brief['next_actions']);
        $this->assertStringContainsString('The issue is the landing page', $brief['issue']);
        $this->assertStringContainsString('$267.03 has been spent and there are still 0 leads. That is enough to judge.', $brief['issue']);
        $history = CampaignPerformanceBrief::historyReason($brief);
        $this->assertStringContainsString('Issue: The issue is the landing page', $history);
        $this->assertStringContainsString('What to do:', $history);
        $this->assertStringContainsString('Make the first screen ask for the leads', $history);
        $this->assertStringContainsString('267.03', implode(' ', $brief['insights']));
        $this->assertStringContainsString('https://lucos.com/landing', $joined);
        $this->assertStringContainsString('Pause the campaign', $joined);
        $this->assertStringContainsString('The ad says', $joined);
        $this->assertStringNotContainsString('Set the first heading', $joined);
        $this->assertStringContainsString('turn the campaign back on', $joined);
        $this->assertStringNotContainsString('Still learning', $brief['scaling_stance']);
        $insightText = strtolower(implode(' ', $brief['insights']));
        $this->assertStringContainsString('health: underperforming', $insightText);
        $this->assertStringContainsString('performance: poor', $insightText);
    }

    public function test_healthy_ctr_and_high_cpc_is_auction_cost_not_a_bad_ad(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 2.5,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $this->assertSame('Auction cost', $brief['primary_bottleneck']);
        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('internal target', $joined);
        $this->assertStringContainsString('breakdown', $joined);
        $this->assertStringContainsString('placement', $joined);
        $this->assertStringContainsString('advantage+ audience', $joined);
        $this->assertStringNotContainsString('bring cpc under', $joined);
        $this->assertStringNotContainsString('change the page', $joined);
        $this->assertContains('trim_expensive_placement', $brief['allowed_moves']);
        $this->assertContains('widen_audience', $brief['allowed_moves']);
        $this->assertStringContainsString('underperforming', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringContainsString('Performance: Poor', implode(' ', $brief['insights']));
        $this->assertStringContainsString('click price', strtolower($brief['issue']));
    }

    public function test_a_sales_campaign_is_reviewed_on_the_objective_not_the_cpc_ceiling(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'campaign_profile' => [
                'name' => 'Lucos-Compare-Image-20260907',
                'objective' => 'OUTCOME_SALES',
            ],
            'windows' => [
                '7d' => [
                    'spend' => 97.45,
                    'impressions' => 1398,
                    'clicks' => 29,
                    'link_clicks' => 29,
                    'outbound_clicks' => 29,
                    'ctr' => 0.0207,
                    'cpc' => 3.36,
                    'conversions' => 1,
                ],
                'outcome_7d' => [
                    'platform_spend' => 97.45,
                    'orders' => 0,
                    'subscriptions' => 0,
                    'leads' => 0,
                    'installs' => 0,
                    'revenue' => 0,
                    'roas' => 0,
                ],
            ],
            'affiliate' => ['matched' => true],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $insights = strtolower(implode(' ', $brief['insights']));
        $actions = strtolower(implode(' ', $brief['next_actions']));

        $this->assertSame('Tracking', $brief['primary_bottleneck']);
        $this->assertStringContainsString('tracking', strtolower($brief['issue']));
        $this->assertStringNotContainsString('click price', strtolower($brief['issue']));
        $this->assertStringContainsString('primary metric is cost per result and roas, not cpc', $insights);
        $this->assertStringContainsString('clicks are landing', $insights);
        $this->assertStringContainsString('auction cost, not the', $insights);
        $this->assertStringContainsString('meta reports', $actions);
        $this->assertStringContainsString('placement', $actions);
        $this->assertStringNotContainsString('bring cpc under', $actions);
        $this->assertStringContainsString('Performance: Inconclusive', implode(' ', $brief['insights']));
    }

    public function test_campaign_review_is_the_treated_data_the_model_writes_from(): void
    {
        $snapshot = [
            'verdict' => 'watch',
            'campaign_profile' => [
                'name' => 'Lucos-Compare-Image-20260907',
                'objective' => 'OUTCOME_SALES',
            ],
            'windows' => [
                '7d' => [
                    'spend' => 97.45,
                    'impressions' => 1398,
                    'clicks' => 29,
                    'link_clicks' => 29,
                    'outbound_clicks' => 29,
                    'ctr' => 0.0207,
                    'cpc' => 3.36,
                    'conversions' => 1,
                ],
                'outcome_7d' => [
                    'platform_spend' => 97.45,
                    'orders' => 0,
                    'revenue' => 0,
                    'roas' => 0,
                ],
            ],
            'affiliate' => ['matched' => true],
            'marketing_diagnosis' => [
                'primary_lever' => 'fix_landing_page',
                'plan' => ['Fix the landing page.'],
            ],
        ];

        $review = CampaignPerformanceBrief::campaignReview($snapshot, 'watch');

        $this->assertSame('tracking', $review['bottleneck']);
        $this->assertSame('hold', $review['lever']);
        $this->assertSame('cost per result and ROAS', $review['primary_metric']);
        $this->assertArrayHasKey('tracking', $review['levels']);
        $this->assertArrayHasKey('traffic', $review['levels']);
        $this->assertArrayHasKey('funnel', $review['levels']);
        $this->assertArrayHasKey('economics', $review['levels']);
        $this->assertArrayHasKey('stability', $review['levels']);
        $this->assertNotEmpty($review['plan']);
        $this->assertLessThanOrEqual(3, count($review['plan']));
        $this->assertStringContainsString('tracking', strtolower(implode(' ', $review['plan'])));

        $aligned = CampaignPerformanceBrief::alignMarketingDiagnosis(
            ['primary_lever' => 'fix_landing_page', 'plan' => ['Fix the landing page.']],
            $review,
        );

        $this->assertSame('hold', $aligned['primary_lever']);
        $this->assertSame($review['plan'], $aligned['plan']);
        $this->assertStringNotContainsString('Fix the landing page.', $aligned['summary']);
    }

    public function test_a_weak_ad_still_maps_the_treated_campaign_to_the_creative_lever(): void
    {
        $review = CampaignPerformanceBrief::campaignReview([
            'verdict' => 'learning',
            'windows' => [
                '7d' => [
                    'spend' => 40,
                    'impressions' => 2000,
                    'clicks' => 0,
                    'ctr' => 0,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'improve_creative'],
        ], 'learning');

        $this->assertSame('creative', $review['bottleneck']);
        $this->assertSame('improve_creative', $review['lever']);
    }

    public function test_auction_next_action_names_the_costliest_placement_on_file(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 2.5,
                    'conversions' => 0,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'breakdowns' => [
                        'placements' => [
                            ['label' => 'Instagram Reels', 'spend' => 62, 'cpc' => 4.10, 'conversions' => 0],
                            ['label' => 'Facebook Feed', 'spend' => 18, 'cpc' => 1.10, 'conversions' => 2],
                        ],
                    ],
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('instagram reels', $joined);
        $this->assertStringContainsString('$62.00', $joined);
        $this->assertStringContainsString('turn off', $joined);
        $this->assertStringNotContainsString('github', $joined);
        $this->assertStringNotContainsString('bring cpc under', $joined);
        $this->assertStringNotContainsString('facebook feed', $joined);
    }

    public function test_auction_does_not_name_a_placement_cheaper_than_the_cpc_target(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 3.36,
                    'conversions' => 0,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'breakdowns' => [
                        'placements' => [
                            ['label' => 'Facebook Reels', 'spend' => 4.98, 'cpc' => 1.66, 'conversions' => 0],
                        ],
                    ],
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringNotContainsString('facebook reels', $joined);
        $this->assertStringContainsString('breakdown', $joined);
        $this->assertStringContainsString('highest cpc', $joined);
    }

    public function test_retargeting_high_cpc_does_not_chase_the_internal_target(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'campaign_profile' => ['name' => 'Lucos Retargeting LP Visitors'],
            'windows' => [
                '7d' => [
                    'spend' => 134.4,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 3.36,
                    'conversions' => 1,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'audience' => ['type' => 'custom'],
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('do not chase', $joined);
        $this->assertStringContainsString('visitor window', $joined);
        $this->assertStringNotContainsString('bring cpc under', $joined);
        $this->assertStringNotContainsString('advantage+ audience', $joined);
        $this->assertContains('widen_retargeting', $brief['allowed_moves']);
        $this->assertNotContains('trim_expensive_placement', $brief['allowed_moves']);
    }

    public function test_capped_bid_with_high_cpc_starts_with_lowest_cost(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'ctr' => 0.02,
                    'cpc' => 2.5,
                    'conversions' => 0,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'bid' => ['bid_strategy' => 'COST_CAP', 'bid_amount' => 0.41],
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('lowest cost', $joined);
        $this->assertStringContainsString('$0.41', $joined);
        $this->assertStringContainsString('breakdown', $joined);
        $this->assertContains('lowest_cost_bid', $brief['allowed_moves']);
        $this->assertStringNotContainsString('bring cpc under', $joined);
    }

    public function test_low_landing_page_view_rate_is_a_visit_problem(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'windows' => [
                '7d' => [
                    'spend' => 40,
                    'impressions' => 2000,
                    'clicks' => 100,
                    'link_clicks' => 100,
                    'outbound_clicks' => 20,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $this->assertSame('Clicks are not landing', $brief['primary_bottleneck']);
        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('landing-page views', $joined);
        $this->assertStringContainsString('redirects', $joined);
        $this->assertStringContainsString('Performance: Needs attention', implode(' ', $brief['insights']));
    }

    public function test_landing_page_views_are_not_treated_as_one_hundred_percent_of_link_clicks(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'windows' => [
                '7d' => [
                    'spend' => 80,
                    'impressions' => 4000,
                    'clicks' => 83,
                    'link_clicks' => 83,
                    'outbound_clicks' => 83,
                    'conversions' => 0,
                ],
            ],
            'performance_strategy' => [
                'delivery' => ['landing_page_views' => 9],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $joined = strtolower(implode(' ', $brief['insights']).' '.implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('lpv rate 11%', $joined);
        $this->assertStringNotContainsString('lpv rate 100%', $joined);
        $this->assertSame('Clicks are not landing', $brief['primary_bottleneck']);
    }

    public function test_next_actions_wait_when_later_landing_screens_were_not_read(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'windows' => [
                '7d' => [
                    'spend' => 80,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'link_clicks' => 40,
                    'conversions' => 0,
                ],
            ],
            'creative_context' => [
                'landing_url' => 'https://search.com/onboarding',
                'landing_page' => [
                    'title' => 'Search',
                    'headings' => ['Get answers'],
                    'text' => 'Continue with Google to start.',
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $joined = implode(' ', $brief['next_actions']);
        $this->assertStringContainsString('later screens', strtolower($joined));
        $this->assertStringContainsString('What to do next', $joined);
    }

    public function test_platform_conversions_above_internal_results_point_at_tracking(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'windows' => [
                '7d' => [
                    'spend' => 90,
                    'impressions' => 4000,
                    'clicks' => 80,
                    'ctr' => 0.02,
                    'cpc' => 1.1,
                    'conversions' => 4,
                ],
                'outcome_7d' => [
                    'platform_spend' => 90,
                    'orders' => 0,
                    'subscriptions' => 0,
                    'leads' => 0,
                    'installs' => 0,
                    'revenue' => 0,
                    'roas' => 0,
                ],
            ],
            'affiliate' => ['matched' => true],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $this->assertSame('Tracking', $brief['primary_bottleneck']);
        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringContainsString('tracking', $joined);
        $this->assertStringContainsString('meta reports', $joined);
        $this->assertStringNotContainsString('change the page', $joined);
        $this->assertStringContainsString('not trustworthy', strtolower($brief['scaling_stance']));
        $this->assertStringContainsString('our own records for this period are still at zero', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringNotContainsString('lag window', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringContainsString('Performance: Inconclusive', implode(' ', $brief['insights']));
    }

    public function test_a_meta_objective_on_the_row_replaces_a_missing_profile_objective(): void
    {
        $brief = CampaignPerformanceBrief::forDisplay([
            'status' => 'learning',
            'objective' => 'OUTCOME_LEADS',
        ], [
            'verdict' => 'learning',
            'campaign_profile' => ['name' => 'Lucos'],
            'windows' => [
                '30d' => [
                    'spend' => 267.03,
                    'impressions' => 3045,
                    'clicks' => 136,
                    'ctr' => 0.0447,
                    'cpc' => 1.96,
                    'conversions' => 0,
                ],
            ],
            'creative_context' => [
                'ads' => [['headline' => 'One Wrong File Change']],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ]);

        $this->assertSame('Leads', $brief['objective']);
        $text = strtolower(implode(' ', [...$brief['insights'], ...$brief['next_actions']]));
        $this->assertStringContainsString('leads', $text);
        $this->assertStringNotContainsString('marketing objective is not set', $text);
    }

    public function test_traffic_objective_is_not_scored_as_zero_purchases(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_TRAFFIC'],
            'windows' => [
                '30d' => [
                    'spend' => 216.91,
                    'impressions' => 38000,
                    'clicks' => 829,
                    'ctr' => 0.0218,
                    'cpc' => 0.26,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $this->assertSame('Traffic', $brief['objective']);
        $this->assertSame('Traffic delivery', $brief['primary_bottleneck']);
        $text = strtolower(implode(' ', [...$brief['insights'], ...$brief['next_actions']]));
        $this->assertStringContainsString('traffic', $text);
        $this->assertStringContainsString('landing-page views', $text);
        $this->assertStringContainsString('do not pause or rewrite the page yet', $text);
        $this->assertStringContainsString('829 clicks', $text);
        $this->assertStringContainsString('check landing page views', $text);
        $this->assertStringContainsString('fix the link or the redirect', $text);
        $this->assertStringNotContainsString('page is the break', $text);
        $this->assertStringNotContainsString('score this campaign', $text);
        $this->assertStringContainsString('performance: inconclusive', $text);
    }

    public function test_a_traffic_campaign_with_landing_views_is_not_told_to_rewrite_the_page(): void
    {
        $snapshot = [
            'verdict' => 'learning',
            'campaign_profile' => ['name' => 'Lucos'],
            'windows' => [
                '30d' => [
                    'spend' => 198.92,
                    'impressions' => 38000,
                    'clicks' => 764,
                    'link_clicks' => 764,
                    'outbound_clicks' => 764,
                    'ctr' => 0.0215,
                    'cpc' => 0.26,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ];
        $stored = CampaignPerformanceBrief::fromSnapshot($snapshot, 'learning');
        $snapshot['brief'] = $stored;

        $brief = CampaignPerformanceBrief::forDisplay([
            'status' => 'learning',
            'objective' => 'OUTCOME_TRAFFIC',
        ], $snapshot);

        $this->assertSame('Traffic', $brief['objective']);
        $this->assertSame('Visits are landing', $brief['primary_bottleneck']);
        $text = strtolower(implode(' ', [...$brief['insights'], $brief['issue'], ...$brief['next_actions']]));
        $this->assertStringContainsString('buying visits', $text);
        $this->assertStringContainsString('764 clicks opened 764 landing-page views', $text);
        $this->assertStringContainsString('not on purchases', $text);
        $this->assertStringNotContainsString('objective is not set', $text);
        $this->assertStringContainsString('do not rewrite the page', $text);
        $this->assertStringNotContainsString('pause the campaign', $text);
        $this->assertStringNotContainsString('set the first heading', $text);
        $this->assertStringContainsString('764 landing-page views', implode(' ', $brief['insights']));
    }

    public function test_a_creative_change_hands_the_live_ad_to_a_designer(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => ['spend' => 40, 'impressions' => 8000, 'clicks' => 20, 'ctr' => 0.0025, 'cpc' => 2, 'conversions' => 0],
            ],
            'creative_context' => [
                'ads' => [[
                    'headline' => 'Ship code faster',
                    'headlines' => ['Ship code faster', 'Stop debugging alone'],
                    'primary_text' => 'Lucos reviews every step before it touches your code.',
                    'cta' => 'LEARN_MORE',
                    'image_url' => 'https://cdn.example.com/lucos-control.png',
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'improve_creative'],
        ], 'learning');

        $joined = implode(' ', $brief['next_actions']);
        $this->assertStringContainsString('Image prompt (text only)', $joined);
        $this->assertStringContainsString('Exact on-image line: “Ship code faster”', $joined);
        $this->assertStringContainsString('Stop debugging alone', $joined);
        $this->assertStringContainsString('Lucos reviews every step', $joined);
        $this->assertStringContainsString('https://cdn.example.com/lucos-control.png', $joined);
        $this->assertStringContainsString('The studio makes the still', $joined);
        $this->assertStringContainsString('does not generate it', $joined);
        $this->assertStringContainsString('Performance: Needs attention', implode(' ', $brief['insights']));
    }

    public function test_a_page_change_quotes_the_lander_on_file_and_does_not_invent_one(): void
    {
        $withPage = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'windows' => [
                '7d' => ['spend' => 80, 'impressions' => 2000, 'clicks' => 40, 'ctr' => 0.02, 'cpc' => 2, 'conversions' => 0],
            ],
            'creative_context' => [
                'landing_url' => 'https://example.com/offer',
                'landing_page' => [
                    'title' => 'Lucos',
                    'headings' => ['Approve the change', 'See the plan'],
                    'text' => 'Review every step before the code changes.',
                ],
                'ads' => [[
                    'headline' => 'One wrong file change',
                    'cta' => 'SEE_DETAILS',
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $quoted = implode(' ', $withPage['next_actions']);
        $this->assertStringContainsString('The first line is “Approve the change”.', $quoted);
        $this->assertStringContainsString('Then the page asks “See the plan”.', $quoted);
        $this->assertStringContainsString('the first line states “One wrong file change”', $quoted);
        $this->assertStringContainsString('before “See the plan”', $quoted);
        $this->assertStringNotContainsString('See details', $quoted);
        $this->assertStringNotContainsString('not on file', $quoted);

        $missing = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'windows' => [
                '7d' => ['spend' => 80, 'impressions' => 2000, 'clicks' => 40, 'ctr' => 0.02, 'cpc' => 2, 'conversions' => 0],
            ],
            'creative_context' => [
                'landing_url' => 'https://lucos.com/landing',
                'landing_page' => ['title' => null, 'headings' => [], 'text' => null],
                'ads' => [[
                    'headline' => 'One wrong file change',
                    'primary_text' => 'You approve the change.',
                    'cta' => 'SEE_DETAILS',
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $held = implode(' ', $missing['next_actions']);
        $this->assertStringContainsString('https://lucos.com/landing', $held);
        $this->assertStringContainsString('The ad says “One wrong file change”.', $held);
        $this->assertStringContainsString('Make the first screen ask for the results', $held);
        $this->assertStringNotContainsString('not saved', $held);
        $this->assertStringNotContainsString('Set the first heading', $held);
        $this->assertStringNotContainsString('You approve the change.', $held);
        $this->assertStringNotContainsString('Fix the landing page.', $held);
    }

    public function test_model_steps_that_ask_for_an_ai_image_are_rejected(): void
    {
        $snapshot = [
            'verdict' => 'learning',
            'windows' => [
                '7d' => ['spend' => 40, 'impressions' => 800, 'clicks' => 0, 'conversions' => 0],
            ],
            'creative_context' => [
                'ads' => [['headline' => 'Ship code faster']],
            ],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'learning');

        $rejected = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Generate an image of a developer at a laptop for this 800 impression ad.',
            'Ship code faster should be the headline on the AI image.',
        ], $snapshot);

        $this->assertSame($brief['next_actions'], $rejected['next_actions']);
        $this->assertStringContainsString('Image prompt (text only)', implode(' ', $rejected['next_actions']));

        $vague = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Ask the page owner for a clearer offer on this 800 impression ad.',
            'The page body is not on file for Ship code faster.',
        ], $snapshot);
        $this->assertSame($brief['next_actions'], $vague['next_actions']);

        $traffic = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_TRAFFIC', 'daily_budget' => 8],
            'daily_budget' => 8,
            'windows' => [
                '30d' => [
                    'spend' => 198.92,
                    'impressions' => 38000,
                    'clicks' => 753,
                    'link_clicks' => 753,
                    'outbound_clicks' => 753,
                    'ctr' => 0.0215,
                    'cpc' => 0.26,
                    'conversions' => 0,
                ],
            ],
            'creative_context' => [
                'landing_url' => 'https://lucos.com/landing?utm_source=meta&utm_campaign={{campaign.id}}',
                'ads' => [[
                    'headline' => 'Transform Thoughts to Code',
                    'primary_text' => 'Write code as fast as you think',
                    'cta' => 'LEARN_MORE',
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');
        $overruled = CampaignPerformanceBrief::applyModelSteps($traffic, [
            'Keep the $8.00 daily budget unchanged: 0% change while learning.',
            'On https://lucos.com/landing?utm_source=meta&utm_campaign={{campaign.id}}, set the first-screen heading to “Transform Thoughts to Code,” supporting text to “Write code as fast as you think,” and button to LEARN_MORE.',
        ], [
            'daily_budget' => 8,
            'windows' => ['30d' => ['spend' => 198.92, 'clicks' => 753, 'impressions' => 38000]],
            'creative_context' => [
                'landing_url' => 'https://lucos.com/landing?utm_source=meta&utm_campaign={{campaign.id}}',
                'ads' => [[
                    'headline' => 'Transform Thoughts to Code',
                    'primary_text' => 'Write code as fast as you think',
                    'cta' => 'LEARN_MORE',
                ]],
            ],
        ]);
        $this->assertSame($traffic['next_actions'], $overruled['next_actions']);
        $this->assertStringContainsString('do not rewrite the page', strtolower(implode(' ', $overruled['next_actions'])));

        $creative = CampaignPerformanceBrief::applyModelSteps($traffic, [
            'Draft a creative test for the 753 clicks on Transform Thoughts to Code.',
            'Leave the budget as it is for this 198.92 spend.',
        ], [
            'daily_budget' => 8,
            'windows' => ['30d' => ['spend' => 198.92, 'clicks' => 753, 'impressions' => 38000]],
            'creative_context' => [
                'ads' => [['headline' => 'Transform Thoughts to Code']],
            ],
        ]);
        $this->assertSame($traffic['next_actions'], $creative['next_actions']);
    }

    public function test_a_zero_inside_the_reporting_lag_is_not_a_page_failure(): void
    {
        $this->travelTo('2026-10-21 12:00:00');

        $open = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'windows' => [
                '7d' => [
                    'spend' => 80,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'conversions' => 0,
                    'from' => '2026-10-15 00:00:00',
                    'to' => '2026-10-21 00:00:00',
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $this->assertSame('Count not in yet', $open['primary_bottleneck']);
        $openText = strtolower(implode(' ', [$open['issue'], ...$open['next_actions'], $open['window_label']]));
        $this->assertStringContainsString('internal count is not in yet', $openText);
        $this->assertStringContainsString('2026-10-15', $openText);
        $this->assertStringContainsString('2026-10-21', $openText);
        $this->assertStringNotContainsString('pause the campaign', $openText);
        $this->assertStringNotContainsString('set the first heading', $openText);

        $closed = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'windows' => [
                '7d' => [
                    'spend' => 80,
                    'impressions' => 2000,
                    'clicks' => 40,
                    'conversions' => 0,
                    'to' => '2026-10-01 00:00:00',
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $this->assertSame('Landing page', $closed['primary_bottleneck']);
        $this->assertStringContainsString('pause the campaign', strtolower(implode(' ', $closed['next_actions'])));
    }

    public function test_brand_awareness_quotes_the_saved_audience_when_clicks_got_cheaper(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => [
                'name' => 'Lucos-Brand Awareness-20260831',
                'objective' => 'OUTCOME_TRAFFIC',
            ],
            'windows' => [
                '7d' => [
                    'spend' => 22,
                    'impressions' => 8000,
                    'clicks' => 100,
                    'link_clicks' => 100,
                    'outbound_clicks' => 100,
                    'conversions' => 0,
                ],
                '14d' => [
                    'spend' => 58,
                    'impressions' => 16000,
                    'clicks' => 200,
                    'conversions' => 0,
                ],
            ],
            'audience' => [
                'countries' => ['US'],
                'age_min' => 18,
                'age_max' => 65,
                'interests' => ['Node.js', 'GitHub'],
                'job_titles' => ['PHP Programmer', 'Java Developer'],
                'advantage_audience' => true,
                'custom_audience' => false,
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'learning');

        $this->assertSame('Named audience', $brief['primary_bottleneck']);
        $text = implode(' ', [$brief['issue'], ...$brief['next_actions']]);
        $this->assertStringContainsString('Delivery is healthy', $text);
        $this->assertStringContainsString('Nothing to change', $text);
        $this->assertStringContainsString('Delivery got cheaper', $text);
        $this->assertStringContainsString('$0.22', $text);
        $this->assertStringContainsString('$0.36', $text);
        $this->assertStringContainsString('not a higher chance of a subscription', $text);
        $this->assertStringNotContainsString('separate retargeting campaign', $text);
        $this->assertStringNotContainsString('Keep this audience', $text);

        $invented = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Target startup founders because the subscription chance is high on this $22.00 week.',
            'Keep Node.js in the audience for these 100 clicks.',
        ], [
            'windows' => ['7d' => ['spend' => 22, 'clicks' => 100, 'impressions' => 8000]],
            'audience' => ['interests' => ['Node.js'], 'job_titles' => ['PHP Programmer']],
        ]);
        $this->assertSame($brief['next_actions'], $invented['next_actions']);

        $written = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Delivery is healthy on these 100 clicks at $22.00. Nothing to change.',
            'Node.js is already the saved audience. Do not name a new audience.',
        ], [
            'windows' => ['7d' => ['spend' => 22, 'clicks' => 100, 'impressions' => 8000]],
            'audience' => ['interests' => ['Node.js'], 'job_titles' => ['PHP Programmer']],
        ]);
        $this->assertSame('llm', $written['next_actions_source']);
        $this->assertStringContainsString('Nothing to change', $written['next_actions'][0]);
        $this->assertStringContainsString('Node.js', $written['next_actions'][1]);

        $longAudience = 'Keep Node.js, GitHub, Web development (websites), Software development (software), and Python (programming language) for these 100 clicks. Job titles stay IT Engineer, PHP Programmer, PHP Website Developer, and Software Development Engineer. Do not name a new audience for this list.';
        $this->assertGreaterThan(280, mb_strlen($longAudience));
        $kept = CampaignPerformanceBrief::applyModelSteps($brief, [
            $longAudience,
            'Leave the $22.00 spend on these 100 clicks. Nothing to change.',
            str_repeat('This line is too long to keep. ', 30),
        ], [
            'windows' => ['7d' => ['spend' => 22, 'clicks' => 100, 'impressions' => 8000]],
            'audience' => ['interests' => ['Node.js', 'GitHub'], 'job_titles' => ['PHP Programmer']],
        ]);
        $this->assertSame('llm', $kept['next_actions_source']);
        $this->assertCount(2, $kept['next_actions']);
        $this->assertStringContainsString('Web development (websites)', $kept['next_actions'][0]);

        $flat = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'learning',
            'campaign_profile' => [
                'name' => 'Lucos-Brand Awareness-20260831',
                'objective' => 'OUTCOME_TRAFFIC',
            ],
            'windows' => [
                '7d' => [
                    'spend' => 30,
                    'impressions' => 8000,
                    'clicks' => 100,
                    'link_clicks' => 100,
                    'outbound_clicks' => 100,
                    'conversions' => 0,
                ],
                '14d' => [
                    'spend' => 60,
                    'impressions' => 16000,
                    'clicks' => 200,
                    'conversions' => 0,
                ],
            ],
            'audience' => [
                'countries' => ['US'],
                'age_min' => 18,
                'age_max' => 65,
                'interests' => ['Node.js'],
                'job_titles' => [],
                'advantage_audience' => false,
                'custom_audience' => false,
            ],
        ], 'learning');

        $flatText = implode(' ', $flat['next_actions']);
        $this->assertStringNotContainsString('Delivery got cheaper', $flatText);
        $this->assertStringContainsString('Nothing to change', $flatText);
        $this->assertStringNotContainsString('Node.js', $flatText);
    }

    public function test_sales_inside_the_cost_lines_are_healthy(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'scale_up',
            'campaign_profile' => ['objective' => 'OUTCOME_SALES'],
            'windows' => [
                '7d' => [
                    'spend' => 100,
                    'impressions' => 5000,
                    'clicks' => 80,
                    'ctr' => 0.016,
                    'cpc' => 1.25,
                    'conversions' => 10,
                ],
                'outcome_7d' => [
                    'platform_spend' => 100,
                    'orders' => 10,
                    'revenue' => 250,
                    'roas' => 2.5,
                    'cpa' => 10,
                ],
            ],
            'affiliate' => ['matched' => true],
            'marketing_diagnosis' => ['primary_lever' => 'spend_more'],
        ], 'scale_up');

        $insights = implode(' ', $brief['insights']);
        $this->assertStringContainsString('Healthy', $insights);
        $this->assertStringContainsString('Performance: Good', $insights);
        $this->assertStringContainsString('at a cost this budget can afford', $insights);
        $this->assertStringContainsString('ROAS 2.50x', $insights);
        $this->assertStringContainsString('CPA $10.00', $insights);
    }

    public function test_landed_leads_with_an_expensive_click_are_a_page_problem(): void
    {
        $this->travelTo('2026-10-21');
        $snapshot = [
            'verdict' => 'pause',
            'campaign_profile' => [
                'name' => 'Search_Newflow_Lead_Video_ABO-20260908',
                'objective' => 'OUTCOME_LEADS',
            ],
            'windows' => [
                '30d' => [
                    'spend' => 309.96,
                    'impressions' => 4007,
                    'clicks' => 121,
                    'link_clicks' => 96,
                    'outbound_clicks' => 96,
                    'conversions' => 0,
                    'to' => '2026-10-21',
                ],
            ],
            'creative_context' => [
                'landing_url' => 'https://search.com/onboarding/landing',
                'ads' => [[
                    'headline' => 'A Faster, Cleaner Way to Search',
                    'primary_text' => 'Same web results, better perks.',
                    'cta' => 'LEARN_MORE',
                ]],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'pause');

        $this->assertSame('Landing page', $brief['primary_bottleneck']);
        $this->assertContains('fix_first_screen', $brief['allowed_moves']);
        $this->assertNotContains('new_heading', $brief['allowed_moves']);
        $text = implode(' ', [$brief['issue'], ...$brief['next_actions']]);
        $this->assertStringContainsString('A Faster, Cleaner Way to Search', $text);
        $this->assertStringContainsString('96 landing-page views', $text);
        $this->assertStringContainsString('0 leads', $text);
        $this->assertStringContainsString('Make the first screen ask for the leads', $text);
        $this->assertStringNotContainsString('not saved', $text);
        $this->assertStringContainsString('Pause the campaign', $text);
        $this->assertStringNotContainsString('Set the first heading', $text);
        $this->assertStringNotContainsString('page is not the problem', strtolower($text));
        $this->assertStringNotContainsString('show up again', $text);

        $copied = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Set the first heading to “A Faster, Cleaner Way to Search” on https://search.com/onboarding/landing.',
            'These 96 landing-page views produced 0 leads on $309.96 spend.',
        ], $snapshot);
        $this->assertSame($brief['next_actions'], $copied['next_actions']);

        $snapshot['creative_context']['landing_page'] = [
            'title' => 'Sign in — Search.com',
            'headings' => ['Get answers, not links. Search smarter today.', 'Enter your code'],
            'text' => 'Continue with Google. Continue with Apple. Email address.',
        ];
        $saved = CampaignPerformanceBrief::fromSnapshot($snapshot, 'pause');
        $pageText = implode(' ', $saved['next_actions']);
        $this->assertStringContainsString('The page title is “Sign in — Search.com”.', $pageText);
        $this->assertStringContainsString('The first line is “Get answers, not links. Search smarter today”.', $pageText);
        $this->assertStringContainsString('Then the page asks “Enter your code”.', $pageText);
        $this->assertStringContainsString('before “Enter your code”', $pageText);
        $this->assertStringNotContainsString('Learn more', $pageText);
        $this->assertStringNotContainsString('not saved', $pageText);

        $written = CampaignPerformanceBrief::applyModelSteps($saved, [
            'Pause the campaign. 96 landing-page views and $309.96 produced 0 leads.',
            'The first line is “Get answers, not links. Search smarter today.” Then the page asks “Enter your code”. Change the first screen so the first line states “A Faster, Cleaner Way to Search” before that code step.',
        ], $snapshot);
        $this->assertSame('llm', $written['next_actions_source']);
    }

    public function test_proposed_changes_become_the_numbered_next_steps_and_the_model_cannot_replace_them(): void
    {
        $snapshot = [
            'verdict' => 'watch',
            'windows' => [
                '7d' => ['spend' => 80, 'impressions' => 2000, 'clicks' => 40, 'conversions' => 1],
            ],
            'performance_strategy' => [
                'broken_step' => 'volume',
                'delivery_state' => 'active',
                'proposed_changes' => [
                    ['action' => 'watch_ad', 'ad_id' => '1', 'text' => 'Watch Lucos retargeting (1).'],
                    ['action' => 'wait_ad', 'ad_id' => '2', 'text' => 'Do not judge Lucos still (2) yet (too early).'],
                ],
            ],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'watch');

        $joined = implode(' ', $brief['next_actions']);
        $this->assertStringContainsString('Watch Lucos retargeting (1).', $joined);
        $this->assertStringContainsString('Do not judge Lucos still (2) yet (too early).', $joined);
        $this->assertStringContainsString('Watch this campaign; do not pause it.', $joined);
        $this->assertStringNotContainsString('Pause the campaign', $joined);
        $this->assertNotContains('pause', $brief['allowed_moves']);

        $overruled = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Pause the campaign. $80.00 spend is not converting.',
            'Replace Lucos retargeting (1) with a new still.',
        ], $snapshot);

        $this->assertSame($brief['next_actions'], $overruled['next_actions']);
        $this->assertArrayNotHasKey('next_actions_source', $overruled);
    }

    public function test_watch_does_not_tell_the_buyer_to_pause_the_campaign(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'campaign_profile' => ['objective' => 'OUTCOME_LEADS'],
            'creative_context' => [
                'ads' => [['headline' => 'One Wrong File Change Can Cost You 20 Minutes']],
                'landing_url' => 'https://lucos.com/landing',
            ],
            'windows' => [
                '30d' => [
                    'spend' => 267.03,
                    'impressions' => 3045,
                    'clicks' => 136,
                    'ctr' => 0.0447,
                    'cpc' => 1.96,
                    'conversions' => 0,
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'fix_landing_page'],
        ], 'watch');

        $joined = strtolower(implode(' ', $brief['next_actions']));
        $this->assertStringNotContainsString('pause the campaign', $joined);
        $this->assertStringContainsString('hold the budget', $joined);
        $this->assertNotContains('pause', $brief['allowed_moves']);

        $rejected = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Pause the campaign. $267.03 spend produced 0 leads.',
            'Rewrite the first screen on https://lucos.com/landing.',
        ], [
            'verdict' => 'watch',
            'windows' => ['30d' => ['spend' => 267.03, 'clicks' => 136, 'impressions' => 3045, 'conversions' => 0]],
            'creative_context' => ['landing_url' => 'https://lucos.com/landing'],
        ]);
        $this->assertSame($brief['next_actions'], $rejected['next_actions']);
    }

    public function test_broken_delivery_does_not_say_the_run_is_healthy(): void
    {
        $snapshot = [
            'verdict' => 'learning',
            'campaign_profile' => [
                'name' => 'Attestpath-Brand Awareness',
                'objective' => 'OUTCOME_TRAFFIC',
            ],
            'windows' => [
                '7d' => [
                    'spend' => 22,
                    'impressions' => 8000,
                    'clicks' => 100,
                    'link_clicks' => 100,
                    'outbound_clicks' => 100,
                    'conversions' => 0,
                ],
                '14d' => [
                    'spend' => 58,
                    'impressions' => 16000,
                    'clicks' => 200,
                    'conversions' => 0,
                ],
            ],
            'audience' => [
                'countries' => ['US'],
                'age_min' => 18,
                'age_max' => 65,
                'interests' => ['Node.js', 'GitHub'],
                'job_titles' => ['PHP Programmer'],
                'advantage_audience' => true,
                'custom_audience' => false,
            ],
            'performance_strategy' => [
                'broken_step' => 'delivery',
                'delivery_state' => 'not_delivering',
                'objective_kind' => 'awareness',
            ],
            'marketing_diagnosis' => ['primary_lever' => 'hold'],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'learning');
        $review = CampaignPerformanceBrief::campaignReview($snapshot, 'learning');

        $this->assertSame('Delivery', $brief['primary_bottleneck']);
        $this->assertStringContainsString('The issue is delivery', $brief['issue']);
        $this->assertStringNotContainsString('healthy', strtolower($brief['issue']));
        $this->assertStringNotContainsString('healthy', strtolower(implode(' ', $brief['next_actions'])));
        $this->assertStringNotContainsString('healthy', strtolower($review['levels']['funnel']));

        $rejected = CampaignPerformanceBrief::applyModelSteps($brief, [
            'Delivery is healthy. Nothing in this window needs a change.',
            'Leave the $22.00 spend as it is on Attestpath-Brand Awareness.',
        ], $snapshot);
        $this->assertSame($brief['next_actions'], $rejected['next_actions']);
    }

    public function test_a_delivery_stop_lists_restart_hold_and_the_roster_ad(): void
    {
        $snapshot = [
            'verdict' => 'watch',
            'campaign_profile' => [
                'name' => 'Attestpath-SOC-2 – Brand Awareness',
                'objective' => 'OUTCOME_TRAFFIC',
                'daily_budget' => 20,
            ],
            'windows' => [
                '7d' => ['spend' => 0, 'impressions' => 0, 'clicks' => 0, 'conversions' => 0],
                '30d' => ['spend' => 74.47, 'impressions' => 15021, 'clicks' => 266, 'conversions' => 0],
            ],
            'performance_strategy' => [
                'broken_step' => 'delivery',
                'delivery_state' => 'not_delivering',
                'objective_kind' => 'traffic',
                'proposed_changes' => [
                    [
                        'action' => 'wait_ad',
                        'ad_id' => '120251606607860626',
                        'text' => 'Do not judge Attestpath-SCO-2 – Copy (120251606607860626) yet (too early).',
                    ],
                ],
            ],
            'marketing_diagnosis' => ['primary_lever' => 'hold'],
        ];
        $brief = CampaignPerformanceBrief::fromSnapshot($snapshot, 'watch');
        $joined = implode(' ', $brief['next_actions']);

        $this->assertGreaterThanOrEqual(3, count($brief['next_actions']));
        $this->assertStringContainsString('Restart delivery', $joined);
        $this->assertStringContainsString('$0.00', $joined);
        $this->assertStringContainsString('$20.00 daily budget', $joined);
        $this->assertStringContainsString('$74.47', $joined);
        $this->assertStringContainsString('266 clicks', $joined);
        $this->assertStringContainsString('Do not rewrite the ad or the landing page', $joined);
        $this->assertStringContainsString('Do not judge Attestpath-SCO-2 – Copy', $joined);
        $this->assertStringNotContainsString('Pause the campaign', $joined);
        $this->assertStringNotContainsString('healthy', strtolower($joined));
    }

    public function test_traffic_insights_do_not_treat_zero_internal_leads_as_a_lag(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'maintain',
            'campaign_profile' => [
                'name' => 'Lucos-Brand Awareness-20260831',
                'objective' => 'OUTCOME_TRAFFIC',
            ],
            'campaign_goals' => [
                'objective' => 'OUTCOME_TRAFFIC',
                'optimization_goals' => ['LANDING_PAGE_VIEWS'],
            ],
            'windows' => [
                '7d' => [
                    'spend' => 16,
                    'impressions' => 1273,
                    'clicks' => 58,
                    'link_clicks' => 58,
                    'outbound_clicks' => 58,
                    'conversions' => 0,
                ],
                'outcome_7d' => [
                    'leads' => 0,
                    'orders' => 0,
                    'subscriptions' => 0,
                    'installs' => 0,
                    'conversions' => 0,
                    'platform_spend' => 25,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'optimization_goal' => 'LANDING_PAGE_VIEWS',
                    'delivery' => ['landing_page_views' => 14, 'spend' => 16, 'clicks' => 58],
                ]],
            ],
        ], 'maintain');

        $joined = strtolower(implode(' ', $brief['insights']));

        $this->assertStringNotContainsString('our own records for this period are still at zero', $joined);
        $this->assertStringNotContainsString('not trustworthy', $joined);
        $this->assertStringNotContainsString('revenue for those visits', $joined);
        $this->assertStringNotContainsString('worth the spend', $joined);
    }

    public function test_traffic_insights_do_not_need_revenue_when_visits_are_landing(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'maintain',
            'campaign_profile' => [
                'name' => 'Lucos-Brand Awareness-20260831',
                'objective' => 'OUTCOME_TRAFFIC',
            ],
            'campaign_goals' => [
                'objective' => 'OUTCOME_TRAFFIC',
                'optimization_goals' => ['LANDING_PAGE_VIEWS'],
            ],
            'windows' => [
                '7d' => [
                    'spend' => 18.06,
                    'impressions' => 1383,
                    'clicks' => 75,
                    'link_clicks' => 67,
                    'outbound_clicks' => 67,
                    'conversions' => 0,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'optimization_goal' => 'LANDING_PAGE_VIEWS',
                    'delivery' => ['landing_page_views' => 65, 'spend' => 18.06, 'clicks' => 75, 'cpm' => 13.06],
                ]],
            ],
        ], 'maintain');

        $joined = strtolower(implode(' ', $brief['insights']));

        $this->assertStringContainsString('landing-page views, not revenue', $joined);
        $this->assertStringContainsString('performance: good', $joined);
        $this->assertStringNotContainsString('revenue for those visits', $joined);
        $this->assertStringNotContainsString('worth the spend', $joined);
    }

    public function test_landing_page_views_are_not_scored_against_a_longer_click_window(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'maintain',
            'campaign_profile' => [
                'name' => 'Lucos-Brand Awareness-20260831',
                'objective' => 'OUTCOME_TRAFFIC',
            ],
            'campaign_goals' => [
                'objective' => 'OUTCOME_TRAFFIC',
                'optimization_goals' => ['LANDING_PAGE_VIEWS'],
            ],
            'windows' => [
                '7d' => [
                    'spend' => 16,
                    'impressions' => 1273,
                    'clicks' => 58,
                    'link_clicks' => 58,
                    'outbound_clicks' => 58,
                    'conversions' => 0,
                ],
                '30d' => [
                    'spend' => 165.57,
                    'impressions' => 20769,
                    'clicks' => 622,
                    'link_clicks' => 622,
                    'outbound_clicks' => 622,
                    'conversions' => 0,
                ],
            ],
            'ad_set_optimization' => [
                'ad_sets' => [[
                    'optimization_goal' => 'LANDING_PAGE_VIEWS',
                    'delivery' => ['landing_page_views' => 14, 'spend' => 16, 'clicks' => 58],
                ]],
            ],
        ], 'maintain');

        $joined = strtolower(implode(' ', $brief['insights']));

        $this->assertStringContainsString('spend $16.00', $joined);
        $this->assertStringContainsString('14 landing-page views', $joined);
        $this->assertStringContainsString('lpv rate 24%', $joined);
        $this->assertStringNotContainsString('lpv rate 2%', $joined);
        $this->assertStringNotContainsString('622 landing-page views', $joined);
    }

    public function test_a_cost_cap_delivery_break_is_not_called_tracking(): void
    {
        $brief = CampaignPerformanceBrief::fromSnapshot([
            'verdict' => 'watch',
            'campaign_profile' => [
                'name' => 'Attestpath -Retargeting- LP Visitors - 30d-20260921',
                'objective' => 'OUTCOME_LEADS',
            ],
            'performance_strategy' => [
                'objective_kind' => 'leads',
                'tracking_mismatch' => false,
                'broken_step' => 'delivery',
                'delivery_state' => 'not_delivering',
                'delivery' => [
                    'bid_strategy' => 'COST_CAP',
                    'bid_amount' => 0.4,
                    'spend_7d' => 0,
                ],
            ],
            'windows' => [
                '7d' => [
                    'spend' => 0,
                    'impressions' => 0,
                    'clicks' => 0,
                    'conversions' => 0,
                ],
                '30d' => [
                    'spend' => 146.2,
                    'impressions' => 2127,
                    'clicks' => 30,
                    'conversions' => 2,
                ],
                'outcome_7d' => [
                    'leads' => 0,
                    'orders' => 0,
                    'subscriptions' => 0,
                    'installs' => 0,
                    'revenue' => 0,
                ],
            ],
            'affiliate' => ['matched' => true],
        ], 'watch');

        $this->assertSame('Delivery', $brief['primary_bottleneck']);
        $this->assertStringContainsString('delivery', strtolower($brief['issue']));
        $this->assertStringNotContainsString('tracking', strtolower($brief['issue']));
        $this->assertStringContainsString('cost cap', strtolower(implode(' ', $brief['insights'])));
        $this->assertStringNotContainsString('not trustworthy', strtolower(implode(' ', $brief['insights'])));
    }
}
