<?php

namespace Tests\Feature;

use App\Agent\Answers;
use App\Agent\Choices;
use App\Agent\MarketingAgent;
use App\Agent\ToolRegistry;
use App\Agent\Tools\Campaign\ChooseAdCopy;
use App\Agent\Tools\Campaign\WriteAdCopy;
use App\Agent\Workspace;
use App\Http\Controllers\ChatController;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\TestCase;

/**
 * Choosing the wording instead of being handed it.
 *
 * The only way to change one headline was to ask for the whole set again, which
 * replaced every variation including the ones already approved. These pin the
 * way out of that: alternatives offered as a question, the click applied without
 * a model turn, the buyer's own wording accepted, and a request for different
 * options kept separate from a choice.
 */
class ChooseAdCopyTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

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

        MarketingAgent::fake(['Noted.']);

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

        $workspace = app(Workspace::class);
        $workspace->bindTo('conv-copy-0001');
        $workspace->ownedBy($this->user);
    }

    private function campaign(string $platform = 'meta', int $ads = 3): Campaign
    {
        $campaign = Campaign::create([
            'user_id' => $this->user->id,
            'name' => 'Test',
            'platform' => $platform,
            'status' => 'draft',
        ]);

        for ($i = 1; $i <= $ads; $i++) {
            $campaign->ads()->create([
                'headline' => "Headline {$i}",
                'primary_text' => "Body {$i}.",
                'cta' => 'LEARN_MORE',
            ]);
        }

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

        return $campaign->fresh();
    }

    private function runTool(array $arguments = []): array
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t) => $t->name() === 'campaign__choose_ad_copy');

        $this->assertNotNull($tool, 'choose_ad_copy is not registered.');

        return json_decode((string) $tool->handle(new Request($arguments)), true);
    }

    private function offered(string $field): ?array
    {
        return collect(app(Choices::class)->all())->firstWhere('field', $field);
    }

    /** @return array<string, array{string, int, int}> */
    public static function customCopyPlatforms(): array
    {
        return ['meta' => ['meta', 40, 125], 'linkedin' => ['linkedin', 70, 600]];
    }

    #[DataProvider('customCopyPlatforms')]
    public function test_custom_copy_uses_the_platform_limits_in_the_offer_and_when_saved(string $platform, int $headlineLimit, int $bodyLimit): void
    {
        $campaign = $this->campaign($platform);
        $this->runTool(['offer_selection' => true]);
        $choice = $this->offered('ad_copy_selection');
        $this->assertSame($headlineLimit, $choice['copy_limits']['headline']);
        $this->assertSame($bodyLimit, $choice['copy_limits']['primary_text']);
        $selection = '__custom__::'.$campaign->ads()->orderBy('id')->value('id');

        $invalid = $this->runTool([
            'selection' => $selection,
            'headline' => str_repeat('H', $headlineLimit + 1),
            'primary_text' => str_repeat('B', $bodyLimit),
        ]);
        $this->assertFalse($invalid['ok']);
        $this->assertSame(3, $campaign->ads()->count());

        $invalidBody = $this->runTool([
            'selection' => $selection,
            'headline' => str_repeat('H', $headlineLimit),
            'primary_text' => str_repeat('B', $bodyLimit + 1),
        ]);
        $this->assertFalse($invalidBody['ok']);

        $saved = $this->runTool([
            'selection' => $selection,
            'headline' => str_repeat('H', $headlineLimit),
            'primary_text' => str_repeat('B', $bodyLimit),
        ]);
        $this->assertTrue($saved['ok']);
        $this->assertSame(1, $campaign->ads()->count());
        $this->assertSame($headlineLimit, mb_strlen($campaign->ads()->first()->headline));
        $this->assertSame($bodyLimit, mb_strlen($campaign->ads()->first()->primary_text));
    }

    /**
     * A campaign whose ads carry the given keys, so positions and ids differ.
     *
     * @param  list<int>  $ids
     */
    private function campaignWithAdIds(array $ids): Campaign
    {
        $campaign = $this->campaign('meta', count($ids));

        foreach ($campaign->ads()->orderBy('id')->get()->values() as $index => $ad) {
            $campaign->ads()->whereKey($ad->getKey())->update(['id' => $ids[$index]]);
        }

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

        return $campaign->fresh();
    }

    private function headlines(Campaign $campaign): array
    {
        return $campaign->ads()->orderBy('id')->pluck('headline')->all();
    }

    // ------------------------------------------------------------- offering

    public function test_alternatives_are_offered_rather_than_applied(): void
    {
        $campaign = $this->campaign();

        $result = $this->runTool(['ad' => 1, 'headlines' => ['Shorter', 'Punchier', 'Plainer']]);

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

        $offered = $this->offered('ad_headline');
        $this->assertNotNull($offered);
        $this->assertStringContainsString('variation 1', $offered['question']);
        $this->assertContains('Shorter', array_column($offered['options'], 'label'));

        // Nothing moved just by asking.
        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));
    }

    /** Typing your own line is the edit path, so the question has to allow it. */
    public function test_the_buyers_own_wording_is_allowed(): void
    {
        $this->campaign();

        $this->runTool(['ad' => 1, 'headlines' => ['Shorter']]);

        $this->assertTrue($this->offered('ad_headline')['allow_other']);
    }

    /** The platform's own word for the body, so the question reads like the platform. */
    public function test_the_body_question_uses_the_platforms_word(): void
    {
        $this->campaign('google');

        $this->runTool(['ad' => 1, 'primary_texts' => ['One', 'Two']]);

        $this->assertStringContainsString('description', $this->offered('ad_primary_text')['question']);
    }

    public function test_both_questions_can_be_offered_at_once(): void
    {
        $this->campaign();

        $this->runTool(['ad' => 1, 'headlines' => ['A', 'B'], 'primary_texts' => ['C', 'D']]);

        $this->assertNotNull($this->offered('ad_headline'));
        $this->assertNotNull($this->offered('ad_primary_text'));
    }

    public function test_legacy_copy_review_card_advances_to_variation_choices(): void
    {
        $this->campaign();
        app(Workspace::class)->rememberChoices([[
            'field' => 'copy_review',
            'question' => 'Review the ad copy above',
            'options' => [['value' => 'continue', 'label' => 'Continue to variation choices']],
        ]]);

        $applied = app(Answers::class)->applyAll([['field' => 'copy_review', 'value' => 'continue']]);

        $this->assertTrue($applied[0]['applied']);
        $selection = $this->offered('ad_copy_selection');
        $this->assertNotNull($selection);
        $this->assertSame(6, count($selection['options']));
        $this->assertSame('Write custom ad copy', $selection['options'][5]['label']);
    }

    public function test_review_defaults_to_complete_variation_choices(): void
    {
        $this->campaign();

        $result = $this->runTool(['ad' => 1]);

        $this->assertTrue($result['ok']);
        $this->assertNotNull($this->offered('ad_copy_selection'));
        $this->assertNull($this->offered('ad_headline'));
        $this->assertNull($this->offered('ad_primary_text'));
    }

    public function test_review_does_not_offer_regeneration_for_live_ads(): void
    {
        $campaign = $this->campaign('linkedin', ads: 1);
        $campaign->ads()->first()->update(['external_ad_id' => 'live-ad']);

        $result = $this->runTool(['offer_selection' => true]);

        $this->assertFalse($result['ok']);
        $this->assertNull($this->offered('ad_copy_selection'));
        $this->assertArrayNotHasKey('copy_regeneration', (array) $campaign->fresh()->meta);
    }

    public function test_variation_choices_can_be_scoped_to_one_ad_set(): void
    {
        $campaign = $this->campaign();
        $primaryAdSet = $campaign->primaryAdSet;
        $otherAdSet = $campaign->adSets()->create(['name' => 'Other audience', 'position' => 2]);
        $campaign->ads()->orderBy('id')->get()->last()->update(['ad_set_id' => $otherAdSet->id]);

        $result = $this->runTool(['offer_selection' => true, 'ad_set_id' => $primaryAdSet->id]);

        $this->assertTrue($result['ok'], json_encode($result));
        $this->assertSame(2, $result['variations']);
        $this->assertSame([
            'Use variation 1 only',
            'Use variation 2 only',
            'Use all 2 variations as separate ads',
            'Regenerate ad-copy',
            'Write custom ad copy',
        ], array_column($this->offered('ad_copy_selection')['options'], 'label'));
    }

    // -------------------------------------------------------------- applying

    /**
     * The click lands on the variation it was offered for.
     *
     * This is the whole reason the index travels in the value: two questions can
     * be on screen for different variations at once, and the apply path is given
     * nothing but the field name and the value.
     */
    public function test_the_chosen_line_lands_on_that_variation_only(): void
    {
        $campaign = $this->campaign();

        app(Answers::class)->applyAll([['field' => 'ad_headline', 'value' => '2::Punchier']]);

        $this->assertSame(['Headline 1', 'Punchier', 'Headline 3'], $this->headlines($campaign));
    }

    public function test_the_chosen_body_lands_too(): void
    {
        $campaign = $this->campaign();

        app(Answers::class)->applyAll([['field' => 'ad_primary_text', 'value' => '3::New body.']]);

        $this->assertSame('New body.', $campaign->ads()->orderBy('id')->get()[2]->primary_text);
    }

    public function test_only_the_selected_draft_variation_is_retained(): void
    {
        $campaign = $this->campaign();
        $ads = $campaign->ads()->orderBy('id')->get();
        $ads[1]->update([
            'headline' => 'Selected headline',
            'primary_text' => 'Selected body.',
            'description' => 'Selected description.',
            'cta' => 'SIGN_UP',
        ]);
        $liveAd = $campaign->ads()->create([
            'headline' => 'Live headline',
            'primary_text' => 'Live body.',
            'description' => 'Live description.',
            'cta' => 'LEARN_MORE',
            'external_ad_id' => 'live-ad-1',
        ]);

        app(Answers::class)->applyAll([[
            'field' => 'ad_copy_selection',
            'value' => (string) $ads[1]->getKey(),
        ]]);

        $draftAds = $campaign->ads()->whereNull('external_ad_id')->orderBy('id')->get();
        $this->assertSame([$ads[1]->id], $draftAds->pluck('id')->all());
        $this->assertSame(['Selected headline'], $draftAds->pluck('headline')->all());
        $this->assertSame(['Selected body.'], $draftAds->pluck('primary_text')->all());
        $this->assertSame(['Selected description.'], $draftAds->pluck('description')->all());
        $this->assertSame(['SIGN_UP'], $draftAds->pluck('cta')->all());
        $this->assertSame('Live headline', $liveAd->fresh()->headline);
    }

    public function test_using_all_variations_preserves_their_distinct_copy(): void
    {
        $campaign = $this->campaign();
        $source = $campaign->ads()->first();

        $this->assertTrue(app(Answers::class)->apply('ad_copy_selection', '__all::'.$source->id));

        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));
    }

    public function test_retry_requests_new_variations_without_changing_the_existing_ads(): void
    {
        $campaign = $this->campaign();
        $source = $campaign->ads()->first();

        $result = $this->runTool(['selection' => ChooseAdCopy::REGENERATE.'::'.$source->id]);

        $this->assertTrue($result['ok']);
        $this->assertStringContainsString('write_ad_copy', $result['note']);
        $this->assertStringContainsString('Wait for the user to choose', $result['note']);
        $this->assertSame('What should these ads highlight?', $this->offered('copy_emphasis')['question']);
        $this->assertNull($this->offered('ad_copy_selection'));
        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));
    }

    #[TestWith(['linkedin', 1])]
    #[TestWith(['linkedin', 3])]
    #[TestWith(['google', 3])]
    public function test_regeneration_waits_for_a_highlight_then_shows_three_new_variations(string $platform, int $ads): void
    {
        $campaign = $this->campaign($platform, ads: $ads);
        $before = $this->headlines($campaign);
        $this->runTool(['offer_selection' => true]);
        $choice = $this->offered('ad_copy_selection');
        $this->assertNotNull($choice);
        $regenerate = collect($choice['options'])->firstWhere('label', 'Regenerate ad-copy');
        $this->assertNotNull($regenerate);
        if ($ads === 1) {
            $this->assertNotContains('Use all 1 variations as separate ads', array_column($choice['options'], 'label'));
        }
        app(Choices::class)->drain();
        $this->assertTrue(app(Answers::class)->apply('ad_copy_selection', $regenerate['value']));
        $this->assertNotNull($this->offered('copy_emphasis'));
        $this->assertNull($this->offered('ad_headline'));
        $this->assertNull($this->offered('ad_primary_text'));
        $writer = app(WriteAdCopy::class);
        $freshAds = array_map(fn (int $index): array => [
            'headline' => 'Fresh headline '.$index,
            'primary_text' => 'Fresh benefit-focused body '.$index,
            'cta' => 'LEARN_MORE',
        ], [1, 2, 3]);

        app(Choices::class)->drain();
        $writer->handle(new Request(['ads' => $freshAds]));
        $this->assertNotNull($this->offered('copy_emphasis'));
        $this->assertSame($before, $this->headlines($campaign));

        app(Choices::class)->drain();
        $this->assertTrue(app(Answers::class)->apply('copy_emphasis', 'Key Benefits & Features'));
        $invalid = json_decode((string) $writer->handle(new Request(['ads' => array_slice($freshAds, 0, 2)])), true);
        $this->assertFalse($invalid['ok']);
        $this->assertSame($before, $this->headlines($campaign));

        $written = json_decode((string) $writer->handle(new Request(['ads' => $freshAds])), true);

        $this->assertTrue($written['ok'], json_encode($written));
        $this->assertSame(['Fresh headline 1', 'Fresh headline 2', 'Fresh headline 3'], $this->headlines($campaign));
        $choice = $this->offered('ad_copy_selection');
        $this->assertSame('Which ad-copy variation should we use?', $choice['question']);
        // Google reviews the lines themselves now, so this question carries
        // only Regenerate and the checkbox lists carry the copy. See
        // test_google_review_puts_every_line_on_screen_with_a_checkbox.
        $this->assertSame($platform === 'google' ? [
            'Regenerate ad-copy',
        ] : [
            'Use variation 1 only', 'Use variation 2 only', 'Use variation 3 only',
            'Use all 3 variations as separate ads', 'Regenerate ad-copy', 'Write custom ad copy',
        ], array_column($choice['options'], 'label'));

        if ($platform === 'google') {
            $this->assertSame(
                ['Fresh headline 1', 'Fresh headline 2', 'Fresh headline 3'],
                array_column($this->offered('google_headlines')['options'], 'value'),
                'the freshly written headlines have to be the ones offered',
            );
        }
        $this->assertArrayNotHasKey('copy_regeneration', $campaign->fresh()->meta);
    }

    public function test_promotion_regeneration_waits_for_offer_details_without_showing_old_variations(): void
    {
        $campaign = $this->campaign('linkedin');
        $source = $campaign->ads()->first();
        $this->runTool(['selection' => ChooseAdCopy::REGENERATE.'::'.$source->id]);
        app(Choices::class)->drain();
        $this->assertTrue(app(Answers::class)->apply('copy_emphasis', 'Special Promotion & Discount'));
        $detailsChoice = $this->offered('copy_promotion_details');

        $this->assertNotNull($detailsChoice);
        $this->assertTrue($detailsChoice['allow_other']);
        $this->assertFalse($detailsChoice['other_in_composer']);
        $this->assertNull($this->offered('ad_copy_selection'));
        app(Workspace::class)->rememberChoices(app(Choices::class)->drain());

        $controller = app(ChatController::class);
        (new \ReflectionMethod($controller, 'offerNextStep'))->invoke($controller);
        $this->assertNotNull($this->offered('copy_promotion_details'));
        $this->assertNull($this->offered('ad_copy_selection'));
        app(Choices::class)->drain();
        $this->runTool(['offer_selection' => true]);
        $this->assertNotNull($this->offered('copy_promotion_details'));
        $this->assertNull($this->offered('ad_copy_selection'));

        $freshAds = array_map(fn (int $index): array => [
            'headline' => 'Save on your plan '.$index,
            'primary_text' => 'Get 10% off your first month. New customers only.',
            'cta' => 'LEARN_MORE',
        ], [1, 2, 3]);
        $writer = app(WriteAdCopy::class);
        $blocked = json_decode((string) $writer->handle(new Request(['ads' => $freshAds])), true);
        $this->assertFalse($blocked['ok']);
        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));

        app(Choices::class)->drain();
        $applied = (new \ReflectionMethod($controller, 'applyAnswers'))->invoke($controller, [[
            'field' => 'copy_promotion_details',
            'value' => '10% off your first month. New customers only. No expiry.',
        ]]);
        $this->assertTrue($applied[0]['applied']);
        $written = json_decode((string) $writer->handle(new Request(['ads' => $freshAds])), true);

        $this->assertTrue($written['ok'], json_encode($written));
        $this->assertSame(3, $campaign->ads()->count());
        $this->assertNotNull($this->offered('ad_copy_selection'));
        $this->assertArrayNotHasKey('copy_regeneration', $campaign->fresh()->meta);
    }

    public function test_promotion_regeneration_can_return_to_the_highlight_chooser(): void
    {
        $campaign = $this->campaign('linkedin');
        $source = $campaign->ads()->first();
        $this->runTool(['selection' => ChooseAdCopy::REGENERATE.'::'.$source->id]);
        app(Choices::class)->drain();
        app(Answers::class)->apply('copy_emphasis', 'Special Promotion & Discount');
        app(Choices::class)->drain();

        $this->assertTrue(app(Answers::class)->apply('copy_promotion_details', '__change_highlight'));
        $this->assertNotNull($this->offered('copy_emphasis'));
        $this->assertTrue($campaign->fresh()->meta['copy_regeneration']['awaiting_emphasis']);
        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));
    }

    public function test_selection_does_not_remove_ads_from_another_ad_set(): void
    {
        $campaign = $this->campaign();
        $source = $campaign->ads()->first();
        $otherSet = $campaign->adSets()->create(['name' => 'Other audience', 'position' => 2]);
        $otherAd = $campaign->ads()->create([
            'ad_set_id' => $otherSet->id,
            'headline' => 'Other headline',
            'primary_text' => 'Other body.',
            'cta' => 'LEARN_MORE',
        ]);

        $this->assertTrue(app(Answers::class)->apply('ad_copy_selection', (string) $source->id));

        $this->assertSame([$source->id, $otherAd->id], $campaign->ads()->orderBy('id')->pluck('id')->all());
    }

    /**
     * "Use variation 1" picks the first variation, not the ad whose id is 1.
     *
     * Dev server, 8 Oct, campaign 175. The buyer said "Use variation 1 only to
     * create one ad" and was told "That ad-copy variation is no longer
     * available". Nothing had gone away: apply_to_all read the digit as a primary
     * key, the campaign's only ad was id 269, so the lookup found nothing - while
     * every other branch of this tool counts variations from one and the chat
     * prints the choices as 1. 2. 3., which is the number the buyer repeats back.
     */
    public function test_a_variation_can_be_chosen_by_its_position(): void
    {
        // Ids deliberately far from 1, 2, 3. On a fresh database the ads get
        // exactly those keys, so "2" matches by primary key and the position
        // path is never reached - the first version of this test passed with the
        // fallback deleted. Production ids look like 269.
        $campaign = $this->campaignWithAdIds([267, 268, 269]);
        $second = $campaign->ads()->orderBy('id')->get()->get(1);

        $this->assertSame(268, $second->id, 'the fixture did not take the ids');
        $this->assertTrue(app(Answers::class)->apply('ad_copy_selection', '2'));

        $this->assertSame(1, $campaign->ads()->count(), 'the other drafts should have gone');
        $this->assertSame($second->id, $campaign->ads()->first()->id, 'the wrong variation was kept');
    }

    /**
     * Not when the drafts span two ad sets, because then the number is ambiguous.
     *
     * The single action deletes every other draft in the set, so a guess here
     * removes ads the buyer never pointed at. Refusing and asking them to click
     * is the cheap half of that trade.
     */
    public function test_a_position_is_refused_when_drafts_span_two_ad_sets(): void
    {
        $campaign = $this->campaignWithAdIds([267, 268]);
        $second = $campaign->adSets()->create(['position' => 2, 'name' => 'Second set']);
        $campaign->ads()->orderBy('id')->first()->update(['ad_set_id' => $second->id]);

        $this->assertFalse(app(Answers::class)->apply('ad_copy_selection', '1'));
        $this->assertSame(2, $campaign->ads()->count(), 'an ambiguous position deleted a draft');
    }

    /** And the id a click sends still wins, so no button changes meaning. */
    public function test_an_offered_id_still_takes_precedence_over_the_position(): void
    {
        $campaign = $this->campaign();
        $third = $campaign->ads()->orderBy('id')->get()->get(2);

        $this->assertTrue(app(Answers::class)->apply('ad_copy_selection', (string) $third->id));

        $this->assertSame($third->id, $campaign->ads()->first()->id);
    }

    /**
     * A position past the end is refused, and says what there is.
     *
     * The old wording was "no longer available", which implies it existed and was
     * withdrawn. The sibling error in the same file already said it properly.
     */
    public function test_a_position_that_does_not_exist_says_how_many_there_are(): void
    {
        $campaign = $this->campaign();

        $this->assertFalse(app(Answers::class)->apply('ad_copy_selection', '9'));
        $this->assertSame(3, $campaign->ads()->count(), 'a failed selection deleted drafts');
    }

    /**
     * A published ad's id is not re-read as a position.
     *
     * This is the dangerous case and the reason the fallback is conditional. The
     * single action deletes every other draft in the ad set, so if a number that
     * already means a published ad were reinterpreted as a position, the buyer
     * would lose drafts they never pointed at. The first version of the fix did
     * that, and the test below this one caught it.
     */
    public function test_a_published_ads_id_is_not_reinterpreted_as_a_position(): void
    {
        $campaign = $this->campaign();
        $ads = $campaign->ads()->orderBy('id')->get();
        $ads->first()->update(['external_ad_id' => 'live-ad']);

        $this->assertFalse(app(Answers::class)->apply('ad_copy_selection', (string) $ads->first()->id));
        $this->assertSame(3, $campaign->ads()->count(), 'drafts were deleted by a refused selection');
    }

    public function test_stale_or_published_variations_cannot_be_selected(): void
    {
        $campaign = $this->campaign();
        $source = $campaign->ads()->first();
        $source->update(['external_ad_id' => 'live-ad']);

        $this->assertFalse(app(Answers::class)->apply('ad_copy_selection', (string) $source->id));
        $this->assertFalse(app(Answers::class)->apply('ad_copy_selection', '999999'));

        $this->assertSame(3, $campaign->ads()->count());
    }

    public function test_google_search_keeps_its_responsive_ad_copy_bundle(): void
    {
        $campaign = $this->campaign('google');
        $source = $campaign->ads()->first();

        $this->assertFalse(app(Answers::class)->apply('ad_copy_selection', (string) $source->id));

        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));
    }

    /**
     * The Google review is the copy itself, line by line.
     *
     * This asserted the screen it replaces: "keep all copy for one responsive
     * search ad" or "regenerate", which meant a buyer who wanted eleven of
     * twelve headlines had to throw the set away. Asked for directly - "need to
     * see all the headlines and description before publishing" and "give
     * options to choose multiple headlines and descriptions like a checkbox
     * next to them" - so the premise is retired rather than the behaviour.
     *
     * Regenerate stays, on the same screen, because disliking every line is
     * still a thing a buyer can want.
     */
    public function test_google_review_puts_every_line_on_screen_with_a_checkbox(): void
    {
        $campaign = $this->campaign('google');
        $source = $campaign->ads()->first();
        $this->runTool(['offer_selection' => true]);

        $headlines = $this->offered('google_headlines');
        $descriptions = $this->offered('google_descriptions');

        $this->assertNotNull($headlines, 'the headlines never reached the screen');
        $this->assertNotNull($descriptions, 'the descriptions never reached the screen');
        $this->assertTrue($headlines['multiple']);
        $this->assertTrue($descriptions['multiple']);

        // Every written line, and all of them already ticked: keeping what you
        // have must stay one click.
        $this->assertSame(
            ['Headline 1', 'Headline 2', 'Headline 3'],
            array_column($headlines['options'], 'value'),
        );
        $this->assertTrue(collect($headlines['options'])->every(fn (array $option): bool => $option['selected']));
        $this->assertSame('30 characters', substr((string) $headlines['options'][0]['hint'], -13));

        // And Regenerate, on the same screen rather than instead of it.
        $regenerate = $this->offered('ad_copy_selection');
        $this->assertNotNull($regenerate);
        $this->assertSame(
            [ChooseAdCopy::REGENERATE.'::'.$source->id],
            array_column($regenerate['options'], 'value'),
        );
        $this->assertTrue(Choices::isOneSemanticForm(
            ['google_headlines', 'google_descriptions', 'ad_copy_selection'],
        ), 'the three questions have to share one screen');

        app(Choices::class)->drain();
        $result = $this->runTool(['selection' => $regenerate['options'][0]['value']]);
        $this->assertTrue($result['ok']);
        $this->assertNotNull($this->offered('copy_emphasis'));
    }

    /** Narrowing the set records it and leaves the written lines alone. */
    public function test_google_copy_lines_are_narrowed_rather_than_destroyed(): void
    {
        $campaign = $this->campaign('google');
        $this->runTool(['offer_selection' => true]);

        $result = $this->runTool(['use_headlines' => ['Headline 1', 'Headline 3', 'Headline 2']]);

        $this->assertTrue($result['ok']);
        $this->assertSame(
            ['Headline 1', 'Headline 3', 'Headline 2'],
            $campaign->fresh()->meta['google_copy_lines']['headlines'],
        );

        // The drafts still hold everything, so the buyer can widen it again.
        $this->assertSame(['Headline 1', 'Headline 2', 'Headline 3'], $this->headlines($campaign));
    }

    /** Google's own floor, refused before the campaign exists rather than after. */
    public function test_too_few_headlines_is_refused(): void
    {
        $this->campaign('google');
        $this->runTool(['offer_selection' => true]);

        $result = $this->runTool(['use_headlines' => ['Headline 1', 'Headline 2']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('3 to 15 headlines', $result['error']);
    }

    /** A line nobody wrote cannot arrive as a selection. */
    public function test_a_line_the_ad_does_not_hold_is_refused(): void
    {
        $this->campaign('google');
        $this->runTool(['offer_selection' => true]);

        $result = $this->runTool(['use_headlines' => ['Headline 1', 'Headline 2', 'Invented']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('Invented', $result['error']);
    }

    /** Typed wording arrives with no index and belongs to the first variation. */
    public function test_wording_typed_by_the_buyer_is_accepted(): void
    {
        $campaign = $this->campaign();

        app(Answers::class)->applyAll([['field' => 'ad_headline', 'value' => 'My own line']]);

        $this->assertSame('My own line', $this->headlines($campaign)[0]);
    }

    /** A headline that happens to start with digits is not an index. */
    public function test_a_typed_line_is_not_mistaken_for_an_index(): void
    {
        $campaign = $this->campaign();

        app(Answers::class)->applyAll([['field' => 'ad_headline', 'value' => '50% off everything']]);

        $this->assertSame('50% off everything', $this->headlines($campaign)[0]);
    }

    // ----------------------------------------------------------- regenerate

    /**
     * Asking for different options is not a value to store.
     *
     * Refused on purpose, so the sentence reaches the model and it writes a
     * fresh set. Storing it would put the literal marker in the ad.
     */
    public function test_regenerate_is_refused_rather_than_stored(): void
    {
        $campaign = $this->campaign();

        $result = $this->runTool(['headline' => '1::'.ChooseAdCopy::REGENERATE]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('different options', $result['error']);
        $this->assertSame('Headline 1', $this->headlines($campaign)[0]);
    }

    /** And it is offered, because asking in prose is what replaced whole sets. */
    public function test_regenerate_is_offered_beside_the_alternatives(): void
    {
        $this->campaign();

        $this->runTool(['ad' => 1, 'headlines' => ['A', 'B']]);

        $values = array_column($this->offered('ad_headline')['options'], 'value');

        $this->assertContains('1::'.ChooseAdCopy::REGENERATE, $values);
    }

    // ---------------------------------------------------------------- guards

    public function test_a_variation_that_does_not_exist_is_refused(): void
    {
        $this->campaign(ads: 2);

        $result = $this->runTool(['ad' => 9, 'headlines' => ['A']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('no variation 9', $result['error']);
    }

    public function test_it_asks_for_copy_first_when_there_is_none(): void
    {
        $this->campaign(ads: 0);

        $result = $this->runTool(['ad' => 1, 'headlines' => ['A']]);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('write_ad_copy', $result['error']);
    }

    public function test_empty_wording_is_refused(): void
    {
        $campaign = $this->campaign();

        $this->runTool(['headline' => '1::   ']);

        $this->assertSame('Headline 1', $this->headlines($campaign)[0]);
    }

    /** What is there now is marked, so the buyer can see what they would change. */
    public function test_the_current_line_is_marked(): void
    {
        $this->campaign();

        $this->runTool(['ad' => 1, 'headlines' => ['Headline 1', 'Something else']]);

        $current = collect($this->offered('ad_headline')['options'])->firstWhere('label', 'Headline 1');

        $this->assertSame('Current', $current['badge'] ?? null);
    }
}
