<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\Instructions;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\LaunchFlow;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Platforms\LinkedInRules;
use App\Campaigns\Platforms\MetaRules;
use App\Campaigns\Targeting\TargetingSelections;
use App\DTOs\LandingPageAnalysis;
use App\Models\ArtifactFieldSource;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use App\Services\AI\AudienceInterestPhrases;
use App\Services\Meta\Meta;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Log;
use Laravel\Ai\Ai;
use Laravel\Ai\StructuredAnonymousAgent;
use Laravel\Ai\Tools\Request;
use Mockery;
use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
use Tests\SeedsVerifiedCountries;
use Tests\TestCase;

/**
 * The other two questions a brief was answering once per platform.
 *
 * Countries and bid strategy are both one decision for a brief, and both were
 * being asked again for every platform in it.
 *
 * Countries had the machinery and no data: locations has been in
 * SHARED_WITH_BRIEF since the trait was written and nothing ever wrote it, so
 * the fallback could not fire. Bidding had neither, and needed a mapping of its
 * own, because "bid automatically" is LOWEST_COST_WITHOUT_CAP on Meta,
 * MAXIMIZE_CLICKS on Google and AUTOMATED_BID on LinkedIn.
 */
class TargetingAndBiddingAreAskedOnceTest extends TestCase
{
    use RefreshDatabase;
    use SeedsVerifiedCountries;

    protected Brief $brief;

    protected function setUp(): void
    {
        parent::setUp();

        $this->seedVerifiedCountries();

        $this->actingAs(User::factory()->create());

        app(Workspace::class)->bindTo('conv-shared-steps');

        $this->brief = Brief::create([
            'conversation_id' => 'conv-shared-steps',
            'user_id' => auth()->id(),
        ]);
    }

