<?php

namespace App\Agent;

use App\Agent\Tools\Campaign\ChooseAudienceList;
use App\Agent\Tools\Campaign\TargetLocationList;
use App\Campaigns\Targeting\SearchKeywordSelections;
use Laravel\Ai\Tools\Request as ToolRequest;
use Throwable;

/**
 * Applies an answer the user clicked, without asking the model to interpret it.
 *
 * Every option already carries the value the platform accepts. It was never
 * sent: clicking put a sentence in the composer and the model had to turn that
 * back into an argument. Where the sentence contained the value that worked,
 * and where it did not the model sometimes called the tool with nothing, which
 * re-offered the same question. Clicking "Highest volume" or "Standard tagging"
 * did nothing at all until you clicked it twice. Confirmed in the browser on
 * 16 Sep on both.
 *
 * So the value is now posted and applied here, before the turn runs. The model
 * still sees the message and still replies; it simply no longer decides whether
 * the answer was recorded.
 *
 * This is not a second way into the agent. It runs the same tool objects from
 * the same registry that the model would have called, so the guardrails, the
 * audit log and the workspace are identical. The controller already calls tools
 * directly this way when it has to put options on screen itself.
 */
class Answers
{
    /**
     * Which tool owns each question, and the argument it expects.
     *
     * Keyed by the field name the offering tool passes to Choices::offer(), so
     * the two sides are named the same thing on purpose.
     *
     * The namespace defaults to `campaign`, which is where all of these lived
     * while Meta was the only platform. Google's tools are registered under
     * their own, so the entry has to say which registry name to look for.
     *
     * @var array<string, array{tool: string, argument: string, shape?: string, namespace?: string}>
     */
    private const FIELDS = [
        // Several at once: one brief, a campaign on each platform chosen.
        'platforms' => ['tool' => 'start_campaign', 'argument' => 'platforms', 'shape' => 'list'],
        'platform' => ['tool' => 'start_campaign', 'argument' => 'platform'],
        'ad_account_id' => ['tool' => 'verify_ad_account', 'argument' => 'ad_account_id'],
        'campaign_type' => ['tool' => 'choose_campaign_type', 'argument' => 'campaign_type'],
        'objective' => ['tool' => 'choose_objective', 'argument' => 'objective'],
        'special_ad_categories' => ['tool' => 'declare_ad_category', 'argument' => 'categories', 'shape' => 'list'],
        'page_id' => ['tool' => 'choose_page', 'argument' => 'page_id'],
        'linkedin_lead_form_id' => ['tool' => 'choose_linked_in_resource', 'argument' => 'lead_form_id'],
        'linkedin_conversion_id' => ['tool' => 'choose_linked_in_resource', 'argument' => 'conversion_id'],
        'linkedin_audience_mode' => ['tool' => 'choose_linked_in_resource', 'argument' => 'audience_mode'],
        'linkedin_audience_segment' => ['tool' => 'choose_linked_in_resource', 'argument' => 'review_audience', 'shape' => 'linkedin_audience_review'],
        'linkedin_professional_search' => ['tool' => 'choose_linked_in_resource', 'argument' => 'query'],
        'linkedin_professional_selection' => ['tool' => 'choose_linked_in_resource', 'argument' => 'selection', 'shape' => 'list'],
        'linkedin_audience_remove' => ['tool' => 'choose_linked_in_resource', 'argument' => 'remove', 'shape' => 'list'],
        'linkedin_audience_conflict' => ['tool' => 'choose_linked_in_resource', 'argument' => 'conflict'],
        'linkedin_audience_exclude' => ['tool' => 'choose_linked_in_resource', 'argument' => 'exclude_facet'],
        'linkedin_professional_exclusion' => ['tool' => 'choose_linked_in_resource', 'argument' => 'exclude_selection', 'shape' => 'list'],
        'retry_linkedin_insight_tag' => ['tool' => 'choose_linked_in_resource', 'argument' => 'section', 'shape' => 'linkedin_insight_retry'],
        'pixel_id' => ['tool' => 'choose_pixel', 'argument' => 'pixel_id'],
        'budget_amount' => ['tool' => 'set_campaign_budget', 'argument' => 'amount', 'shape' => 'number'],
        'budget_strategy' => ['tool' => 'set_campaign_budget', 'argument' => 'strategy', 'shape' => 'strategy'],
        // How one total is divided when a brief runs on several platforms.
        'budget_split' => ['tool' => 'split_budget', 'argument' => 'split'],
        'bid_strategy' => ['tool' => 'set_bidding', 'argument' => 'strategy'],
        // The second half of a capped strategy. Applied without naming the
        // strategy: the tool reads the one already on the campaign.
        'bid_amount' => ['tool' => 'set_bidding', 'argument' => 'target_cost'],
        'ends_at' => ['tool' => 'set_schedule', 'argument' => 'ends_at'],
        'countries' => ['tool' => 'set_targeting', 'argument' => 'countries', 'shape' => 'list'],
        'location_scope' => ['tool' => 'choose_location', 'argument' => 'scope'],
        'location_search' => ['tool' => 'choose_location', 'argument' => 'query', 'shape' => 'location_search'],
        // Advanced targeting: the pasted lists, then the reviewed matches to save.
        'location_list' => ['tool' => 'target_location_list', 'argument' => 'lists', 'shape' => 'location_list'],
        'location_list_review' => ['tool' => 'target_location_list', 'argument' => 'selected', 'shape' => 'list'],
        'meta_location' => ['tool' => 'choose_location', 'argument' => 'external_id', 'shape' => 'location_result'],
        'google_location' => ['tool' => 'choose_location', 'argument' => 'external_id', 'shape' => 'location_result'],
        'linkedin_location' => ['tool' => 'choose_location', 'argument' => 'external_id', 'shape' => 'location_result'],
        'google_location_exclude' => ['tool' => 'choose_location', 'argument' => 'external_id', 'shape' => 'location_result'],
        'placements' => ['tool' => 'set_targeting', 'argument' => 'placements', 'shape' => 'list'],
        'devices' => ['tool' => 'set_targeting', 'argument' => 'devices', 'shape' => 'commas'],
        'meta_age_range' => ['tool' => 'set_targeting', 'argument' => 'age_range', 'shape' => 'age_range'],
        'meta_gender' => ['tool' => 'set_targeting', 'argument' => 'genders', 'shape' => 'meta_gender'],
        'meta_audience_mode' => ['tool' => 'set_targeting', 'argument' => 'audience_mode', 'shape' => 'audience_mode'],
        'meta_audience_category' => ['tool' => 'set_targeting', 'argument' => 'audience_category'],
        'meta_audience_facet' => ['tool' => 'set_targeting', 'argument' => 'audience_facet'],
        'meta_detailed_search' => ['tool' => 'set_targeting', 'argument' => 'facet_query'],
        'meta_detailed_selection' => ['tool' => 'set_targeting', 'argument' => 'detailed_ids', 'shape' => 'list'],
        'meta_detailed_remove' => ['tool' => 'set_targeting', 'argument' => 'remove_detailed', 'shape' => 'list'],
        'meta_interest_selection' => ['tool' => 'set_targeting', 'argument' => 'interest_ids', 'shape' => 'interest_options'],
        'meta_retarget_pixel' => ['tool' => 'create_website_audience', 'argument' => 'pixel_id', 'shape' => 'website_pixel'],
        'meta_retarget_event' => ['tool' => 'create_website_audience', 'argument' => 'event_name', 'shape' => 'website_event'],
        'meta_retarget_confirmation' => ['tool' => 'create_website_audience', 'argument' => 'confirm_action', 'shape' => 'website_confirmation'],
        'conversion_event' => ['tool' => 'choose_conversion_event', 'argument' => 'conversion_event'],
        'instagram_account_id' => ['tool' => 'choose_instagram_account', 'argument' => 'instagram_account_id'],
        'utm' => ['tool' => 'set_tracking', 'argument' => 'utm'],
        'creative_ids' => ['tool' => 'import_creatives', 'argument' => 'creative_ids', 'shape' => 'ints'],
        // The button on the ad. Applied to every ad on the campaign,
        // because it describes the offer rather than the variation.
        'cta' => ['tool' => 'choose_call_to_action', 'argument' => 'cta'],
        // Wording picked from the alternatives on screen. The value
        // carries which variation it belongs to, because a click is
        // applied by field name alone and the names are this map.
        'ad_headline' => ['tool' => 'choose_ad_copy', 'argument' => 'headline'],
        'ad_primary_text' => ['tool' => 'choose_ad_copy', 'argument' => 'primary_text'],
        'ad_copy_selection' => ['tool' => 'choose_ad_copy', 'argument' => 'selection', 'shape' => 'ad_copy_selection'],
        // The two halves of a responsive search ad's copy, each its own
        // question on one screen. They are separate entries because each
        // records its own half, so unticking a description cannot disturb the
        // headlines the buyer already settled.
        'google_headlines' => ['tool' => 'choose_ad_copy', 'argument' => 'use_headlines', 'shape' => 'list'],
        'google_descriptions' => ['tool' => 'choose_ad_copy', 'argument' => 'use_descriptions', 'shape' => 'list'],
        // Page-derived ad assets, approved rather than attached.
        'google_sitelinks' => ['tool' => 'choose_ad_copy', 'argument' => 'use_sitelinks', 'shape' => 'list'],
        'google_callouts' => ['tool' => 'choose_ad_copy', 'argument' => 'use_callouts', 'shape' => 'list'],
        'google_structured_snippet' => ['tool' => 'choose_ad_copy', 'argument' => 'use_structured_snippet', 'shape' => 'list'],
        // A legacy pending review card still advances to the selection card.
        'copy_review' => ['tool' => 'choose_ad_copy', 'argument' => 'offer_selection'],
        // Recorded so the copy is never written before the highlight is chosen.
        'copy_emphasis' => ['tool' => 'write_ad_copy', 'argument' => 'emphasis'],
        'copy_promotion_details' => ['tool' => 'write_ad_copy', 'argument' => 'promotion_details'],

        // Google's equivalent of a pixel. Applied by the shared tool, which
        // stores it on the campaign like Meta's, so one column answers "what
        // counts a conversion here" whatever the platform.
        //
        // There is no customer_id entry. Choosing a Google account was a
        // question with one answer once Google became a single common account,
        // so the tool that owned it is no longer registered.
        'conversion_action_resource_name' => ['tool' => 'choose_pixel', 'argument' => 'pixel_id', 'shape' => 'conversion_actions'],
        // The one question on screen that had no entry here, so the only
        // question whose answer depended on the model remembering to call its
        // tool. Reported as "I gave my own custom keywords but still it is
        // asking for keyword": nothing was saved, hasExplicitSelection stayed
        // false, and LaunchFlow asked again.
        'google_search_keywords' => ['tool' => 'set_search_keywords', 'argument' => 'keywords', 'shape' => 'search_keywords'],
    ];

