<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Objectives;
use App\Campaigns\Platforms\GoogleRules;
use App\Campaigns\Platforms\Platforms;
use App\Models\ArtifactFieldSource;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignAdSet;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Collection;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Write the ads for every campaign on this brief.
 *
 * Replaces the existing set rather than appending, so re-running after an edit
 * does not quietly double the number of ads. Assets are paired round robin, so
 * three copy variations over one image still ship three ads that differ by copy.
 *
 * Replaces the unpublished ones. An ad that is live on Meta cannot be rewritten
 * - a creative there is immutable, and our delete is local only - so deleting
 * its row left the ad running with nothing pointing at it, which is how a
 * campaign ends up with ads nobody here can pause. New copy on a live campaign
 * is therefore additional ads, which is what add_ads sends.
 *
 * Scoped to one ad set, the first unless another is named. A campaign can hold
 * several since add_ad_set, and rewriting the copy for a second audience must
 * not clear the first one's.
 *
 * Written once for all of them, not just the one in focus. Copy is the last
 * thing a campaign needs and the only shared answer that was still per campaign,
 * so on a two-platform brief every "write the ad copy" landed on whichever tab
 * the buyer happened to be looking at. Seen on dev on 23 Sep: a Meta and Google
 * conversation where Google got three ads and Meta finished with none, and the
 * chat called it ready.
 *
 * The platforms do not accept the same text, and for a while every platform got
 * the same text anyway. Meta allows a 40 character headline, Google 30,
 * LinkedIn 70; the body is 125, 90 and 600. One set of copy for the brief had
 * to clear all of them at once, so a three-platform brief was written to
 * Google's 30 and 90 and the other two were handed copy two thirds shorter than
 * they would take. It published, and it wasted most of the room Meta and
 * LinkedIn give you.
 *
 * So a variation can name its platform and is then held to that platform's
 * limits alone. A variation with no platform is still shared, still has to fit
 * the tightest of the campaigns receiving it, and is still the right answer for
 * a brief on one platform or for copy that genuinely reads the same everywhere.
 * Each platform's own limits come back on every call, so the next one can use
 * the room rather than guess at it.
 */
