<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Platforms\Platforms;
use App\Campaigns\Targeting\GoogleAdAssets;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\CampaignAd;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Picking the wording, rather than being handed it.
 *
 * write_ad_copy produces a set of variations and stores them, and that was the
 * end of it: the only way to change a headline was to ask for the whole set
 * again in prose and hope the one line you liked survived. Buyers did exactly
 * that - "keep 2 but make the first one shorter" - and got three new ads none of
 * which were the ones they had approved.
 *
 * So the alternatives are offered as a question like every other question in the
 * flow. The model writes several lines, this puts them on screen, and the click
 * applies server-side without a model turn. Three things come out of that for
 * free: the buyer's own wording through "write my own", a regenerate that asks
 * for fresh options rather than a fresh campaign, and a record that the line was
 * chosen rather than generated.
 *
 * One ad at a time, because the variations are meant to differ. Applying a
 * chosen headline to all of them would collapse the set into three copies of
 * itself, which is the opposite of what a variation is for.
 */
class ChooseAdCopy implements Tool
{
    use ActsOnFocusedCampaign;

    /**
     * The index and the text travel together in the value.
     *
     * Answers applies a click by field name alone, and the field names are a
     * static map, so "ad 2's headline" cannot be a field of its own. Carrying
     * the index in the value keeps the apply path stateless: nothing has to
     * remember which ad was being edited between the offer and the click, which
     * is the part that breaks when two questions are on screen at once.
     */
    private const SEPARATOR = '::';

    /** Asking for a different set, rather than a different campaign. */
    public const REGENERATE = '__regenerate';

    public const USE_ALL = '__all';