    public function __construct(
        private readonly ToolRegistry $registry,
        private readonly Workspace $workspace,
    ) {}

    /** Whether this product knows how to apply an answer to this question. */
    public function handles(string $field): bool
    {
        return isset(self::FIELDS[$field]);
    }

    /** @return list<string> every question that can be answered without the model */
    public function fields(): array
    {
        return array_keys(self::FIELDS);
    }

    /**
     * Apply one answer, and say whether it landed.
     *
     * Never throws. An unknown field, a missing tool or a tool that refuses all
     * leave the turn exactly as it was before this existed: the message still
     * reaches the model, which can still do the work. Degrading to the old
     * behaviour is the point, because the old behaviour mostly worked.
     *
     * @param  string|array<string, mixed>|list<string>  $value
     */
    public function apply(string $field, string|array $value): bool
    {
        if (! $this->handles($field)) {
            return false;
        }

        $definition = self::FIELDS[$field];
        $arguments = $this->arguments($definition, $value, $field);

        return $arguments !== null && $this->call($this->qualified($definition), $arguments);
    }

    /**
     * The registry name of the tool that owns a question.
     *
     * @param  array{tool: string, argument: string, shape?: string, namespace?: string}  $definition
     */
    private function qualified(array $definition): string
    {
        return ($definition['namespace'] ?? 'campaign').NamespacedTool::SEPARATOR.$definition['tool'];
    }