    private function campaign(string $platform, array $attributes = []): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => auth()->id(),
            'brief_id' => $this->brief->id,
            'name' => ucfirst($platform).' campaign',
            'platform' => $platform,
            'status' => 'draft',
            ...$attributes,
        ]);

        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    private function tool(string $name, array $arguments = []): array
    {
        $result = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === $name)
            ->handle(new Request($arguments));

        return json_decode((string) $result, true);
    }

    private function markDemographicsSelected(Campaign $campaign): void
    {
        app(Workspace::class)->recordSource($campaign, 'audience_demographics', ArtifactFieldSource::USER_STATED);
    }

    // ---------------------------------------------------------------- countries

    /** The defect: the answer never left the campaign that gave it. */
    public function test_countries_reach_the_brief(): void
    {
        $this->campaign('meta');

        $this->tool('campaign__set_targeting', ['countries' => ['US', 'IN'], 'placements' => ['facebook']]);

        $this->assertSame(['US', 'IN'], $this->brief->refresh()->locations['countries'] ?? null);
    }

    public function test_country_selection_immediately_offers_every_supported_geography_option(): void
    {
        $this->campaign('meta');

        $this->tool('campaign__set_targeting', ['countries' => ['US'], 'placements' => ['facebook'], 'devices' => ['mobile', 'desktop']]);

        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'location_scope');
        $this->assertNotNull($choice);
        $this->assertSame(['whole', 'city', 'region', 'dma', 'postal', 'list'], array_column($choice['options'], 'value'));
    }

    /** So the next platform inherits them instead of being asked. */
    public function test_the_next_platform_inherits_the_countries(): void
    {
        $this->campaign('meta');
        $this->tool('campaign__set_targeting', ['countries' => ['US', 'IN'], 'placements' => ['facebook']]);

        $google = $this->campaign('google');

        $this->assertSame(['US', 'IN'], $google->locations['countries'] ?? null);
    }

    /**
     * The brief keeps the first answer.
     *
     * A campaign narrowed to one country afterwards must not redefine where the
     * whole brief runs; it just keeps its own list.
     */
    public function test_a_narrower_campaign_does_not_redefine_the_brief(): void
    {
        $this->campaign('meta');
        $this->tool('campaign__set_targeting', ['countries' => ['US', 'IN'], 'placements' => ['facebook']]);

        $linkedin = $this->campaign('linkedin');
        $this->tool('campaign__set_targeting', ['countries' => ['US'], 'placements' => ['linkedin_feed']]);

        $this->assertSame(['US', 'IN'], $this->brief->refresh()->locations['countries'] ?? null);

        // Asked of the ad set, which is where targeting lives and which has no
        // brief to fall back to, so this is the campaign's own answer rather
        // than the shared one. It used to decode the campaign's raw column for
        // the same reason.
        $this->assertSame(
            ['US'],
            $linkedin->refresh()->primaryAdSet->locations['countries'] ?? null,
        );
    }

    /** Placements are still the platform's own, because they genuinely differ. */
    public function test_placements_are_not_shared(): void
    {
        $this->campaign('meta');
        $this->tool('campaign__set_targeting', ['countries' => ['US'], 'placements' => ['facebook']]);

        $google = $this->campaign('google');

        $this->assertEmpty($google->placements);
    }

    public function test_linkedin_does_not_ask_for_or_store_unsupported_device_targeting(): void
    {
        $campaign = $this->campaign('linkedin');
        $keys = array_column(app(LaunchFlow::class)->progress($campaign->fresh()), 'key');

        $this->assertNotContains('devices', $keys);

        $result = $this->tool('campaign__set_targeting', ['devices' => ['mobile']]);

        $this->assertFalse($result['ok']);
        $this->assertNull($campaign->fresh()->audience['devices'] ?? null);
    }

    public function test_meta_audience_flow_asks_age_and_gender_before_the_audience_type(): void
    {
        $campaign = $this->campaign('meta', [
            'special_ad_categories' => ['NONE'],
        ]);

        $result = $this->tool('campaign__set_targeting', ['section' => 'audience']);

        $this->assertTrue($result['ok']);
        $choices = app(Choices::class)->all();
        $this->assertSame(['meta_age_range', 'meta_gender'], array_column($choices, 'field'));
        $this->assertTrue(Choices::isOneSemanticForm(['meta_age_range', 'meta_gender']));
        $ageChoice = collect($choices)->firstWhere('field', 'meta_age_range');
        $this->assertSame('age_range', $ageChoice['control']['type']);
        $this->assertSame(18, $ageChoice['control']['minimum']);
        $this->assertSame(18, $ageChoice['control']['age_min']);
        $this->assertSame(65, $ageChoice['control']['age_max']);
        $this->assertStringContainsString('minimum and maximum age', $ageChoice['question']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $applied = app(Answers::class)->applyAll([
            ['field' => 'meta_age_range', 'value' => ['age_min' => 25, 'age_max' => 54]],
            ['field' => 'meta_gender', 'value' => 'all'],
        ]);

        $this->assertCount(2, $applied);
        $this->assertTrue($applied[0]['applied'], json_encode($applied));
        $this->assertTrue($applied[1]['applied']);
        $this->assertSame(25, $campaign->fresh()->audience['age_min']);
        $this->assertSame(54, $campaign->fresh()->audience['age_max']);
        $this->assertArrayNotHasKey('genders', $campaign->fresh()->audience);
        $audienceChoices = app(Choices::class)->all();
        $this->assertSame(['meta_audience_mode'], array_column($audienceChoices, 'field'));
        $audienceChoice = $audienceChoices[0];
        $this->assertSame(
            ['suggestions', 'demographics', 'interests', 'behaviors', 'broad', 'retargeting'],
            array_column($audienceChoice['options'], 'value'),
        );
        $this->assertFalse(collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->firstWhere('key', 'audience')['done']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $audienceApplied = app(Answers::class)->applyAll([
            ['field' => 'meta_audience_mode', 'value' => 'broad'],
        ]);

        $this->assertTrue($audienceApplied[0]['applied']);
        $this->assertSame(25, $campaign->fresh()->audience['age_min']);
        $this->assertSame(54, $campaign->fresh()->audience['age_max']);
        $this->assertSame('broad', $campaign->fresh()->audience['meta_audience_mode']);
    }

    public function test_existing_age_bounds_without_a_demographics_answer_still_get_the_first_question(): void
    {
        $this->campaign('meta', [
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 25, 'age_max' => 34, 'genders' => [2]],
        ]);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);

        $this->assertSame(
            ['meta_age_range', 'meta_gender'],
            array_column(app(Choices::class)->all(), 'field'),
        );
    }

    public function test_meta_demographic_choices_are_refused_for_special_ad_categories(): void
    {
        $this->campaign('meta', ['special_ad_categories' => ['HOUSING']]);

        $result = $this->tool('campaign__set_targeting', ['section' => 'demographics']);

        $this->assertFalse($result['ok']);
        $this->assertSame([], app(Choices::class)->all());

        $result = $this->tool('campaign__set_targeting', ['age_min' => 25, 'age_max' => 34]);

        $this->assertFalse($result['ok']);
        $this->assertNull($this->brief->campaigns()->first()->audience['age_min'] ?? null);

        $result = $this->tool('campaign__set_targeting', ['interest_ids' => ['6001']]);

        $this->assertFalse($result['ok']);
    }

    public function test_explicit_null_age_inputs_are_refused_without_changing_saved_demographics(): void
    {
        $campaign = $this->campaign('meta', [
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 25, 'age_max' => 34],
        ]);

        foreach (['age_min', 'age_max'] as $field) {
            $result = $this->tool('campaign__set_targeting', [$field => null]);

            $this->assertFalse($result['ok']);
            $this->assertSame(25, $campaign->fresh()->audience['age_min']);
            $this->assertSame(34, $campaign->fresh()->audience['age_max']);
        }
    }

    public function test_the_meta_audience_step_offers_broad_defaults_and_custom_ideas(): void
    {
        $campaign = $this->campaign('meta', [
            'special_ad_categories' => ['NONE'],
            'audience' => [
                'age_min' => 25,
                'age_max' => 34,
                'genders' => [2],
                'meta_interests' => [['id' => '6001', 'name' => 'Interest']],
            ],
        ]);
        $this->markDemographicsSelected($campaign);

        $result = $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode');

        $this->assertTrue($result['ok']);
        $this->assertSame(
            ['done', 'suggestions', 'demographics', 'interests', 'behaviors', 'broad', 'retargeting', 'remove'],
            array_column($choice['options'], 'value'),
        );
        $this->assertSame('Suggested', collect($choice['options'])->firstWhere('value', 'suggestions')['badge']);
        $this->assertNull(collect($choice['options'])->firstWhere('value', 'broad')['badge'] ?? null);
        $this->assertTrue($choice['allow_other']);
        $this->assertSame('Custom interest ideas', $choice['other_label']);
        $this->assertSame(1, $choice['other_position']);
        $this->assertFalse($choice['other_in_composer']);
        $this->assertSame('e.g. doctors, medical students', $choice['other_placeholder']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $applied = app(Answers::class)->applyAll([['field' => 'meta_audience_mode', 'value' => 'broad']]);

        $this->assertTrue($applied[0]['applied']);
        $audience = $campaign->fresh()->audience;
        $this->assertSame('broad', $audience['meta_audience_mode']);
        $this->assertArrayNotHasKey('meta_interests', $audience);
        $this->assertSame(25, $audience['age_min']);
        $this->assertSame(34, $audience['age_max']);
        $this->assertSame([2], $audience['genders']);
        $audienceProgress = collect(app(LaunchFlow::class)->progress($campaign->fresh()))
            ->firstWhere('key', 'audience');
        $this->assertTrue($audienceProgress['done']);
    }

    public function test_page_interest_matches_are_offered_with_modes_and_saved_in_one_choice(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://stay.example/',
            title: 'Hotel Booking',
            description: 'Book hotels and compare hotel reviews.',
            headings: ['Hotel deals'],
            text: 'Find hotel booking offers and reviews.',
            keywords: ['hotel booking', 'hotel reviews'],
        ));
        $phrases = Mockery::mock(AudienceInterestPhrases::class);
        $phrases->shouldReceive('forPage')->once()->andReturn(['Hotel Booking', 'Hotel Reviews']);
        $this->app->instance(AudienceInterestPhrases::class, $phrases);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'Hotel Booking')->andReturn([
            ['id' => '6001', 'name' => 'Hotel Booking', 'path' => ['Interests', 'Additional interests', 'Hotel Booking']],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'Hotel Reviews')->andReturn([
            ['id' => '6002', 'name' => 'Hotel Reviews', 'path' => ['Interests', 'Additional interests', 'Hotel Reviews']],
        ]);
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001', '6002'])->andReturn([
            ['id' => '6001', 'name' => 'Hotel Booking', 'valid' => true],
            ['id' => '6002', 'name' => 'Hotel Reviews', 'valid' => true],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $choices = app(Choices::class)->all();

        $this->assertSame(['meta_audience_mode'], array_column($choices, 'field'));
        $suggestions = collect($choices[0]['options'])->firstWhere('value', 'suggestions');
        $this->assertSame(['6001', '6002'], $suggestions['arguments']['interest_ids']);
        $this->assertStringContainsString('Hotel Booking', $suggestions['hint']);
        $this->assertStringContainsString('Hotel Reviews', $suggestions['hint']);
        $this->assertStringContainsString('AI-selected interests from this page', $suggestions['hint']);
        $this->assertSame('Hotel Booking, Hotel Reviews', $choices[0]['other_value']);
        $this->assertSame(1, $choices[0]['other_position']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $applied = app(Answers::class)->applyAll([
            ['field' => 'meta_audience_mode', 'value' => 'suggestions'],
        ]);

        $this->assertTrue($applied[0]['applied']);
        $this->assertSame('custom', $campaign->fresh()->audience['meta_audience_mode']);
        $this->assertSame(['6001', '6002'], array_column($campaign->fresh()->audience['meta_interests'], 'id'));
    }

    public function test_stockprices_page_suggestions_skip_title_tagline_and_signup_form_terms(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $phrases = Mockery::mock(AudienceInterestPhrases::class);
        $phrases->shouldReceive('forPage')->once()->andReturn(['stock market', 'stock trading', 'market data']);
        $this->app->instance(AudienceInterestPhrases::class, $phrases);

        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://stockprices.com/landing',
            title: 'Trade Smarter — StockPrices.com',
            description: '',
            headings: ['Stock Analysis Platform'],
            text: 'Stock Analysis Platform Trade Smarter Real-time market data advanced analytics AI-powered insights informed trading decisions successful traders First Name Please provide proper first name Email valid address State Select State Armed Forces Africa California',
            keywords: ['trade', 'smarter', 'stockprices', 'stock', 'analysis', 'platform', 'select', 'armed', 'forces', 'provide', 'proper', 'market', 'traders'],
        ));

        $searchedIdeas = [];
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->times(3)->andReturnUsing(
            function (string $accountId, string $idea) use (&$searchedIdeas): array {
                $searchedIdeas[] = $idea;

                return match ($idea) {
                    'stock market' => [
                        ['id' => '6101', 'name' => 'Stock market'],
                        ['id' => '6199', 'name' => 'Browser games'],
                    ],
                    'stock trading' => [['id' => '6102', 'name' => 'Stock trading']],
                    'market data' => [['id' => '6103', 'name' => 'Financial markets']],
                    default => [],
                };
            },
        );
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);

        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode');
        $suggestions = collect($choice['options'])->firstWhere('value', 'suggestions');
        $this->assertSame(['stock market', 'stock trading', 'market data'], $searchedIdeas);
        $this->assertSame(['6101', '6102', '6103'], $suggestions['arguments']['interest_ids']);
        $this->assertStringNotContainsString('Browser games', $suggestions['hint']);
        $this->assertSame('stock market, stock trading, market data', $choice['other_value']);
    }

    public function test_openai_page_phrases_fill_the_audience_suggestions_and_drop_unrelated_interests(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://iblockads.org/extension/landing',
            title: 'iblockads',
            description: '',
            headings: ['Browse the Web Without Ads & Trackers'],
            text: 'Block ads and trackers while you browse.',
            keywords: ['browse', 'iblockads', 'trackers', 'blocking'],
        ));
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'phrases' => ['ad blocker', 'online privacy', 'malware protection'],
        ]]);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'ad blocker')->andReturn([
            ['id' => '7001', 'name' => 'Browser games'],
            ['id' => '7002', 'name' => 'Beauty Without Cruelty'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'blocker')->andReturn([
            ['id' => '7003', 'name' => 'Ad blocking'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'online privacy')->andReturn([
            ['id' => '7004', 'name' => 'Internet privacy'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'malware protection')->andReturn([
            ['id' => '7005', 'name' => 'Malware protection'],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode');
        $suggestions = collect($choice['options'])->firstWhere('value', 'suggestions');

        Ai::assertAgentWasPrompted(StructuredAnonymousAgent::class, fn ($prompt): bool => str_contains((string) $prompt->prompt, 'https://iblockads.org/extension/landing')
            && str_contains((string) $prompt->prompt, 'Browse the Web Without Ads & Trackers'));
        $this->assertFalse($suggestions['disabled']);
        $this->assertSame(['7003', '7004', '7005'], $suggestions['arguments']['interest_ids']);
        $this->assertStringContainsString('ad blocker, online privacy, malware protection', $suggestions['hint']);
        $this->assertStringNotContainsString('Beauty Without Cruelty', $suggestions['hint']);
        $this->assertStringNotContainsString('Browser games', $suggestions['hint']);
        $this->assertSame('ad blocker, online privacy, malware protection', $choice['other_value']);
    }

    public function test_short_topics_match_and_a_shared_prefix_does_not(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://studio.example/',
            title: 'Studio',
            description: 'Yoga, golf, and a vpn.',
            headings: [],
            text: '',
            keywords: [],
        ));
        $phrases = Mockery::mock(AudienceInterestPhrases::class);
        $phrases->shouldReceive('forPage')->once()->andReturn(['yoga', 'pets', 'vpn', 'ad blocker']);
        $this->app->instance(AudienceInterestPhrases::class, $phrases);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'yoga')->andReturn([
            ['id' => '1', 'name' => 'Yoga'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'pets')->andReturn([
            ['id' => '2', 'name' => 'Pet food'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'vpn')->andReturn([
            ['id' => '3', 'name' => 'Virtual private network'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'ad blocker')->andReturn([
            ['id' => '4', 'name' => 'Blockchain'],
            ['id' => '5', 'name' => 'Blockbuster'],
            ['id' => '6', 'name' => 'Privateer'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'blocker')->andReturn([
            ['id' => '7', 'name' => 'Ad blocking'],
            ['id' => '4', 'name' => 'Blockchain'],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $suggestions = collect(collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode')['options'])
            ->firstWhere('value', 'suggestions');

        $this->assertFalse($suggestions['disabled']);
        $this->assertSame(['1', '2', '3', '7'], $suggestions['arguments']['interest_ids']);
    }

    public function test_a_disabled_suggestion_does_not_advertise_unmatched_phrases(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://iblockads.org/extension/landing',
            title: 'iblockads',
            description: '',
            headings: ['Block ads'],
            text: '',
            keywords: [],
        ));
        $phrases = Mockery::mock(AudienceInterestPhrases::class);
        $phrases->shouldReceive('forPage')->once()->andReturn(['ad blocker']);
        $this->app->instance(AudienceInterestPhrases::class, $phrases);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->andReturn([
            ['id' => '4', 'name' => 'Blockchain'],
            ['id' => '5', 'name' => 'Blockbuster'],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode');
        $suggestions = collect($choice['options'])->firstWhere('value', 'suggestions');

        $this->assertTrue($suggestions['disabled']);
        $this->assertSame([], $suggestions['arguments']['interest_ids']);
        $this->assertStringContainsString('No relevant Meta interests were found', $suggestions['hint']);
        $this->assertStringNotContainsString('ad blocker', $suggestions['hint']);
    }

    #[TestWith([false])]
    #[TestWith([true])]
    public function test_audience_phrases_are_reused_or_generated_without_an_ad_account(bool $hasStoredPhrases): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://studio.example/',
            title: 'Yoga Studio',
            description: 'Daily yoga.',
            headings: [],
            text: '',
            keywords: [],
        ));
        $page = $this->brief->page_analysis;
        $page['unrelated_metadata'] = ['keep' => true];

        if ($hasStoredPhrases) {
            $page['audience_phrases'] = ['yoga'];
        }

        $this->brief->update(['page_analysis' => $page]);
        $phrases = Mockery::mock(AudienceInterestPhrases::class);
        $phrases->shouldReceive('forPage')->times($hasStoredPhrases ? 0 : 1)->andReturn(['yoga']);
        $this->app->instance(AudienceInterestPhrases::class, $phrases);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->twice()->with('act_123', 'yoga')->andReturn([
            ['id' => '1', 'name' => 'Yoga'],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $savedPage = $this->brief->refresh()->page_analysis;
        $this->assertSame(['yoga'], $savedPage['audience_phrases']);
        $this->assertArrayNotHasKey('audience_phrases_v2', $savedPage);
        $this->assertSame(['keep' => true], $savedPage['unrelated_metadata']);
        app(Choices::class)->drain();
        $this->tool('campaign__set_targeting', ['section' => 'audience']);

        $campaign->update(['ad_account_id' => null]);
        app(Choices::class)->drain();
        $bare = Mockery::mock(AudienceInterestPhrases::class);
        $bare->shouldReceive('forPage')->never();
        $this->app->instance(AudienceInterestPhrases::class, $bare);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $suggestions = collect(collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode')['options'])
            ->firstWhere('value', 'suggestions');

        $this->assertTrue($suggestions['disabled']);
    }

    #[TestWith(['https://studio.example/'])]
    #[TestWith(['https://golf.example/'])]
    public function test_replacing_page_analysis_regenerates_ai_terms_instead_of_reusing_the_previous_page(string $newUrl): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $phrases = Mockery::mock(AudienceInterestPhrases::class);
        $phrases->shouldReceive('forPage')->once()
            ->withArgs(fn (LandingPageAnalysis $analysis): bool => $analysis->title === 'Yoga Studio')
            ->andReturn(['yoga']);
        $phrases->shouldReceive('forPage')->once()
            ->withArgs(fn (LandingPageAnalysis $analysis): bool => $analysis->title === 'Golf Studio')
            ->andReturn(['golf']);
        $this->app->instance(AudienceInterestPhrases::class, $phrases);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'yoga')
            ->andReturn([['id' => '1', 'name' => 'Yoga']]);
        $meta->shouldReceive('targetingInterests')->twice()->with('act_123', 'golf')
            ->andReturn([['id' => '2', 'name' => 'Golf']]);
        $this->app->instance(Meta::class, $meta);

        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://studio.example/', title: 'Yoga Studio', description: '',
            headings: [], text: '', keywords: [],
        ));
        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $this->assertSame(['yoga'], $this->brief->refresh()->page_analysis['audience_phrases']);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: $newUrl, title: 'Golf Studio', description: '',
            headings: [], text: '', keywords: [],
        ));

        foreach ([1, 2] as $turn) {
            app(Choices::class)->drain();
            $this->tool('campaign__set_targeting', ['section' => 'audience']);
            $choice = collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode');
            $suggestions = collect($choice['options'])->firstWhere('value', 'suggestions');
            $this->assertSame(['2'], $suggestions['arguments']['interest_ids']);
            $this->assertSame('golf', $choice['other_value']);
        }

        $this->assertSame(['golf'], $this->brief->refresh()->page_analysis['audience_phrases']);
    }

    public function test_a_model_outage_is_logged_and_does_not_offer_the_brand_name(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://iblockads.org/extension/landing',
            title: 'iblockads',
            description: '',
            headings: ['Block ads'],
            text: '',
            keywords: ['browse', 'trackers'],
        ));
        $logged = false;
        Log::listen(function ($event) use (&$logged): void {
            $logged = $logged || ($event->message ?? '') === 'Audience interest phrases failed';
        });
        Ai::fakeAgent(StructuredAnonymousAgent::class, [
            fn (mixed ...$arguments): never => throw new RuntimeException('model down'),
        ]);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        $choice = collect(app(Choices::class)->all())->firstWhere('field', 'meta_audience_mode');

        $this->assertSame('', $choice['other_value']);
        $this->assertTrue($logged);
    }

    public function test_ai_audience_suggestions_receive_landing_content_and_safe_targeting_instructions(): void
    {
        $this->campaign('meta', ['special_ad_categories' => ['NONE']]);
        $this->brief->rememberPageAnalysis(new LandingPageAnalysis(
            url: 'https://clinic.example/',
            title: 'Clinic Scheduling Software',
            description: 'Appointment scheduling and patient communication software for clinics.',
            headings: ['Reduce no-shows'],
            text: 'Automate appointment reminders for independent healthcare practices.',
            keywords: ['clinic scheduling', 'appointment reminders'],
        ));

        $prompt = (string) app(Instructions::class)->build();

        $this->assertStringContainsString('AI suggestions', $prompt);
        $this->assertStringContainsString('page description: Appointment scheduling and patient communication software for clinics.', $prompt);
        $this->assertStringContainsString('Meta\'s returned interests are the only selectable targeting values', $prompt);
        $this->assertStringContainsString('create_website_audience', $prompt);
        $this->assertStringContainsString('Keyword ideas from landing-page analysis are for Google Search only', $prompt);
        $this->assertStringContainsString(
            'Never show them as suggestions in Meta or LinkedIn conversations',
            preg_replace('/\s+/u', ' ', $prompt) ?? $prompt,
        );
    }

    public function test_typed_ideas_are_resolved_and_only_selected_meta_interests_are_saved(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
            'audience' => ['age_min' => 18, 'age_max' => 65, 'genders' => [1]],
        ]);
        $this->markDemographicsSelected($campaign);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'doctors')->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'path' => ['Interests', 'Additional interests', 'Physicians']],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'Medical students')->andReturn([
            ['id' => '6002', 'name' => 'Medical students'],
        ]);
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001', '6002'])->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'valid' => true],
            ['id' => '6002', 'name' => 'Medical students', 'valid' => true],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['section' => 'audience']);
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $appliedIdea = app(Answers::class)->applyAll([[
            'field' => 'meta_audience_mode',
            'value' => 'Target doctors in USA, Medical students etc.',
        ]]);

        $this->assertTrue($appliedIdea[0]['applied'], json_encode($appliedIdea));
        $this->assertSame(['6001', '6002'], array_column(
            collect(app(Choices::class)->all())->firstWhere('field', 'meta_interest_selection')['options'],
            'value',
        ));
        $this->assertSame(
            'Interests · Additional interests',
            collect(app(Choices::class)->all())->firstWhere('field', 'meta_interest_selection')['options'][0]['hint'],
        );

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $applied = app(Answers::class)->applyAll([[
            'field' => 'meta_interest_selection', 'value' => ['6001', '6002'],
        ]]);

        $this->assertTrue($applied[0]['applied'], json_encode($applied));
        $this->assertSame('custom', $campaign->fresh()->audience['meta_audience_mode']);
        $this->assertSame(['6001', '6002'], array_column($campaign->fresh()->audience['meta_interests'], 'id'));
    }

    public function test_custom_plain_english_option_on_interest_results_adds_search_matches_without_losing_picks(): void
    {
        $campaign = $this->campaign('meta', [
            'ad_account_id' => 'act_123',
            'special_ad_categories' => ['NONE'],
        ]);
        $meta = Mockery::mock(Meta::class);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'doctors')->andReturn([
            ['id' => '6001', 'name' => 'Physicians'],
        ]);
        $meta->shouldReceive('targetingInterests')->once()->with('act_123', 'dentists')->andReturn([
            ['id' => '6002', 'name' => 'Dentists'],
        ]);
        $meta->shouldReceive('validateTargetingInterests')->once()->with('act_123', ['6001', '6002'])->andReturn([
            ['id' => '6001', 'name' => 'Physicians', 'valid' => true],
            ['id' => '6002', 'name' => 'Dentists', 'valid' => true],
        ]);
        $this->app->instance(Meta::class, $meta);

        $this->tool('campaign__set_targeting', ['interest_ideas' => 'doctors']);
        $first = collect(app(Choices::class)->all())->firstWhere('field', 'meta_interest_selection');
        $this->assertTrue($first['allow_other']);
        $this->assertSame('Custom', $first['other_label']);
        $this->assertFalse($first['other_in_composer']);

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $search = app(Answers::class)->applyAll([[
            'field' => 'meta_interest_selection',
            'value' => ['6001', 'dentists'],
        ]]);
        $this->assertTrue($search[0]['applied'], json_encode($search));
        $next = collect(app(Choices::class)->all())->firstWhere('field', 'meta_interest_selection');
        $this->assertSame(['6001', '6002'], array_column($next['options'], 'value'));

        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());
        $saved = app(Answers::class)->applyAll([[
            'field' => 'meta_interest_selection', 'value' => ['6001', '6002'],
        ]]);

        $this->assertTrue($saved[0]['applied'], json_encode($saved));
        $this->assertSame(['6001', '6002'], array_column($campaign->fresh()->audience['meta_interests'], 'id'));
    }

    public function test_changing_other_targeting_does_not_restore_stale_legacy_countries(): void
    {
        $campaign = $this->campaign('meta');
        app(TargetingSelections::class)->saveCampaignCountries($campaign, ['DE']);
        $campaign->update(['locations' => ['countries' => ['US']]]);
        $revision = $campaign->targetingSet()->value('revision');

        $result = $this->tool('campaign__set_targeting', ['age_min' => 25]);

        $this->assertTrue($result['ok']);
        $this->assertSame(['DE'], $result['countries']);
        $this->assertSame(['DE'], app(TargetingSelections::class)->countries($campaign->fresh()));
        $this->assertSame($revision, $campaign->targetingSet()->value('revision'));
    }

    // ------------------------------------------------------------------ bidding

    /** Every platform can express all three intents. */
    public function test_each_platform_has_a_word_for_every_intent(): void
    {
        foreach ([app(MetaRules::class), app(GoogleRules::class), app(LinkedInRules::class)] as $rules) {
            foreach (['AUTOMATIC', 'TARGET_COST', 'BID_CAP'] as $intent) {
                $strategy = $rules->bidStrategyFor($intent, 'WEBSITE_VISITS');

                $this->assertNotNull($strategy, "{$rules->name()} has no strategy for {$intent}");
                $this->assertContains($strategy, $rules->bidStrategies(),
                    "{$rules->name()} maps {$intent} to {$strategy}, which is not on its own list");
            }
        }
    }

    /**
     * Google's automatic depends on what the campaign is for.
     *
     * Maximising clicks and maximising conversions are the same intent aimed at
     * different results, and sending the wrong one buys the wrong thing at full
     * price.
     */
    public function test_google_reads_the_objective_before_bidding_automatically(): void
    {
        $google = app(GoogleRules::class);

        $this->assertSame('MAXIMIZE_CLICKS', $google->bidStrategyFor('AUTOMATIC', 'WEBSITE_TRAFFIC'));
        $this->assertSame('MAXIMIZE_CONVERSIONS', $google->bidStrategyFor('AUTOMATIC', 'WEBSITE_CONVERSIONS'));
    }

    /** An intent nothing recognises is refused rather than approximated. */
    public function test_an_unknown_intent_has_no_strategy(): void
    {
        $this->assertNull((new MetaRules)->bidStrategyFor('WHATEVER_IS_CHEAPEST'));
    }

    /** The defect: the same intent asked again in another vocabulary. */
    public function test_the_next_platform_inherits_the_bid_intent(): void
    {
        $this->campaign('meta', ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP', 'objective' => 'OUTCOME_TRAFFIC']);

        $linkedin = $this->campaign('linkedin', ['objective' => 'WEBSITE_VISITS']);
        $result = $this->tool('campaign__set_bidding');

        $this->assertTrue($result['from_brief'] ?? false, 'LinkedIn was asked to choose all over again.');
        $this->assertSame('AUTOMATED_BID', $linkedin->refresh()->bid_strategy);
    }

    /** And Google gets its own word, chosen for its own objective. */
    public function test_google_inherits_the_intent_in_its_own_terms(): void
    {
        $this->campaign('meta', ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP', 'objective' => 'OUTCOME_TRAFFIC']);

        $google = $this->campaign('google', ['objective' => 'WEBSITE_TRAFFIC']);
        $this->tool('campaign__set_bidding');

        $this->assertSame('MAXIMIZE_CLICKS', $google->refresh()->bid_strategy);
    }

    /** The first platform is still asked, because nothing has been decided. */
    public function test_the_first_platform_is_still_asked_how_to_bid(): void
    {
        $this->campaign('meta');

        $result = $this->tool('campaign__set_bidding');

        $this->assertArrayNotHasKey('from_brief', $result);
        $this->assertStringContainsString('on screen', $result['note']);
    }

    /**
     * The amount is not carried across, only the strategy.
     *
     * A one dollar cost cap that suits Meta may be under LinkedIn's floor, so
     * the number is asked for again even though the strategy is not.
     */
    public function test_the_amount_is_not_inherited(): void
    {
        $this->campaign('meta', [
            'bid_strategy' => 'COST_CAP', 'bid_amount' => 1, 'objective' => 'OUTCOME_TRAFFIC',
        ]);

        $linkedin = $this->campaign('linkedin', ['objective' => 'WEBSITE_VISITS']);
        $result = $this->tool('campaign__set_bidding');

        $this->assertSame('TARGET_COST', $linkedin->refresh()->bid_strategy);
        $this->assertNull($linkedin->refresh()->bid_amount);
        $this->assertStringContainsString('still need answering', $result['note']);
    }

    /** An explicit strategy still wins over the inherited one. */
    public function test_a_platform_can_still_be_given_its_own_strategy(): void
    {
        $this->campaign('meta', ['bid_strategy' => 'LOWEST_COST_WITHOUT_CAP', 'objective' => 'OUTCOME_TRAFFIC']);

        $linkedin = $this->campaign('linkedin', ['objective' => 'WEBSITE_VISITS']);
        $this->tool('campaign__set_bidding', ['strategy' => 'MAXIMUM_BID', 'target_cost' => 5]);

        $this->assertSame('MAXIMUM_BID', $linkedin->refresh()->bid_strategy);
    }
}