    /** What each platform calls the body of the ad, in its own words. */
    private const BODY_LABEL = [
        'meta' => 'primary text',
        'google' => 'description',
        'linkedin' => 'introductory text',
    ];

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly Platforms $platforms,
    ) {}

    public function description(): Stringable|string
    {
        return 'For a general ad-copy review or change, call with offer_selection=true to show complete '
            .'variations and the Regenerate ad-copy action, even when only one draft remains. Regenerate '
            .'asks what to highlight before writing three fresh complete variations. Only offer separate '
            .'headline or body alternatives when the user explicitly requests editing that individual field. '
            .'Pass ad (1 for the '
            .'first variation) with headlines and/or primary_texts to put options on screen, several of '
            .'each. Call this when the user wants different wording, a shorter headline, or to choose '
            .'between lines. Do not call write_ad_copy for an individual wording change: that replaces every '
            .'variation, including the ones already approved. For a newly written variation choice, '
            .'pass its offered value as selection. One chosen variation keeps only that draft ad; '
            .'the all-variations choice keeps the distinct drafts, and retry requests fresh variations.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad' => $schema->integer()
                ->description('Which variation to offer wording for, counting from 1. Defaults to the first.'),
            'headlines' => $schema->array()
                ->items($schema->string())
                ->description('Alternative headlines to offer. Write three or four, all different.'),
            'primary_texts' => $schema->array()
                ->items($schema->string())
                ->description('Alternative body copy to offer. Write three or four, all different.'),
            'headline' => $schema->string()->description('Headline text to apply directly, or the custom headline for a __custom__ selection.'),
            'primary_text' => $schema->string()->description('Body text to apply directly, or the custom primary text for a __custom__ selection.'),
            'selection' => $schema->string()
                ->description('The offered variation-selection value: an ad id, __all::ad_id, __regenerate::ad_id, or __custom__::ad_id.'),
            'offer_selection' => $schema->boolean()
                ->description('Show complete variation choices, including Regenerate ad-copy. Use for general review or changes to existing ad copy.'),
            'ad_set_id' => $schema->integer()
                ->description('Which ad set to offer variations from. Required when variations exist in more than one ad set.'),
            'apply_to_all' => $schema->integer()
                ->description('Which variation to keep: the offered ad id, or its position in the list '
                    .'counting from one, which is the number the user will say. Keeps only that '
                    .'unpublished variation and removes the other drafts in its ad set.'),
            'use_headlines' => $schema->array()->items($schema->string())
                ->description('Google only. The exact headline lines the responsive search ad should '
                    .'use, from the ones already on screen. Three to fifteen. Narrows the written '
                    .'copy; it does not write new lines.'),
            'use_descriptions' => $schema->array()->items($schema->string())
                ->description('Google only. The exact description lines to use, from the ones already '
                    .'on screen. Two to four.'),
            'use_sitelinks' => $schema->array()->items($schema->string())
                ->description('Google only. The sitelink labels the user approved, from the ones '
                    .'offered. An empty array means none, which is a valid ad. Never send a label '
                    .'the user did not tick.'),
            'use_callouts' => $schema->array()->items($schema->string())
                ->description('Google only. The callout texts the user approved, from the ones '
                    .'offered. An empty array means none.'),
            'use_structured_snippet' => $schema->boolean()
                ->description('Google only. True when the user approved the structured snippet that '
                    .'was offered. There is only ever one, built from the page.'),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }

        $ads = $campaign->ads()->orderBy('id')->get();

        if ($ads->isEmpty()) {
            return $this->json([
                'ok' => false,
                'error' => 'There is no ad copy to change yet. Call write_ad_copy first.',
            ]);
        }

        $arguments = $request->all();

        if (! empty($arguments['offer_selection'])) {
            return $this->offerVariationSelection(
                $campaign,
                $ads,
                isset($arguments['ad_set_id']) ? (int) $arguments['ad_set_id'] : null,
            );
        }

        // Narrowing the written copy, which arrives from the checkbox lists and
        // is recorded rather than applied to the ad rows: the lines stay where
        // they were written so the buyer can widen the selection again without
        // regenerating anything.
        if (array_key_exists('use_headlines', $arguments) || array_key_exists('use_descriptions', $arguments)) {
            return $this->keepGoogleCopyLines($campaign, $ads, $arguments);
        }

        if (array_key_exists('use_sitelinks', $arguments)
            || array_key_exists('use_callouts', $arguments)
            || array_key_exists('use_structured_snippet', $arguments)) {
            return $this->keepGoogleAdAssets($campaign, $arguments);
        }

        if (array_key_exists('selection', $arguments) || array_key_exists('apply_to_all', $arguments)) {
            return $this->selectVariations(
                $campaign,
                $ads,
                (string) ($arguments['selection'] ?? $arguments['apply_to_all']),
                (string) ($arguments['headline'] ?? ''),
                (string) ($arguments['primary_text'] ?? ''),
            );
        }

        // Applying comes first: a click arrives as headline or primary_text
        // with the index folded into it, and must not be mistaken for a request
        // to offer the same question again.
        foreach (['headline', 'primary_text'] as $field) {
            if (array_key_exists($field, $arguments)) {
                return $this->apply($campaign, $ads, $field, (string) $arguments[$field]);
            }
        }

        $index = max(1, (int) ($arguments['ad'] ?? 1));

        if (! $ad = $ads->get($index - 1)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('There is no variation %d. The campaign has %d.', $index, $ads->count()),
            ]);
        }

        $headlines = $this->clean($arguments['headlines'] ?? []);
        $bodies = $this->clean($arguments['primary_texts'] ?? []);

        if ($headlines === [] && $bodies === []) {
            return $this->offerVariationSelection(
                $campaign,
                $ads,
                isset($arguments['ad_set_id']) ? (int) $arguments['ad_set_id'] : null,
            );
        }

        return $this->offer($campaign, $ad, $index, $headlines, $bodies);
    }

    /** @param Collection<int, CampaignAd> $ads */
    private function offerVariationSelection(Campaign $campaign, Collection $ads, ?int $adSetId = null): Stringable|string
    {
        if (isset($campaign->meta['copy_regeneration'])) {
            return app(WriteAdCopy::class)->handle(new Request([]));
        }

        $drafts = $this->draftsOf($ads);

        if ($adSetId !== null) {
            if (! $campaign->adSets()->whereKey($adSetId)->exists()) {
                return $this->json(['ok' => false, 'error' => 'That ad set does not belong to this campaign.']);
            }

            $primaryAdSetId = $campaign->primaryAdSet?->id;
            $drafts = $drafts->filter(fn (CampaignAd $ad): bool => (int) ($ad->ad_set_id ?? $primaryAdSetId) === $adSetId)->values();
        }

        if ($drafts->isEmpty()) {
            return $this->json(['ok' => false, 'error' => 'There are no draft variations to review.']);
        }

        $adSets = $drafts
            ->map(fn (CampaignAd $ad): mixed => $ad->ad_set_id ?? $campaign->primaryAdSet?->id)
            ->unique();

        if ($adSets->count() !== 1) {
            return $this->json(['ok' => false, 'error' => 'The draft variations belong to different ad sets. Choose variations within one ad set.']);
        }

        $first = $drafts->first();

        // Google reviews the copy line by line, because that is what a
        // responsive search ad is: one ad holding up to 15 headlines and 4
        // descriptions that Google mixes itself. The old review offered "keep
        // all" or "regenerate", so a buyer who wanted 11 of 12 headlines had to
        // throw the set away and hope the next one was better. 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".
        //
        // Everything below this point is therefore a platform whose variations
        // are separate ads, which is every platform except Google.
        if ($campaign->platform === 'google') {
            return $this->offerGoogleCopyLines($campaign, $drafts);
        }

        $options = $drafts->values()->map(fn (CampaignAd $ad, int $index): array => [
            'value' => (string) $ad->getKey(),
            'label' => sprintf('Use variation %d only', $index + 1),
            'hint' => $ad->headline,
            'sends' => sprintf('Use variation %d only', $index + 1),
        ])->all();

        if ($drafts->count() > 1) {
            $label = sprintf('Use all %d variations as separate ads', $drafts->count());
            $options[] = [
                'value' => self::USE_ALL.self::SEPARATOR.$first->getKey(),
                'label' => $label,
                'sends' => $label,
            ];
        }
        $options[] = [
            'value' => self::REGENERATE.self::SEPARATOR.$first->getKey(),
            'label' => 'Regenerate ad-copy',
            'sends' => 'Regenerate ad-copy. Ask what these ads should highlight first, then write three fresh variations after I choose.',
        ];
        $options[] = [
            'value' => '__custom__'.self::SEPARATOR.$first->getKey(),
            'label' => 'Write custom ad copy',
            'sends' => 'Write custom ad copy.',
        ];

        $this->choices->offerAdCopySelection(
            options: $options,
            limits: $this->platforms->for($campaign)->copyLimits(),
        );

        return $this->json(['ok' => true, 'variations' => $drafts->count(),
            'note' => 'Copy choices are on screen. Wait for the user before changing or publishing ads.']);
    }

    /**
     * @param  list<string>  $headlines
     * @param  list<string>  $bodies
     */
    private function offer(Campaign $campaign, CampaignAd $ad, int $index, array $headlines, array $bodies): Stringable|string
    {
        $bodyLabel = self::BODY_LABEL[$campaign->platform] ?? 'body copy';

        if ($headlines !== []) {
            $this->choices->offer(
                field: 'ad_headline',
                question: sprintf('Which headline should variation %d use?', $index),
                options: $this->options($index, $headlines, $ad->headline, 'headline'),
                allowOther: true,
            );
        }

        if ($bodies !== []) {
            $this->choices->offer(
                field: 'ad_primary_text',
                question: sprintf('Which %s should variation %d use?', $bodyLabel, $index),
                options: $this->options($index, $bodies, $ad->primary_text, $bodyLabel),
                allowOther: true,
            );
        }

        return $this->json([
            'ok' => true,
            'ad' => $index,
            'offered' => ['headlines' => count($headlines), 'primary_texts' => count($bodies)],
            'note' => 'The options are on screen. Say one short line and wait; do not restate them.',
        ]);
    }

    /**
     * @param  list<string>  $candidates
     * @return list<array<string, string>>
     */
    private function options(int $index, array $candidates, ?string $current, string $what): array
    {
        $options = array_map(fn (string $text): array => array_filter([
            'value' => $index.self::SEPARATOR.$text,
            'label' => $text,
            'badge' => $text === $current ? 'Current' : null,
            'sends' => sprintf('Use "%s" as the %s for variation %d', $text, $what, $index),
        ]), $candidates);

        // Offered beside the alternatives rather than left to be typed, because
        // asking for different wording in prose is what produced a whole new set
        // of ads and lost the variations already approved.
        $options[] = [
            'value' => $index.self::SEPARATOR.self::REGENERATE,
            'label' => 'Write me different options',
            'sends' => sprintf('Write me different %s options for variation %d', $what, $index),
        ];

        return $options;
    }

    /**
     * @param  Collection<int, CampaignAd>  $ads
     */
    private function apply(Campaign $campaign, $ads, string $field, string $raw): Stringable|string
    {
        [$index, $text] = $this->split($raw);

        if (! $ad = $ads->get($index - 1)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('There is no variation %d. The campaign has %d.', $index, $ads->count()),
            ]);
        }

        // A request for different options is not a value to store. Refused so
        // the sentence reaches the model, which writes a fresh set and offers
        // it through this tool again.
        if ($text === self::REGENERATE) {
            return $this->json([
                'ok' => false,
                'error' => 'That is a request for different options, not a choice.',
                'note' => sprintf(
                    'Write three or four new %s options for variation %d, different from the ones just offered, '
                    .'and call choose_ad_copy with them. Change nothing else.',
                    $field === 'headline' ? 'headline' : 'body copy',
                    $index,
                ),
            ]);
        }

        if (trim($text) === '') {
            return $this->json(['ok' => false, 'error' => 'That is empty. Give the wording to use.']);
        }

        $ad->update([$field => trim($text)]);

        // Recorded against the campaign because that is what the panel reads,
        // and the point of the record is that the line was chosen by the buyer
        // rather than written for them.
        $this->workspace->recordSource($campaign, $field, ArtifactFieldSource::USER_STATED);

        return $this->json([
            'ok' => true,
            'ad' => $index,
            $field => trim($text),
        ]);
    }

    /**
     * Every headline and description on screen, each with a checkbox.
     *
     * Two questions rather than one, grouped so they share a screen: a headline
     * and a description are different lengths, different limits and different
     * jobs, and a single list of 19 things mixes them up.
     *
     * They arrive ticked. The copy was written to be used, so the default is to
     * use it, and the buyer unticks what they do not want - 15 clicks to keep
     * what you already have would be a worse screen than the one this replaces.
     *
     * The bounds are Google's and are stated rather than assumed: 3 to 15
     * headlines, 2 to 4 descriptions, confirmed against the API, which refuses
     * a fifth description with TOO_MANY. Which is also why the feedback asking
     * for five is not what got built.
     *
     * @param  Collection<int, CampaignAd>  $drafts
     */
    private function offerGoogleCopyLines(Campaign $campaign, Collection $drafts): Stringable|string
    {
        $headlines = $this->distinctLines($drafts, 'headline');
        $descriptions = $this->distinctLines($drafts, 'description', 'primary_text');

        if ($headlines === [] && $descriptions === []) {
            return $this->json(['ok' => false, 'error' => 'The draft ad has no copy to review.']);
        }

        // Regenerate stays on the screen beside the checkboxes. Narrowing a set
        // and replacing it are different wants, and a buyer who dislikes all
        // twelve headlines should not have to untick eleven of them to say so.
        //
        // Optional, because it is an action rather than an answer. Grouped
        // questions all have to be answered before Continue lights up, so
        // without this a buyer who had picked nine headlines and two
        // descriptions was still held until they pressed Regenerate - which
        // discarded the copy, wrote a new set and asked the same three
        // questions again, round and round.
        $this->choices->offerAdCopySelection(
            options: [[
                'value' => self::REGENERATE.self::SEPARATOR.$drafts->first()->getKey(),
                'label' => 'Regenerate ad-copy',
                'sends' => 'Regenerate ad-copy. Ask what these ads should highlight first, then write three fresh variations after I choose.',
            ]],
            limits: $this->platforms->for($campaign)->copyLimits(),
            optional: true,
        );

        $kept = (array) ($campaign->meta['google_copy_lines'] ?? []);
        $keptHeadlines = (array) ($kept['headlines'] ?? []);
        $keptDescriptions = (array) ($kept['descriptions'] ?? []);

        $option = static fn (string $text, int $limit, array $kept): array => [
            'value' => $text,
            'label' => $text,
            // The count is the thing a buyer checks on a 30 character headline,
            // and Google refuses the ad rather than trimming it.
            'hint' => mb_strlen($text).'/'.$limit.' characters',
            // Nothing chosen yet means everything is in, which is what the ad
            // would have published as before this screen existed.
            'selected' => $kept === [] || in_array($text, $kept, true),
            'sends' => 'Keep the line: '.$text,
        ];

        $this->choices->offer(
            field: 'google_headlines',
            question: sprintf(
                'Which headlines should the ad use? Google needs %d to %d and mixes them itself.',
                GoogleRules::MIN_HEADLINES,
                GoogleRules::MAX_HEADLINES,
            ),
            options: array_map(
                fn (string $text): array => $option($text, GoogleRules::HEADLINE_LIMIT, $keptHeadlines),
                $headlines,
            ),
            multiple: true,
        );

        $this->choices->offer(
            field: 'google_descriptions',
            question: sprintf(
                'And which descriptions? Google needs %d to %d.',
                GoogleRules::MIN_DESCRIPTIONS,
                GoogleRules::MAX_DESCRIPTIONS,
            ),
            options: array_map(
                fn (string $text): array => $option($text, GoogleRules::DESCRIPTION_LIMIT, $keptDescriptions),
                $descriptions,
            ),
            multiple: true,
        );

        // Sitelinks and callouts, offered rather than attached.
        //
        // Unticked, unlike the copy above. The copy was written for this ad so
        // the default is to use it; these are read off the landing page, and
        // the whole complaint about them was "not sure from where these got
        // generated" after a live ad went out carrying "Login to continue" and
        // a stock ticker. Something lifted off a page is a suggestion until
        // somebody says otherwise, so it starts off.
        //
        // Optional, so they never hold up Continue.
        $assets = app(GoogleAdAssets::class);
        $analysis = $campaign->brief?->pageAnalysis();
        $approved = (array) ($campaign->meta['google_ad_assets'] ?? []);
        $sitelinks = $assets->sitelinksFor($analysis);
        $callouts = $assets->calloutsFor($analysis);

        if ($sitelinks !== []) {
            $this->choices->offer(
                field: 'google_sitelinks',
                question: 'Any of these worth adding as sitelinks? They are links this page has to your own site.',
                options: array_map(static fn (array $sitelink): array => [
                    'value' => $sitelink['text'],
                    'label' => $sitelink['text'],
                    'hint' => $sitelink['final_url'],
                    'selected' => in_array($sitelink['text'], (array) ($approved['sitelinks'] ?? []), true),
                    'sends' => 'Add the sitelink '.$sitelink['text'],
                ], $sitelinks),
                multiple: true,
                optional: true,
            );
        }

        if ($callouts !== []) {
            $this->choices->offer(
                field: 'google_callouts',
                question: 'And any of these as callouts? They are short claims taken from the page.',
                options: array_map(static fn (string $callout): array => [
                    'value' => $callout,
                    'label' => $callout,
                    'hint' => mb_strlen($callout).'/'.GoogleAdAssets::CALLOUT_LIMIT.' characters',
                    'selected' => in_array($callout, (array) ($approved['callouts'] ?? []), true),
                    'sends' => 'Add the callout '.$callout,
                ], $callouts),
                multiple: true,
                optional: true,
            );
        }

        // The snippet is one thing rather than a list, so approving it is a
        // single yes. Offered the same way and just as optional: without a
        // question it could never be approved, and the publisher sends only
        // what was - which would have left the feature permanently off.
        $snippet = $assets->structuredSnippetFor($analysis, $campaign->meta['google_snippet_header'] ?? null);

        if ($snippet !== null) {
            $this->choices->offer(
                field: 'google_structured_snippet',
                question: sprintf('Add this %s snippet to the ad?', $snippet['header']),
                options: [[
                    'value' => 'yes',
                    'label' => $snippet['header'].': '.implode(', ', $snippet['values']),
                    'hint' => count($snippet['values']).' values, taken from the page',
                    'selected' => ($approved['structured_snippet'] ?? false) === true,
                    'sends' => 'Add the '.$snippet['header'].' structured snippet',
                ]],
                multiple: true,
                optional: true,
            );
        }

        return $this->json([
            'ok' => true,
            'headlines' => $headlines,
            'descriptions' => $descriptions,
            'sitelinks_offered' => array_column($sitelinks, 'text'),
            'callouts_offered' => $callouts,
            'structured_snippet_offered' => $snippet,
            'note' => sprintf(
                'All %d headlines and %d descriptions are on screen with checkboxes, already ticked. '
                .'Say one short line and wait for the user to untick what they do not want. Do not list '
                .'the copy back to them: they can see it.%s',
                count($headlines),
                count($descriptions),
                ($sitelinks !== [] || $callouts !== [])
                    ? ' Sitelinks and callouts read off the page are offered unticked below; nothing is '
                        .'published unless the user ticks it, so do not describe them as added.'
                    : '',
            ),
        ]);
    }

    /**
     * Record which written lines the ad should use.
     *
     * Recorded, not applied. The lines live on the draft ad rows and the
     * publisher reads the selection when it assembles the responsive search ad,
     * so unticking a headline does not destroy it: the buyer can tick it again
     * next turn, which is the whole difference between this and "regenerate".
     *
     * Counts are checked here rather than at publish. Google refuses an ad with
     * two headlines outright, and meeting that refusal after the campaign and
     * the budget already exist is the expensive way to find out.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @param  array<string, mixed>  $arguments
     */
    private function keepGoogleCopyLines(Campaign $campaign, Collection $ads, array $arguments): Stringable|string
    {
        if ($campaign->platform !== 'google') {
            return $this->json([
                'ok' => false,
                'error' => 'Choosing individual headlines and descriptions is a Google responsive search ad. '
                    .'On other platforms each variation is its own ad, so choose a variation instead.',
            ]);
        }

        $drafts = $this->draftsOf($ads);
        $written = [
            'headlines' => $this->distinctLines($drafts, 'headline'),
            'descriptions' => $this->distinctLines($drafts, 'description', 'primary_text'),
        ];

        $bounds = [
            'headlines' => [GoogleRules::MIN_HEADLINES, GoogleRules::MAX_HEADLINES],
            'descriptions' => [GoogleRules::MIN_DESCRIPTIONS, GoogleRules::MAX_DESCRIPTIONS],
        ];

        $kept = (array) ($campaign->meta['google_copy_lines'] ?? []);

        foreach (['headlines' => 'use_headlines', 'descriptions' => 'use_descriptions'] as $key => $argument) {
            if (! array_key_exists($argument, $arguments)) {
                continue;
            }

            $chosen = array_values(array_unique(array_filter(
                array_map(static fn (mixed $line): string => trim((string) $line), (array) $arguments[$argument]),
                static fn (string $line): bool => $line !== '',
            )));

            // Chosen from what is on screen, so a line nobody wrote cannot
            // arrive here as a selection. New wording goes through write_ad_copy
            // or the headline question, both of which record who wrote it.
            $unknown = array_values(array_diff($chosen, $written[$key]));

            if ($unknown !== []) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf(
                        'These are not lines the draft ad holds, so nothing changed: %s',
                        implode(' | ', $unknown),
                    ),
                    'note' => 'Offer the copy again with offer_selection=true rather than inventing lines.',
                ]);
            }

            [$least, $most] = $bounds[$key];

            if (count($chosen) < $least || count($chosen) > $most) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf(
                        'A responsive search ad takes %d to %d %s, and %d %s chosen, so nothing changed.',
                        $least,
                        $most,
                        $key,
                        count($chosen),
                        count($chosen) === 1 ? 'was' : 'were',
                    ),
                ]);
            }

            $kept[$key] = $chosen;
        }

        $campaign->update(['meta' => [...(array) $campaign->meta, 'google_copy_lines' => $kept]]);
        $this->workspace->recordSource($campaign, 'ad_copy', ArtifactFieldSource::USER_STATED);

        return $this->json([
            'ok' => true,
            'headlines' => $kept['headlines'] ?? $written['headlines'],
            'descriptions' => $kept['descriptions'] ?? $written['descriptions'],
            'note' => 'Say how many of each the ad will use and move on. The lines are on screen already.',
        ]);
    }

    /**
     * Record which page-derived ad assets the buyer approved.
     *
     * An empty list is a real answer - "none of these" - so unlike the copy
     * lines there is no minimum and no fallback. GooglePublisher sends only
     * what is recorded here, so an ad with nothing approved simply carries no
     * sitelinks, which is what every Google ad this product published before
     * the feature existed did.
     *
     * @param  array<string, mixed>  $arguments
     */
    private function keepGoogleAdAssets(Campaign $campaign, array $arguments): Stringable|string
    {
        if ($campaign->platform !== 'google') {
            return $this->json([
                'ok' => false,
                'error' => 'Sitelinks and callouts are Google ad assets. Other platforms have no equivalent here.',
            ]);
        }

        $assets = app(GoogleAdAssets::class);
        $analysis = $campaign->brief?->pageAnalysis();
        $offered = [
            'sitelinks' => array_column($assets->sitelinksFor($analysis), 'text'),
            'callouts' => $assets->calloutsFor($analysis),
        ];

        $approved = (array) ($campaign->meta['google_ad_assets'] ?? []);

        foreach (['sitelinks' => 'use_sitelinks', 'callouts' => 'use_callouts'] as $key => $argument) {
            if (! array_key_exists($argument, $arguments)) {
                continue;
            }

            $chosen = array_values(array_unique(array_filter(
                array_map(static fn (mixed $line): string => trim((string) $line), (array) $arguments[$argument]),
                static fn (string $line): bool => $line !== '',
            )));

            // Only what was offered. A sitelink invented here would be
            // published copy nobody wrote, which is the whole defect.
            $unknown = array_values(array_diff($chosen, $offered[$key]));

            if ($unknown !== []) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf(
                        'These were not offered as %s, so nothing changed: %s',
                        $key,
                        implode(' | ', $unknown),
                    ),
                    'note' => 'Offer the copy again with offer_selection=true rather than inventing assets.',
                ]);
            }

            $approved[$key] = $chosen;
        }

        if (array_key_exists('use_structured_snippet', $arguments)) {
            // One snippet, so approving it is a single yes - but it can arrive
            // three ways: as a list from the checkbox, as a boolean from the
            // model's schema, or as a word. An empty list is the buyer
            // unticking it, which is a real "no".
            $wanted = $arguments['use_structured_snippet'];

            $approved['structured_snippet'] = match (true) {
                is_array($wanted) => $wanted !== [],
                is_bool($wanted) => $wanted,
                default => filter_var($wanted, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) ?? filled($wanted),
            };
        }

        $campaign->update(['meta' => [...(array) $campaign->meta, 'google_ad_assets' => $approved]]);
        $this->workspace->recordSource($campaign, 'ad_copy', ArtifactFieldSource::USER_STATED);

        return $this->json([
            'ok' => true,
            'sitelinks' => $approved['sitelinks'] ?? [],
            'callouts' => $approved['callouts'] ?? [],
            'structured_snippet' => ($approved['structured_snippet'] ?? false) === true,
            'note' => 'Say how many of each the ad will carry. None is a normal answer.',
        ]);
    }

    /**
     * The distinct lines across the draft variations, in the order written.
     *
     * A Google responsive search ad is assembled from several ad rows, one
     * headline each with the descriptions pooled, so the set the buyer is
     * choosing from is spread across rows rather than held on one.
     *
     * @param  Collection<int, CampaignAd>  $drafts
     * @return list<string>
     */
    private function distinctLines(Collection $drafts, string ...$fields): array
    {
        return $drafts
            ->flatMap(fn (CampaignAd $ad): array => array_map(
                fn (string $field): ?string => $ad->{$field},
                $fields,
            ))
            ->filter(fn (?string $text): bool => filled($text))
            ->map(fn (string $text): string => trim($text))
            ->unique()
            ->values()
            ->all();
    }

    /**
     * The unpublished variations, in the order they were offered.
     *
     * @param  Collection<int, CampaignAd>  $ads
     * @return Collection<int, CampaignAd>
     */
    private function draftsOf(Collection $ads): Collection
    {
        return $ads->filter(fn (CampaignAd $ad): bool => $ad->external_ad_id === null)->values();
    }

    /**
     * The nth variation the buyer was shown, counting from one.
     *
     * Refused outright when the drafts span more than one ad set, because then
     * "variation 2" has no single meaning and the single action below deletes
     * every other draft in the set. Guessing there would delete the wrong ads,
     * which is worse than asking the buyer to click.
     *
     * @param  Collection<int, CampaignAd>  $ads
     */
    private function byOrdinal(Campaign $campaign, Collection $ads, int $ordinal): ?CampaignAd
    {
        if ($ordinal < 1) {
            return null;
        }

        $drafts = $this->draftsOf($ads);

        $adSets = $drafts
            ->map(fn (CampaignAd $ad): mixed => $ad->ad_set_id ?? $campaign->primaryAdSet?->id)
            ->unique();

        if ($adSets->count() > 1) {
            return null;
        }

        return $drafts->get($ordinal - 1);
    }

    private function selectVariations(
        Campaign $campaign,
        Collection $ads,
        string $selection,
        string $customHeadline = '',
        string $customPrimaryText = '',
    ): Stringable|string {
        $parts = explode(self::SEPARATOR, $selection, 2);
        $action = count($parts) === 2 ? $parts[0] : 'single';
        $sourceId = count($parts) === 2 ? $parts[1] : $selection;

        if (! in_array($action, ['single', self::USE_ALL, self::REGENERATE, '__custom__'], true) || ! ctype_digit($sourceId)) {
            return $this->json(['ok' => false, 'error' => 'That ad-copy selection is not valid.']);
        }

        $source = $ads->first(fn (CampaignAd $ad): bool => (int) $ad->getKey() === (int) $sourceId
            && $ad->external_ad_id === null);

        // A click sends the ad's id; a person says "variation 1".
        //
        // Everything else in this file counts variations from one - the ad
        // argument is $ads->get($index - 1), and the questions it asks read
        // "Which headline should variation %d use?" - so the chat prints the
        // choices as 1. 2. 3. and that is the number the buyer repeats back.
        // This one branch read the same digit as a primary key, so "Use
        // variation 1 only to create one ad" looked for the ad whose id is 1,
        // found nothing on a campaign whose only ad is 269, and answered "That
        // ad-copy variation is no longer available". Nothing had gone away; it
        // had never existed. Dev server, 8 Oct, campaign 175.
        //
        // The id is tried first and still wins, because that is what the buttons
        // send and they are unambiguous. The ordinal is only a fallback, so no
        // click changes meaning.
        //
        // And only when the number matches no ad on this campaign at all. A
        // published ad's own id must stay refused rather than be re-read as a
        // position: the single action below deletes every other draft in the ad
        // set, so reinterpreting a number that already means something would
        // delete ads the buyer never pointed at. The first version of this did
        // exactly that, and test_stale_or_published_variations_cannot_be_selected
        // caught it.
        $claimed = $ads->contains(fn (CampaignAd $ad): bool => (int) $ad->getKey() === (int) $sourceId);

        if ($source === null && ! $claimed) {
            $source = $this->byOrdinal($campaign, $ads, (int) $sourceId);
        }

        if ($source === null) {
            $drafts = $this->draftsOf($ads);

            return $this->json([
                'ok' => false,
                // Said as the sibling error twenty lines up says it, rather than
                // implying something was withdrawn.
                'error' => $drafts->isEmpty()
                    ? 'There are no draft variations to choose from. Call write_ad_copy first.'
                    : sprintf(
                        'There is no variation %d. There %s %d to choose from.',
                        (int) $sourceId,
                        $drafts->count() === 1 ? 'is' : 'are',
                        $drafts->count(),
                    ),
            ]);
        }

        $adSetId = $source->ad_set_id ?? $campaign->primaryAdSet->id;
        $matchingDrafts = $ads->filter(fn (CampaignAd $ad): bool => ($ad->ad_set_id ?? $campaign->primaryAdSet->id) === $adSetId
            && $ad->external_ad_id === null);

        if ($action === self::REGENERATE) {
            $campaign->update(['meta' => [...(array) $campaign->meta, 'copy_regeneration' => [
                'ad_set_id' => $adSetId, 'awaiting_emphasis' => true,
            ]]]);
            $this->workspace->forgetSources($campaign, 'copy_emphasis', 'copy_selection_adset_'.$adSetId);
            $this->choices->offerCopyEmphasis();

            return $this->json([
                'ok' => true,
                'note' => sprintf('The highlight question is on screen. Wait for the user to choose, then call write_ad_copy with three fresh variations and ad_set_id %d. Offer the same variation-selection card again and wait; do not publish yet.', $adSetId),
            ]);
        }

        if ($action === '__custom__') {
            $headline = trim($customHeadline);
            $primaryText = trim($customPrimaryText);
            $limits = $this->platforms->for($campaign)->copyLimits();

            if ($campaign->platform === 'google') {
                return $this->json(['ok' => false, 'error' => 'Google Search needs its headline variations together for one responsive ad.']);
            }

            if ($headline === '' || $primaryText === '') {
                return $this->json(['ok' => false, 'error' => 'Enter both a headline and primary text for your ad.']);
            }

            foreach (['headline' => $headline, 'primary_text' => $primaryText] as $field => $text) {
                if (mb_strlen($text) > ($limits[$field] ?? PHP_INT_MAX)) {
                    return $this->json(['ok' => false, 'error' => sprintf(
                        '%s is too long. The limit is %d characters.',
                        ucfirst(str_replace('_', ' ', $field)),
                        $limits[$field],
                    )]);
                }
            }

            DB::transaction(function () use ($campaign, $matchingDrafts, $source, $headline, $primaryText): void {
                $source->update(['headline' => $headline, 'primary_text' => $primaryText]);
                $campaign->ads()
                    ->whereKey($matchingDrafts->modelKeys())
                    ->whereKeyNot($source->id)
                    ->whereNull('external_ad_id')
                    ->delete();
            });
        }

        if ($action === 'single' && $campaign->platform === 'google') {
            return $this->json(['ok' => false, 'error' => 'Google Search needs the headline variations together for one responsive search ad.']);
        }

        if ($action === 'single') {
            DB::transaction(function () use ($campaign, $matchingDrafts, $source): void {
                $campaign->ads()
                    ->whereKey($matchingDrafts->modelKeys())
                    ->whereKeyNot($source->id)
                    ->whereNull('external_ad_id')
                    ->delete();
            });
        }

        $this->workspace->recordSource($campaign, 'ads', ArtifactFieldSource::USER_STATED);
        $this->workspace->recordSource(
            $campaign,
            'copy_selection_adset_'.$adSetId,
            ArtifactFieldSource::USER_STATED,
        );

        return $this->json([
            'ok' => true,
            'selected_ads' => in_array($action, ['single', '__custom__'], true) ? 1 : $matchingDrafts->count(),
            'note' => in_array($action, ['single', '__custom__'], true)
                ? 'Only the selected draft variation remains in this ad set, with its creative attached. Publish one ad.'
                : ($campaign->platform === 'google'
                    ? 'Keep all headline and description variations together for one responsive search ad.'
                    : 'Keep all selected variations as distinct ads in this ad set, with their creatives attached.'),
        ]);
    }

    /**
     * @return array{int, string}
     */
    private function split(string $raw): array
    {
        $at = strpos($raw, self::SEPARATOR);

        // Typed rather than clicked. "Write my own" sends the wording with no
        // index in front of it, and the first variation is the one being
        // offered unless the model said otherwise.
        if ($at === false || ! ctype_digit(substr($raw, 0, $at))) {
            return [1, $raw];
        }

        return [(int) substr($raw, 0, $at), substr($raw, $at + strlen(self::SEPARATOR))];
    }

    /**
     * @param  mixed  $values
     * @return list<string>
     */
    private function clean($values): array
    {
        return collect(is_array($values) ? $values : [])
            ->map(fn ($v): string => trim((string) $v))
            ->filter()
            ->unique()
            ->values()
            ->all();
    }
}