    /**
     * Apply everything that was clicked, one call per tool.
     *
     * Answers are merged by the tool that owns them rather than applied one at
     * a time, because a tool asked for half of what it needs puts the other
     * half back on screen. Clicking "daily" and "10" together sent
     * set_campaign_budget(level, mode) with no amount, which re-offered the
     * amounts, and then set_campaign_budget(amount) which set it: the question
     * was answered and re-asked in the same turn. Targeting did the same thing
     * with countries, placements and devices, and the screen showed the
     * placements again underneath the next step. Seen on arb-dev on 17 Sep.
     *
     * Merged, the tool is handed everything at once and has nothing left to ask.
     *
     * @param  list<array{field?: string, value?: mixed}>  $answers
     * @return list<array{field: string, value: mixed, applied: bool}>
     */
    public function applyAll(array $answers): array
    {
        $calls = [];
        $fieldsByTool = [];
        $chosen = [];

        foreach ($answers as $answer) {
            $field = (string) ($answer['field'] ?? '');
            $value = $answer['value'] ?? '';

            // Numbers are accepted as well as strings: JSON carries an unquoted
            // budget as an int, and silently skipping it would drop the answer
            // with nothing to show for it. Booleans are not an answer to
            // anything offered here.
            $usable = is_string($value) || is_array($value) || is_int($value) || is_float($value);

            if (! $this->handles($field) || ! $usable) {
                continue;
            }

            $value = is_array($value) ? $value : (string) $value;

            $definition = self::FIELDS[$field];
            $arguments = $this->arguments($definition, $value, $field);

            if ($arguments === null) {
                continue;
            }

            $tool = $this->qualified($definition);

            // Later answers win on a clash, which only happens when one screen
            // offers the same argument twice, and the newer one is the answer.
            $calls[$tool] = [
                ...$calls[$tool] ?? [],
                ...$arguments,
            ];

            $fieldsByTool[$tool][] = $field;
            $chosen[$field] = $value;
        }

        // What was taken and what was not, so the turn can say so.
        //
        // This returned void, and the controller sent the model the word
        // "Continue." when a click arrived with no typed message. So the model
        // was never told what the buyer had chosen: it answered the question
        // that was already settled, or moved on without a word about the choice,
        // and a click read as though nothing had happened. Koushik and Kapil both
        // clicked the same option twice for that reason.
        $applied = [];

        foreach ($calls as $tool => $arguments) {
            $took = $this->call($tool, $arguments);

            foreach ($fieldsByTool[$tool] ?? [] as $field) {
                $applied[] = [
                    'field' => $field,
                    'value' => $chosen[$field] ?? null,
                    'applied' => $took,
                ];
            }
        }

        return $applied;
    }