class WriteAdCopy implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'Write one or more ad variations for every campaign in this conversation that '
            .'shares a brief, not only the one in focus. Replaces any existing ads. Write the '
            .'copy yourself rather than asking the user for it. Set platform on a variation to '
            .'write copy for that platform alone, which is worth doing whenever they have '
            .'different limits: a variation with no platform goes everywhere and must fit the '
            .'tightest of them. Copy over a limit is refused rather than truncated, and the '
            .'result reports every platform\'s limits.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ads' => $schema->array()->items(
                $schema->object([
                    // A flat list with the platform on each entry, rather than
                    // an object keyed by platform. The keys would have to be
                    // enumerated from config to be declarable, and Gemini
                    // rejects the whole request over one loose array schema, so
                    // the shape that cannot go wrong is the one worth having.
                    'platform' => $schema->string()->description(
                        'Which platform this variation is for, for example "meta" or "google". '
                        .'Omit to use the same variation on every platform in this conversation, '
                        .'which then has to fit the tightest of their limits.'
                    ),
                    'headline' => $schema->string()->description('Short headline. The limit differs by platform.')->required(),
                    'primary_text' => $schema->string()->description('The main body copy.')->required(),
                    'description' => $schema->string()->description('Optional supporting line.'),
                    'cta' => $schema->string()->description('One of '.implode(', ', Objectives::CALLS_TO_ACTION).'.')->required(),
                ])
            )->description('The ad variations to write. Meta\'s shape: one headline, body and '
                .'call to action each. On Google use headlines and descriptions instead.'),
            'headlines' => $schema->array()->items($schema->string())
                ->description('Google only, and the shape Google actually takes: a pool of 3 to 15 '
                    .'headlines of at most 30 characters, which Google mixes per auction into one '
                    .'responsive search ad. Write the full pool rather than the minimum - three '
                    .'headlines give the auction almost nothing to combine.'),
            'descriptions' => $schema->array()->items($schema->string())
                ->description('Google only. 1 to 4 descriptions of at most 90 characters, mixed with '
                    .'the headlines into the same responsive search ad.'),
            'path1' => $schema->string()
                ->description('Google only, and only when the user has asked for a display path. '
                    .'The text shown after the domain, at most 15 characters. It is published ad '
                    .'copy and it is not part of the real URL, so do not invent one: leave both '
                    .'paths out unless the user named the words they want there.'),
            'path2' => $schema->string()
                ->description('Google only. Second display path, at most 15 characters. Same rule as '
                    .'path1: only when the user asked for it.'),
            'ad_set_id' => $schema->integer()
                ->description('Which ad set these ads belong to. Omit for the campaign\'s first ad set, '
                    .'which is what "the campaign" means unless the user is working on one they added '
                    .'with add_ad_set. Only that ad set\'s unpublished ads are replaced.'),
            'emphasis' => $schema->string()
                ->description('What the user chose or typed for the ads to highlight. Never invent one.'),
            'offer_emphasis' => $schema->boolean()
                ->description('Internal flow action: offer the single ad-highlight question before writing copy.'),
            'promotion_details' => $schema->string()->description('User-provided promotion or discount, including any eligibility and expiry terms. Never invent an offer. __change_highlight returns to the highlight chooser.'),
        ];
    }

    /**
     * Which ad set this copy is for.
     *
     * Null for an id belonging to another campaign, which is refused rather than
     * quietly redirected to the first ad set: writing somebody's ads into the
     * wrong audience is worse than failing to write them.
     *
     * A campaign always has a first ad set, so the unstated case is never
     * ambiguous.
     */
    private function adSetFor(Campaign $campaign, mixed $id): ?CampaignAdSet
    {
        if (blank($id)) {
            return $campaign->primaryAdSet;
        }

        return $campaign->adSets()->whereKey((int) $id)->first();
    }

    /**
     * The ads this copy replaces: unpublished, and belonging to this ad set.
     *
     * ad_set_id is null on every ad written before ad sets were rows, and those
     * were all in the campaign's only ad set, so the first ad set answers for
     * them. Reading null as "no ad set" instead would leave them behind for ever
     * and add a second set beside them on every rewrite.
     *
     * @return Collection<int, CampaignAd>
     */
    private function draftsOf(Campaign $campaign, CampaignAdSet $adSet): Collection
    {
        return $campaign->ads()
            ->whereNull('external_ad_id')
            ->where(function ($query) use ($campaign, $adSet): void {
                $query->where('ad_set_id', $adSet->id);

                if ($adSet->is($campaign->primaryAdSet)) {
                    $query->orWhereNull('ad_set_id');
                }
            })
            ->orderBy('id')
            ->get();
    }

    /**
     * Whether the arguments carry JSON structure inside their values.
     *
     * A headline is prose. It does not contain `},{`, `}]}` or a bare
     * `field_name:` fragment, and a call to action is a single enum word. When
     * those appear in a value the payload was mangled on the way in, and every
     * field in it is suspect, not just the one that happened to be checked
     * first.
     *
     * @param  list<array<string,mixed>>  $ads
     * @return ?string what was found, for the refusal to quote back
     */
    private function structurallyCorrupt(array $ads): ?string
    {
        foreach ($ads as $index => $ad) {
            if (! is_array($ad)) {
                return sprintf('Ad %d is not an object.', $index + 1);
            }

            foreach (['headline', 'primary_text', 'description', 'cta'] as $field) {
                $value = $ad[$field] ?? null;

                if (! is_string($value)) {
                    continue;
                }

                $fragment = preg_match('/\}\s*,\s*\{|\}\s*\]|\[\s*\{|^\s*,\s*\w+\s*:\s*$|\w+"\s*:/', $value) === 1;

                if ($fragment) {
                    return sprintf(
                        'Ad %d field [%s] contains JSON punctuation: %s.',
                        $index + 1,
                        $field,
                        json_encode(mb_substr($value, 0, 60)),
                    );
                }
            }
        }

        return null;
    }

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

        $ads = (array) ($request->all()['ads'] ?? []);
        $arguments = $request->all();
        $emphasis = trim((string) ($arguments['emphasis'] ?? ''));
        $regeneration = $campaign->meta['copy_regeneration'] ?? null;

        if ($regeneration['awaiting_promotion_details'] ?? false) {
            $details = trim((string) ($arguments['promotion_details'] ?? ''));
            if ($details === '__change_highlight') {
                $regeneration = [...$regeneration, 'awaiting_emphasis' => true, 'awaiting_promotion_details' => false];
                $campaign->update(['meta' => [...(array) $campaign->meta, 'copy_regeneration' => $regeneration]]);
                $this->workspace->forgetSources($campaign, 'copy_emphasis');
                $this->choices->offerCopyEmphasis();

                return $this->json(['ok' => true, 'note' => 'Choose a different highlight before writing new copy.']);
            }
            if ($details === '') {
                $this->offerPromotionDetails();

                return $this->json(['ok' => $ads === [], 'note' => 'Wait for the actual offer details before writing copy. Do not show or select the previous variations.']);
            }
            $regeneration = [...$regeneration, 'awaiting_promotion_details' => false, 'promotion_details' => $details];
            $campaign->update(['meta' => [...(array) $campaign->meta, 'copy_regeneration' => $regeneration]]);
            $this->workspace->recordSource($campaign, 'copy_promotion_details', ArtifactFieldSource::USER_STATED);
            if ($ads === []) {
                return $this->json(['ok' => true, 'promotion_details' => $details,
                    'note' => sprintf('Write three fresh variations using only this offer and the documented campaign facts, with ad_set_id %d. Show the new selection card. Do not invent eligibility or expiry terms.', $regeneration['ad_set_id'])]);
            }
        }

        if (($arguments['offer_emphasis'] ?? false) || ($emphasis === '' && ($regeneration['awaiting_emphasis'] ?? false)) || ($ads === [] && $emphasis === ''
            && ! array_key_exists('copy_emphasis', $this->workspace->sourcesFor($campaign)))) {
            $this->choices->offerCopyEmphasis();

            return $this->json(['ok' => true, 'note' => 'The highlight question is on screen. Wait for the user before writing copy.']);
        }

        if ($ads === [] && $emphasis !== '') {
            $this->workspace->recordSource($campaign, 'copy_emphasis', ArtifactFieldSource::USER_STATED);
            if ($regeneration !== null) {
                $needsPromotion = $emphasis === 'Special Promotion & Discount';
                $regeneration = [...$regeneration, 'awaiting_emphasis' => false, 'awaiting_promotion_details' => $needsPromotion];
                $campaign->update(['meta' => [...(array) $campaign->meta,
                    'copy_regeneration' => $regeneration]]);
                if ($needsPromotion) {
                    $this->offerPromotionDetails();

                    return $this->json(['ok' => true, 'emphasis' => $emphasis,
                        'note' => 'Enter the actual promotion details on screen, or choose a different highlight. Keep existing ads unchanged and do not offer the old variation card.']);
                }
            }

            return $this->json(['ok' => true, 'emphasis' => $emphasis,
                'note' => $regeneration !== null
                    ? sprintf('Highlight recorded. Call write_ad_copy with three fresh variations around it and ad_set_id %d. Show the new variation-selection card.', $regeneration['ad_set_id'])
                    : 'Highlight recorded. Write the variations around it now with write_ad_copy.']);
        }

        // Highlights first, then copy, then the variation choice: one question per step.
        if (collect($this->choices->all())->contains('field', 'copy_emphasis')) {
            return $this->json(['ok' => false, 'error' => 'The highlight question is on screen.',
                'note' => 'Wait for the user to choose what the ads should highlight. Do not write copy in this turn.']);
        }

        if ($emphasis !== '') {
            $this->workspace->recordSource($campaign, 'copy_emphasis', ArtifactFieldSource::USER_STATED);
        } elseif ($this->workspace->wasOffered('copy_emphasis')
            && ! array_key_exists('copy_emphasis', $this->workspace->sourcesFor($campaign))) {
            return $this->json(['ok' => false, 'error' => 'The user has not chosen what the ads should highlight yet.',
                'note' => 'Ask them to pick a highlight on screen. If they typed one, call write_ad_copy again with it in emphasis.']);
        }

        // Google's own shape, taken before Meta's variation model gets a say.
        //
        // A responsive search ad is a pool of up to fifteen headlines and four
        // descriptions that Google mixes per auction. Expressed as Meta
        // variations that is fifteen rows, each carrying a body and a call to
        // action Google has no use for, against a cap of five - so in practice
        // the model wrote three headlines and Google was handed almost nothing
        // to combine. Mohsin's note on 15 Oct was exactly this: "it is giving
        // me meta specific suggestions".
        if ($campaign->platform === 'google'
            && (filled($arguments['headlines'] ?? null) || filled($arguments['descriptions'] ?? null))) {
            return $this->writeGoogleAssets($campaign, $arguments);
        }

        if ($ads === []) {
            return $this->json(['ok' => false, 'error' => 'At least one ad variation is required.']);
        }
        if ($regeneration !== null && count($ads) !== 3) {
            return $this->json(['ok' => false, 'error' => 'Regeneration requires three fresh ad-copy variations. Existing ads were not changed.']);
        }

        // Counted per platform, because that is what the cap means.
        //
        // PublishGate reads it off one campaign's own ads, and this counted the
        // whole submission, so three platforms asking for three variations each
        // came to nine against a limit of five and was refused. The feature
        // exists to write copy per platform and could not be used at three
        // platforms at all: on arb-dev it answered "this campaign group allows
        // five variations total, not nine platform-specific variations" and the
        // buyer fell back to one shared set squeezed to Google's limits.
        //
        // Five ads on one campaign is the thing worth stopping. Five across
        // three campaigns is not the same number and never was.
        $limit = (int) config('platforms.guardrails.max_ads_per_publish');

        $perPlatform = collect($ads)->countBy(fn (array $ad): string => strtolower(trim((string) ($ad['platform'] ?? 'shared'))));

        foreach ($perPlatform as $platform => $count) {
            // Google's variations are the assets of one responsive search ad,
            // not separate ads, so the cap on how many ads one approval may
            // create does not apply to how many headlines it carries.
            $rules = $platform === 'shared' || ! $this->platforms->supports($platform)
                ? null
                : $this->platforms->for($platform);

            if ($rules?->buildsOneAdFromEveryVariation()) {
                continue;
            }

            if ($count > $limit) {
                return $this->json([
                    'ok' => false,
                    'error' => $platform === 'shared'
                        ? sprintf('%d shared variations given, but at most %d may be published to one campaign.', $count, $limit)
                        : sprintf('%d variations given for %s, but at most %d may be published to one campaign.', $count, $platform, $limit),
                ]);
            }
        }

        // Arguments that arrived as broken JSON are named as such.
        //
        // Real payloads from the stored conversations:
        //
        //   "primary_text": "Block pop-ups and annoying ads daily.},{cta:"
        //   "cta": "}]}xsd}"
        //   "headline": ",primary_text:"
        //
        // The model emitted its own delimiters inside the values. This then
        // refused with "[}]}] is not a supported call to action", which sends
        // the model looking for a better call to action when the whole payload
        // is malformed, and it retried a dozen times in one turn, every time.
        // Naming the real problem is what lets it recover on the next attempt
        // rather than the fifteenth.
        if ($corrupt = $this->structurallyCorrupt($ads)) {
            return $this->json([
                'ok' => false,
                'error' => 'These ad arguments did not arrive as valid JSON. '.$corrupt
                    .' Send the ads again as a clean JSON array, with no braces, brackets or field '
                    .'names inside any text value.',
                'note' => 'Do not change the wording to try to fix this and do not retry more than '
                    .'once. If it happens again, write the copy out in the chat and ask the user to '
                    .'confirm it instead.',
            ]);
        }

        foreach ($ads as $index => $ad) {
            foreach (['headline', 'primary_text', 'cta'] as $field) {
                if (blank($ad[$field] ?? null)) {
                    return $this->json(['ok' => false, 'error' => 'Ad '.($index + 1)." is missing {$field}."]);
                }
            }

            // The platform's own list, not one shared constant.
            //
            // This checked Objectives::CALLS_TO_ACTION whatever the campaign ran
            // on, and that constant is Meta's seven. So a LinkedIn ad was
            // accepted with BOOK_TRAVEL, which LinkedIn has no button for, and
            // refused APPLY, REGISTER, REQUEST_DEMO and VIEW_QUOTE, which are
            // four of the ten it does. Either way the copy was agreed and the
            // failure arrived at publish as an enum error.
            //
            // A platform with no buttons at all - Google, whose Search ads carry
            // none - has nothing to check against, so the field is ignored
            // rather than refused.
            $supported = $this->platforms->for($campaign)->callsToAction();

            if ($supported !== [] && ! in_array(strtoupper((string) $ad['cta']), $supported, true)) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('[%s] is not a call to action %s supports.', $ad['cta'], $campaign->platform),
                    'supported' => $supported,
                ]);
            }
        }

        $targets = $this->sharingTheBrief($campaign);

        // Split by platform before anything is checked, because what counts as
        // too long and how many variations are needed are both the platform's
        // answer, not the brief's.
        $shared = array_values(array_filter($ads, fn (array $ad): bool => blank($ad['platform'] ?? null)));

        $byPlatform = [];

        foreach ($ads as $ad) {
            if (filled($key = strtolower(trim((string) ($ad['platform'] ?? ''))))) {
                $byPlatform[$key][] = $ad;
            }
        }

        $unknown = array_diff(array_keys($byPlatform), $targets->pluck('platform')->all());

        if ($unknown !== []) {
            return $this->json([
                'ok' => false,
                'error' => '['.implode(', ', $unknown).'] is not a platform in this conversation.',
                'platforms' => $targets->pluck('platform')->values()->all(),
            ]);
        }

        // Shared copy still has to clear the tightest limit of every campaign
        // that will receive it. Written per platform it only has to clear that
        // one, which is the whole point: 30 characters is Google's answer and
        // was being imposed on Meta's 40 and LinkedIn's 70.
        $sharedTargets = $targets->reject(fn (Campaign $t): bool => isset($byPlatform[$t->platform]));

        foreach ($targets as $target) {
            $group = $byPlatform[$target->platform] ?? $shared;

            if ($group === []) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('No copy was written for %s.', $target->name),
                    'note' => 'Every campaign on this brief needs copy. Write variations for the missing '
                        .'platform, or leave the platform off a variation so it is used everywhere.',
                ]);
            }

            $limits = isset($byPlatform[$target->platform])
                ? $this->platforms->for($target)->copyLimits()
                : $this->tightestLimits($sharedTargets);

            // Google builds one responsive search ad out of the headlines of
            // every ad on the campaign, and refuses it below three. One
            // variation is a perfectly good Meta campaign and an unpublishable
            // Google one, and the refusal arrives at publish, after the
            // campaign and budget exist.
            if (($least = $this->leastVariations(collect([$target]))) > count($group)) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf(
                        '%d variation%s given for %s. A Google Search ad is built from the headlines of '
                        .'all of them and needs at least %d different ones.',
                        count($group),
                        count($group) === 1 ? '' : 's',
                        $this->platforms->for($target)->name(),
                        $least,
                    ),
                    'note' => 'Write the missing variations yourself and call this again with all of them.',
                ]);
            }

            if ($tooLong = $this->overLimit($group, $limits)) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('%s: %s', $this->platforms->for($target)->name(), $tooLong),
                    'limits' => $limits,
                    'note' => 'Rewrite that variation shorter, or give this platform its own variations by '
                        .'setting platform on them. Do not ask the user to shorten it, and do not send it '
                        .'again unchanged: the platform refuses it rather than trimming it.',
                ]);
            }
        }

        // Assets already attached to this conversation, paired round robin.
        $assets = $this->workspace->artifacts(Asset::class)
            ->map(fn ($link) => $link->artifactable)
            ->filter()
            ->values();

        $written = [];

        // An ad set belongs to one campaign, and this writes for every campaign
        // on the brief.
        //
        // Resolved against all of them before anything is written, and then
        // applied only to the one that owns it; the rest take their own first ad
        // set, which is what they would have had anyway. Asking each target in
        // turn instead meant a two-platform brief wrote the copy for whichever
        // campaign owned the ad set and then refused on the next one - a partial
        // write, reported as "that ad set is not part of this campaign" without
        // saying which campaign it meant.
        $requestedAdSet = $regeneration['ad_set_id'] ?? $request->all()['ad_set_id'] ?? null;
        $owner = null;

        if (filled($requestedAdSet)) {
            $owner = $targets->first(
                fn (Campaign $t): bool => $t->adSets()->whereKey((int) $requestedAdSet)->exists(),
            );

            if ($owner === null) {
                return $this->json([
                    'ok' => false,
                    'error' => 'That ad set does not belong to any campaign in this conversation.',
                    'ad_sets' => $targets
                        ->flatMap(fn (Campaign $t): array => $t->adSets()->get(['id', 'position', 'name'])->all())
                        ->all(),
                    'note' => 'Nothing was written. Name one of the ad sets listed, or omit ad_set_id '
                        .'to write for each campaign\'s first ad set.',
                ]);
            }
        }

        foreach ($targets as $target) {
            if ($regeneration !== null && ! $target->is($campaign)) {
                continue;
            }
            $adSet = $this->adSetFor($target, $owner?->is($target) ? $requestedAdSet : null);

            // Every campaign has a first ad set, so this is only reachable if
            // one somehow has none at all.
            if ($adSet === null) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('%s has no ad set to write ads into.', $target->name),
                ]);
            }

            // Only this ad set's unpublished ads, and never the published ones.
            //
            // This replaced every ad on the campaign. On a draft that is right:
            // rewriting the copy before anything exists should leave one set of
            // ads behind. On a published campaign it deleted the rows carrying
            // external_ad_id, so the ads carried on running on Meta - a creative
            // is immutable there, our delete is local - and nothing pointed at
            // them any more: not editable, not pausable, not visible as ours.
            // The same shape as the LinkedIn rollback defect above.
            //
            // Keeping them is also what makes new copy on a live campaign mean
            // what a buyer expects. Meta cannot edit a running ad's words, so
            // the new variations are additional ads, which is exactly what
            // add_ads then sends.
            $replacing = $this->draftsOf($target, $adSet);

            // Remember the pairing before replacing the rows, so rewriting copy
            // does not silently drop creatives the user already chose. Scoped to
            // the rows actually being replaced, or a published ad's asset would
            // be handed to a new draft that has nothing to do with it.
            $previous = $replacing->pluck('asset_id')->all();

            CampaignAd::whereIn('id', $replacing->pluck('id'))->delete();

            foreach ($byPlatform[$target->platform] ?? $shared as $index => $ad) {
                $createdAd = CampaignAd::create([
                    'campaign_id' => $target->id,
                    'ad_set_id' => $adSet->id,
                    'asset_id' => $previous[$index]
                        ?? ($assets->isNotEmpty() ? $assets[$index % $assets->count()]->id : null),
                    'headline' => trim((string) $ad['headline']),
                    'primary_text' => trim((string) $ad['primary_text']),
                    'description' => filled($ad['description'] ?? null) ? trim((string) $ad['description']) : null,
                    'cta' => strtoupper((string) $ad['cta']),
                ]);

            }

            $this->workspace->recordSource($target, 'ads', ArtifactFieldSource::MODEL_INFERRED);

            $live = $target->ads()->whereNotNull('external_ad_id')->count();

            $written[$target->name] = array_filter([
                'platform' => $target->platform,
                'ad_set' => $adSet->name,
                'variations' => $target->ads()->count(),
                // Named so the model does not report a campaign as having more
                // ads than were written, and knows these are additions.
                'already_live' => $live ?: null,
                'own_copy' => isset($byPlatform[$target->platform]),
            ], fn (mixed $value): bool => $value !== null);
        }

        $tailored = collect($written)->where('own_copy', true)->count();

        if ($regeneration !== null && $written !== []) {
            $meta = (array) $campaign->fresh()->meta;
            unset($meta['copy_regeneration']);
            $campaign->update(['meta' => $meta]);
            app(ChooseAdCopy::class)->handle(new Request([
                'offer_selection' => true, 'ad_set_id' => $regeneration['ad_set_id'],
            ]));
        }

        return $this->json(array_filter([
            'ok' => true,
            'campaign_id' => $campaign->id,
            'written' => $written,
            // Each platform's own room, not the tightest of them. Reported so
            // the next call can use it: a model told only the shared limit has
            // no way to know Meta would have taken ten more characters.
            'limits_by_platform' => $targets
                ->mapWithKeys(fn (Campaign $t): array => [$t->platform => $this->platforms->for($t)->copyLimits()])
                ->all(),
            'assets_attached' => $assets->count(),
            // How much room the shared copy is leaving unused, in characters.
            //
            // Telling the model it "could" tailor the copy was not enough: on
            // arb-dev on 25 Sep it was asked outright to give Meta longer
            // headlines and moved to the next step instead, leaving both
            // platforms on the same 18 to 28 characters against Meta's 40.
            // A rule it has to remember loses to the step in front of it, so
            // the cost of not tailoring is measured here and put in the result,
            // where it is a fact about this copy rather than advice.
            'unused_room' => $tailored === count($written) ? null : $this->unusedRoom($sharedTargets),
            'note' => match (true) {
                count($written) === 0 => null,
                $tailored === 0 => 'The same copy was written to every campaign on this brief, so it was '
                    .'held to the tightest limits. Show the variations, then offer the choice card. '
                    .'Explain any platform copy-room note in unused_room briefly.',
                $tailored === count($written) => 'Each platform got its own copy. Show the variations, then offer the choice card.',
                default => 'Some platforms got their own copy and the rest share one set. Show the variations, then offer the choice card.',
            },
        ], fn ($value) => $value !== null));
    }

    private function offerPromotionDetails(): void
    {
        $this->choices->offer(
            field: 'copy_promotion_details',
            question: 'What is the exact promotion or discount, including any eligibility and expiry terms?',
            options: [[
                'value' => '__change_highlight',
                'label' => 'Choose a different highlight',
                'sends' => 'Choose a different ad highlight instead of a promotion.',
            ]],
            allowOther: true,
            otherLabel: 'Enter promotion details',
            otherPlaceholder: 'Offer, eligibility and expiry (if any)',
        );
    }

    /**
     * Room a platform loses by sharing, in characters.
     *
     * The gap between this platform's limit and the tightest limit the shared
     * copy had to clear. Meta allows forty where Google allows thirty, so ten
     * characters of every shared headline are unavailable purely because one
     * set is being written for both.
     *
     * Measured against the constraint, not against the copy. The first version
     * compared the limit to the longest line actually written, which reported
     * Google as having twenty-five characters spare on a fifteen character
     * headline. That is true and useless: the copy was short because somebody
     * wrote it short, not because it was shared, and tailoring would not
     * recover a thing.
     *
     * @param  Collection<int, Campaign>  $sharedTargets
     * @return array<string, array<string, int>>|null
     */
    /**
     * A Google responsive search ad, written as the pool of assets it is.
     *
     * Stored as one row per headline, because that is what GooglePublisher
     * reads: it collects every row's headline into one ad, and every row's
     * description and body into that ad's descriptions. The rows are assets of
     * a single ad rather than ads, which is what
     * PlatformRules::buildsOneAdFromEveryVariation says and what keeps fifteen
     * headlines from being counted against a cap of five ads.
     *
     * primary_text is filled with a real description rather than filler. The
     * publisher reads description and primary_text alike into the ad's
     * descriptions, so anything put there to satisfy a non-null column would
     * have surfaced in the live ad as a description nobody wrote.
     *
     * @param  array<string, mixed>  $arguments
     */
    private function writeGoogleAssets(Campaign $campaign, array $arguments): Stringable|string
    {
        $adSet = $this->adSetFor($campaign, $arguments['ad_set_id'] ?? null);

        if ($adSet === null) {
            return $this->json(['ok' => false, 'error' => 'That ad set is not part of this campaign.']);
        }

        $limits = $this->platforms->for($campaign)->copyLimits();

        $clean = static fn (mixed $value): string => trim(preg_replace('/\s+/u', ' ', (string) $value) ?? '');

        $headlines = collect((array) ($arguments['headlines'] ?? []))->map($clean)->filter()->unique(
            static fn (string $text): string => mb_strtolower($text),
        )->values();
        $descriptions = collect((array) ($arguments['descriptions'] ?? []))->map($clean)->filter()->unique(
            static fn (string $text): string => mb_strtolower($text),
        )->values();

        if ($headlines->count() < GoogleRules::MIN_HEADLINES || $headlines->count() > GoogleRules::MAX_HEADLINES) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%d distinct headline(s) given. A Google responsive search ad takes %d to %d.',
                    $headlines->count(),
                    GoogleRules::MIN_HEADLINES,
                    GoogleRules::MAX_HEADLINES,
                ),
                'note' => 'Write the full pool yourself and call this again. Do not ask the user to '
                    .'write them, and do not send the same ones again with duplicates removed.',
            ]);
        }

        if ($descriptions->isEmpty() || $descriptions->count() > GoogleRules::MAX_DESCRIPTIONS) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%d distinct description(s) given. A Google responsive search ad takes 1 to %d.',
                    $descriptions->count(),
                    GoogleRules::MAX_DESCRIPTIONS,
                ),
            ]);
        }

        // Over the limit Google truncates rather than refusing, so nobody finds
        // out until they read a live ad ending mid-word.
        foreach ([['headline', $headlines], ['description', $descriptions]] as [$field, $values]) {
            if ($over = $values->first(fn (string $text): bool => mb_strlen($text) > $limits[$field])) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('"%s" is %d characters. A Google %s takes %d.', $over, mb_strlen($over), $field, $limits[$field]),
                    'note' => 'Rewrite that one shorter and send the whole pool again.',
                ]);
            }
        }

        $paths = [];

        foreach (['path1', 'path2'] as $path) {
            if (! filled($arguments[$path] ?? null)) {
                continue;
            }

            $value = $clean($arguments[$path]);

            // A display path is not part of the real URL, so a slash in it is
            // the model building a path rather than naming one.
            if (mb_strlen($value) > 15 || str_contains($value, '/')) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf('Display path "%s" must be at most 15 characters and contain no slash.', $value),
                ]);
            }

            $paths[$path] = $value;
        }

        $replacing = $this->draftsOf($campaign, $adSet);
        $previous = $replacing->pluck('asset_id')->all();

        CampaignAd::whereIn('id', $replacing->pluck('id'))->delete();

        foreach ($headlines as $index => $headline) {
            CampaignAd::create([
                'campaign_id' => $campaign->id,
                'ad_set_id' => $adSet->id,
                'asset_id' => $previous[$index] ?? null,
                'headline' => $headline,
                // A real description, never filler: the publisher reads this
                // into the ad's descriptions alongside the description column.
                'primary_text' => $descriptions[$index] ?? $descriptions[0],
                'description' => $descriptions[$index] ?? null,
                // Not nullable, and Google has no buttons - a search ad carries
                // none. Recorded so the column is satisfied, and ignored at
                // publish, which is why nothing asks the buyer for it.
                'cta' => 'LEARN_MORE',
            ]);
        }

        $campaign->update(['meta' => array_filter([
            ...(array) $campaign->meta,
            'google_display_paths' => $paths ?: null,
        ], static fn (mixed $value): bool => $value !== null)]);

        $this->workspace->recordSource($campaign, 'ads', ArtifactFieldSource::MODEL_INFERRED);

        return $this->json(array_filter([
            'ok' => true,
            'platform' => 'google',
            'headlines' => $headlines->all(),
            'descriptions' => $descriptions->all(),
            'display_paths' => $paths ?: null,
            // Shown because it is what the ad actually points at and the buyer
            // has no other place in this step to check it.
            'final_url' => $campaign->landing_url,
            'note' => sprintf(
                'One responsive search ad, built from %d headline(s) and %d description(s) that Google '
                    .'mixes per auction. Say those counts and the final URL rather than reading every '
                    .'line out. There is no call-to-action button on a search ad, so do not offer one.',
                $headlines->count(),
                $descriptions->count(),
            ),
        ], static fn (mixed $value): bool => $value !== null));
    }

    private function unusedRoom(Collection $sharedTargets): ?array
    {
        if ($sharedTargets->count() < 2) {
            return null;
        }

        $tightest = $this->tightestLimits($sharedTargets);
        $room = [];

        foreach ($sharedTargets as $target) {
            foreach ($this->platforms->for($target)->copyLimits() as $field => $max) {
                $lost = $max - ($tightest[$field] ?? $max);

                // A quarter of the tightest allowance, so a real difference
                // like forty against thirty is reported and a couple of
                // characters is not. A note nobody needs is how notes stop
                // being read.
                if ($lost >= (int) ceil(($tightest[$field] ?? $max) / 4)) {
                    $room[$target->platform][$field] = $lost;
                }
            }
        }

        return $room === [] ? null : $room;
    }

    /**
     * Every campaign this copy belongs to.
     *
     * The focused campaign and its brief's others. A campaign with no brief is
     * on its own, which is the case for one started separately later in a
     * conversation, and it keeps its own copy.
     *
     * Live campaigns are left alone: their ads exist on the platform, and
     * replacing the rows here would put our record out of step with what is
     * running without changing anything on the platform.
     *
     * @return Collection<int, Campaign>
     */
    private function sharingTheBrief(Campaign $campaign): Collection
    {
        if ($campaign->brief === null) {
            return collect([$campaign]);
        }

        return $campaign->brief->campaigns()
            ->get()
            ->reject(fn (Campaign $c): bool => $c->isPublished() && $c->isNot($campaign))
            ->values();
    }

    /**
     * The most variations any of these platforms insists on.
     *
     * Only Google asks for more than one, and only because its responsive
     * search ad is assembled from the headlines of every ad on the campaign.
     * Read from GoogleRules rather than written here, so the number lives with
     * the other Google limits.
     *
     * @param  Collection<int, Campaign>  $targets
     */
    private function leastVariations(Collection $targets): int
    {
        $least = 1;

        foreach ($targets as $target) {
            if ($this->platforms->for($target)->key() === 'google') {
                $least = max($least, GoogleRules::MIN_HEADLINES);
            }
        }

        return $least;
    }

    /**
     * The shortest each field may be across the platforms being written to.
     *
     * One piece of copy has to satisfy all of them, so the limit is the
     * tightest, not the focused campaign's. Meta takes a 40 character headline
     * and Google 30; copy written against Meta's limit is refused by Google at
     * publish, after the campaign and its budget already exist.
     *
     * @param  Collection<int, Campaign>  $targets
     * @return array<string, int>
     */
    private function tightestLimits(Collection $targets): array
    {
        $limits = [];

        foreach ($targets as $target) {
            foreach ($this->platforms->for($target)->copyLimits() as $field => $max) {
                $limits[$field] = isset($limits[$field]) ? min($limits[$field], $max) : $max;
            }
        }

        return $limits;
    }

    /**
     * The first variation that would be refused, named precisely.
     *
     * Refused rather than trimmed. Cutting a headline at 30 characters produces
     * copy nobody wrote and nobody approved, which then runs.
     *
     * @param  array<int, array<string, mixed>>  $ads
     * @param  array<string, int>  $limits
     */
    private function overLimit(array $ads, array $limits): ?string
    {
        foreach ($ads as $index => $ad) {
            foreach ($limits as $field => $max) {
                $value = trim((string) ($ad[$field] ?? ''));

                if ($value !== '' && mb_strlen($value) > $max) {
                    return sprintf(
                        'Ad %d\'s %s is %d characters and the limit here is %d: "%s".',
                        $index + 1,
                        str_replace('_', ' ', $field),
                        mb_strlen($value),
                        $max,
                        $value,
                    );
                }
            }
        }

        return null;
    }
}