    /**
     * Run one tool from the registry, and say whether it took the answer.
     *
     * @param  string  $name  the full registry name, namespace included
     * @param  array<string, mixed>  $arguments
     */
    private function call(string $name, array $arguments): bool
    {
        $tool = collect($this->registry->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === $name);

        if (! $tool) {
            return false;
        }

        try {
            return $this->landed($tool->handle(new ToolRequest($arguments)));
        } catch (Throwable $e) {
            report($e);

            return false;
        }
    }

    /**
     * Whether the tool actually took the answer.
     *
     * Running is not the same as succeeding. A tool that cannot reach the
     * platform, or is handed a value the guardrails refuse, returns its refusal
     * as an ordinary result rather than throwing, and treating that as applied
     * would leave the model believing the question was settled when it was not.
     *
     * Tools that answer in a sentence rather than JSON are taken at their word,
     * because they only reply that way when they succeeded.
     */
    private function landed(\Stringable|string $result): bool
    {
        $decoded = json_decode((string) $result, true);

        return ! is_array($decoded) || ($decoded['ok'] ?? true) !== false;
    }

    /**
     * The tool's arguments for this answer.
     *
     * An empty string survives on purpose: "no tracking" and "run the Instagram
     * ads under the Page" are both answers, and both tools tell them apart from
     * never having been asked by whether the key is present at all.
     *
     * @param  array{tool: string, argument: string, shape?: string}  $definition
     * @param  string|array<string, mixed>|list<string>  $value
     * @return array<string, mixed>|null Null leaves an unsupported selection for the agent.
     */
    private function arguments(array $definition, string|array $value, string $field): ?array
    {
        $shape = $definition['shape'] ?? 'string';

        if ($shape === 'linkedin_audience_review') {
            $choice = collect($this->workspace->pendingChoices())->firstWhere('field', $field);
            $offered = collect($choice['options'] ?? [])->contains(fn (array $option): bool => ($option['value'] ?? null) === $value && ! ($option['disabled'] ?? false));

            return $value === ChooseAudienceList::CHANGE_AUDIENCE_MODE && $offered
                ? ['section' => 'audience', 'review_audience' => true]
                : null;
        }

        if ($shape === 'linkedin_insight_retry') {
            return $value === 'retry' ? ['section' => 'insight_tag'] : null;
        }

        // The budget's level and mode are one click, crossed into one option so
        // the whole of "how the budget works" is a single screen.
        if ($shape === 'strategy') {
            [$level, $mode] = array_pad(explode(':', (string) (is_array($value) ? reset($value) : $value), 2), 2, null);

            return array_filter(['level' => $level, 'mode' => $mode], fn (?string $part): bool => filled($part));
        }

        if ($shape === 'location_list') {
            $form = is_array($value) ? $value : [];

            return [
                'country_code' => is_string($form['country_code'] ?? null) ? $form['country_code'] : '',
                ...collect(TargetLocationList::LISTS)->mapWithKeys(fn (string $kind, string $argument): array => [
                    $argument => is_string($form[$kind] ?? null) ? $form[$kind] : '',
                ])->all(),
            ];
        }

        if ($shape === 'location_search') {
            $search = is_array($value) ? $value : [];

            return [
                'country_code' => is_string($search['country_code'] ?? null) ? $search['country_code'] : '',
                'kind' => is_string($search['kind'] ?? null) ? $search['kind'] : '',
                'query' => is_string($search['query'] ?? null) ? $search['query'] : '',
                'catalog_places' => is_array($search['catalog_places'] ?? null) ? $search['catalog_places'] : [],
            ];
        }

        if ($shape === 'location_result') {
            if (! is_string($value)) {
                return ['country_code' => '', 'kind' => ''];
            }

            $offered = collect($this->workspace->pendingChoices())->firstWhere('field', $field);
            $option = collect($offered['options'] ?? [])->firstWhere('value', $value);
            $selection = $option['arguments'] ?? null;

            return is_array($selection) && isset($selection['external_id'], $selection['country_code'], $selection['kind'], $selection['query'])
                ? $selection : ['country_code' => '', 'kind' => ''];
        }

        if ($shape === 'ad_copy_selection') {
            if (! is_array($value)) {
                return ['selection' => (string) $value];
            }

            return [
                'selection' => (string) ($value['selection'] ?? ''),
                'headline' => (string) ($value['headline'] ?? ''),
                'primary_text' => (string) ($value['primary_text'] ?? ''),
            ];
        }

        if ($shape === 'age_range') {
            if (is_array($value) && array_key_exists('age_min', $value) && array_key_exists('age_max', $value)) {
                return [
                    'age_min' => (int) $value['age_min'],
                    'age_max' => (int) $value['age_max'],
                ];
            }

            $ranges = is_array($value) ? $value : [$value];
            $bounds = [];

            foreach ($ranges as $range) {
                if (! is_string($range) || preg_match('/^(\d{1,2}):(\d{1,2})$/D', $range, $matches) !== 1) {
                    continue;
                }

                $minimum = (int) $matches[1];
                $maximum = (int) $matches[2];

                if ($minimum < 13 || $maximum > 65 || $minimum > $maximum) {
                    continue;
                }

                $bounds[] = [$minimum, $maximum];
            }

            if ($bounds === []) {
                return ['age_min' => 0, 'age_max' => 0];
            }

            return [
                'age_min' => min(array_column($bounds, 0)),
                'age_max' => max(array_column($bounds, 1)),
            ];
        }

        if ($shape === 'meta_gender') {
            $gender = (string) $value;

            return ['genders' => $gender === 'all' ? [] : [(int) $gender]];
        }

        if ($shape === 'interest_options') {
            $values = array_values(array_filter(array_map('strval', (array) $value)));
            $ids = array_values(array_filter($values, static fn (string $item): bool => preg_match('/^[0-9]+$/D', $item) === 1));
            $ideas = array_values(array_filter($values, static fn (string $item): bool => preg_match('/^[0-9]+$/D', $item) !== 1));

            return [
                'interest_ids' => $ids,
                'interest_ideas' => implode(', ', $ideas),
            ];
        }

        if (in_array($shape, ['website_pixel', 'website_event', 'website_confirmation'], true)) {
            $offered = collect($this->workspace->pendingChoices())->firstWhere('field', $field);
            $option = collect($offered['options'] ?? [])->firstWhere('value', (string) $value);
            $arguments = is_array($option['arguments'] ?? null) ? $option['arguments'] : [];

            return match ($shape) {
                'website_pixel' => ['pixel_id' => (string) $value, ...$arguments],
                'website_event' => $arguments + ['event_name' => (string) $value],
                'website_confirmation' => $arguments + ['confirm_action' => (string) $value],
            };
        }

        /**
         * Several conversion actions from one question.
         *
         * choose_pixel has always taken more than one - pixel_id for the
         * primary and also_count for the rest, which the publisher sends as
         * conversion_actions and narrows the goals by category. The question on
         * screen was single-select, so the only way to ask for two was to type
         * it in prose and hope the model split it. Reported twice: "need to
         * have multiple events selections".
         *
         * The first pick is the primary because that is the one the tool treats
         * as the campaign's conversion_event; the order is the order they were
         * offered in, which puts the suggested action first.
         */
        if ($shape === 'conversion_actions') {
            $chosen = array_values(array_filter(array_map('strval', (array) $value), static fn (string $item): bool => $item !== ''));

            if ($chosen === []) {
                return null;
            }

            return array_filter([
                'pixel_id' => array_shift($chosen),
                'also_count' => $chosen,
            ], static fn (mixed $part): bool => $part !== []);
        }

        /**
         * Search keywords, as the buyer clicked and typed them.
         *
         * set_search_keywords takes a complete set of structured criteria -
         * text, match type, negative - and the revision it was read at, so
         * until now a click could not be applied and the answer went to the
         * model as prose. When the model did not call the tool, or called it
         * with the wrong revision, nothing was saved and the step asked again.
         *
         * A clicked suggestion keeps the match type it was offered with. A
         * typed value is split on commas, because that is what the box's own
         * hint tells the buyer to do, and each term is sent as written: the
         * markers are read by SearchKeywordSelections::unmark(), which is where
         * that parsing already lives, so "quoted", [bracketed] and -minus mean
         * the same thing however they arrive.
         *
         * The revision comes off the offered options, which is the revision the
         * question was asked at. That is the point of sending it: a click made
         * against a selection that has since moved must be refused rather than
         * quietly overwrite the newer one.
         */
        if ($shape === 'search_keywords') {
            $offered = collect($this->workspace->pendingChoices())->firstWhere('field', $field);
            $options = collect($offered['options'] ?? []);

            $keywords = [];

            foreach ((array) $value as $picked) {
                // A row that carries its own match type, which is how the
                // keyword form sends one: the suggestions are generated as
                // phrase matches and were offered with only that, so broad and
                // exact could not be chosen from the row they are written on.
                //
                // Sent as the type rather than as [brackets] because an unmarked
                // term already means something here - the match type the
                // suggestion was offered with - and one payload cannot mean both
                // that and broad.
                if (is_array($picked)) {
                    $text = trim((string) ($picked['text'] ?? ''));
                    $matchType = strtoupper(trim((string) ($picked['match_type'] ?? '')));

                    if ($text === '' || ! in_array($matchType, SearchKeywordSelections::MATCH_TYPES, true)) {
                        continue;
                    }

                    $keywords[] = ['text' => $text, 'match_type' => $matchType, 'negative' => false];

                    continue;
                }

                $picked = (string) $picked;
                $option = $options->firstWhere('value', $picked);

                // An offered suggestion: one term, its own match type.
                if ($option !== null) {
                    $keywords[] = [
                        'text' => $picked,
                        'match_type' => (string) (($option['arguments']['match_type'] ?? null) ?: 'BROAD'),
                        'negative' => false,
                    ];

                    continue;
                }

                // Typed: several terms at once, each in Google's shorthand.
                // BROAD is what the hint promises for an unmarked term, and
                // unmark() overrides it wherever a marker says otherwise.
                foreach (explode(',', $picked) as $term) {
                    $term = trim($term);

                    if ($term === '') {
                        continue;
                    }

                    $keywords[] = ['text' => $term, 'match_type' => 'BROAD', 'negative' => false];
                }
            }

            if ($keywords === []) {
                return null;
            }

            $revision = $options->pluck('revision')->filter(fn (mixed $at): bool => $at !== null)->first();

            return [
                'keywords' => $keywords,
                'expected_revision' => (int) ($revision ?? 0),
            ];
        }

        if ($shape === 'audience_mode') {
            $choice = trim((string) $value);

            $offered = collect($this->workspace->pendingChoices())->firstWhere('field', $field);
            $option = collect($offered['options'] ?? [])->firstWhere('value', $choice);
            $optionArguments = is_array($option['arguments'] ?? null) ? $option['arguments'] : [];

            return in_array($choice, ['broad', 'custom', 'suggestions', 'retargeting', 'demographics', 'interests', 'behaviors', 'done', 'remove'], true)
                ? ['audience_mode' => $choice, ...$optionArguments]
                : ['interest_ideas' => $choice];
        }

        $argument = $definition['argument'];

        return [$argument => match ($shape) {
            'list' => array_values(array_filter((array) $value, fn ($item): bool => $item !== null)),
            'ints' => array_values(array_map(intval(...), array_filter((array) $value))),
            'commas' => array_values(array_filter(explode(',', (string) (is_array($value) ? implode(',', $value) : $value)))),
            'number' => (float) (is_array($value) ? reset($value) : $value),
            default => (string) (is_array($value) ? reset($value) : $value),
        }];
    }
}
