<?php

namespace App\Agent;

use App\Campaigns\Targeting\LocationCatalog;
use App\Campaigns\Targeting\LocationListResolver;

/**
 * Choices a tool wants the person to pick from, rather than type.
 *
 * The agent answers in prose, so every step has been an open question and the
 * user has had to know the vocabulary: which objective, which placements, which
 * creative id. Offering the options instead turns most of a campaign into
 * clicking.
 *
 * Collected here during a turn and drained by the controller afterwards, which
 * is the same shape the workspace already uses. It deliberately does not touch
 * the model's reply: the words stay the model's, the options are ours, and the
 * options can only be values the platform actually accepts.
 *
 * Clicking sends an ordinary message. That keeps one entry point into the agent
 * rather than a second, parallel one that would then need its own approval,
 * ownership and audit handling.
 */
class Choices
{
    /**
     * Fields that belong to one question. A tool that offers two unrelated fields at once
     * must be listed here, or its answers are rejected as mixed and, with tools blocked, nothing can answer it.
     *
     * @var list<list<string>>
     */
    private const SEMANTIC_GROUPS = [
        ['budget_strategy', 'budget_amount'],
        ['ad_headline', 'ad_primary_text'],
        // A responsive search ad's headlines and descriptions are reviewed
        // together, because they are one ad, and Regenerate belongs on the same
        // screen: narrowing the set and replacing it are the two things a buyer
        // might want after reading it.
        ['google_headlines', 'google_descriptions', 'ad_copy_selection', 'google_sitelinks', 'google_callouts', 'google_structured_snippet'],
        ['meta_age_range', 'meta_gender'],
    ];

    /** @var list<array<string, mixed>> */
    private array $offered = [];

    /** @var list<string> */
    private array $pinned = [];

    /** @var list<string> */
    private array $ignored = [];

    public function __construct(private readonly LocationCatalog $locationCatalog) {}

    /**
     * @param  string  $field  what is being chosen, for example objective
     * @param  string  $question  short, and shown above the options
     * @param  list<array{value: string, label: string, hint?: ?string, footer?: ?string, image?: ?string, video?: ?string, badge?: ?string, revision?: int, arguments?: array<string, mixed>}>  $options
     * @param  bool  $multiple  whether more than one may be picked
     * @param  array<string, int|string>|null  $control  custom input control configuration
     */
    public function offer(
        string $field,
        string $question,
        array $options,
        bool $multiple = false,
        bool $allowOther = false,
        bool $otherInComposer = false,
        string $otherLabel = 'Other',
        ?string $otherHint = null,
        ?string $otherPlaceholder = null,
        ?string $otherValue = null,
        ?int $otherPosition = null,
        ?array $control = null,
        bool $optional = false,
    ): void {
        if ($options === [] && $control === null) {
            return;
        }

        // The card a click just produced is the flow's own next question; a model's offer for another field must not wipe it.
        if ($this->pinned !== [] && ! in_array($field, $this->pinned, true) && ! self::isOneSemanticForm([...$this->pinned, $field])) {
            $this->ignored[] = $field;

            return;
        }

        $existingFields = array_values(array_diff(array_column($this->offered, 'field'), [$field]));
        if ($existingFields !== [] && ! self::isOneSemanticForm([...$existingFields, $field])) {
            $this->offered = [];
        }

        // A question asked twice in one turn is one question. Two tools can
        // reach the same field, and the model can call one of them twice, and
        // the renderer counts answers by field: four questions over three
        // fields meant "Answer all 4 to continue" could never be satisfied and
        // the button stayed dead. Seen in the browser on 16 Sep with devices
        // asked twice alongside placements and click tracking.
        //
        // The later offer wins, because it was built from more recent state.
        $this->offered = array_values(array_filter(
            $this->offered,
            fn (array $existing): bool => $existing['field'] !== $field,
        ));

        $this->offered[] = [
            'field' => $field,
            'question' => $question,
            'multiple' => $multiple,
            'allow_other' => $allowOther,
            'other_in_composer' => $otherInComposer,
            'other_label' => $otherLabel,
            'other_hint' => $otherHint,
            'other_placeholder' => $otherPlaceholder,
            'other_value' => $otherValue,
            'other_position' => $otherPosition,
            'control' => $control,
            // Whether the group's Continue waits for this one.
            //
            // A group demands every question in it, which is right for the
            // questions that are answers and wrong for the ones that are
            // actions. Regenerate sat beside the headline and description
            // checkboxes, so a buyer who had chosen nine headlines and two
            // descriptions still could not continue without pressing
            // Regenerate - which threw the copy away, wrote a fresh set, and
            // asked the same three questions again. Reported as a loop.
            'optional' => $optional,
            'options' => array_map(fn (array $o): array => [
                'value' => (string) $o['value'],
                'label' => (string) $o['label'],
                'hint' => isset($o['hint']) ? (string) $o['hint'] : null,
                'footer' => isset($o['footer']) ? (string) $o['footer'] : null,
                'image' => isset($o['image']) ? (string) $o['image'] : null,
                'video' => isset($o['video']) ? (string) $o['video'] : null,
                // Stands in for a picture there is no way to produce. A video
                // has no stored poster frame, so beside options that do have
                // one its card rendered as blank space and read as broken.
                'icon' => isset($o['icon']) ? (string) $o['icon'] : null,
                // A short word above the label, for "Suggested" and the like.
                'badge' => isset($o['badge']) ? (string) $o['badge'] : null,
                'disabled' => ! empty($o['disabled']),
                // Already ticked when the question appears. Only honoured on a
                // multi-select: see the browser's own note on why a pre-picked
                // single choice would be an answer nobody gave.
                'selected' => ! empty($o['selected']),
                // What clicking sends. Written here rather than in the browser
                // so the phrasing that reaches the model is ours.
                'sends' => (string) ($o['sends'] ?? $o['label']),
                'revision' => isset($o['revision']) ? (int) $o['revision'] : null,
                'arguments' => isset($o['arguments']) ? (array) $o['arguments'] : null,
            ], $options),
        ];
    }

    /** @param list<string> $fields */
    public static function isOneSemanticForm(array $fields): bool
    {
        if (count($fields) <= 1) {
            return true;
        }

        return collect(self::SEMANTIC_GROUPS)->contains(
            fn (array $group): bool => array_diff($fields, $group) === []
                && count($fields) <= count($group),
        );
    }

    /** Keep what is on offer now against later offers this turn. */
    public function pin(): void
    {
        $this->pinned = array_column($this->offered, 'field');
    }

    /** @return list<string> Fields a later offer tried to add over a pinned one. */
    public function ignored(): array
    {
        return $this->ignored;
    }

    /** Drop a question offered earlier this turn that a later offer has made moot. */
    public function withdraw(string $field): void
    {
        $this->pinned = array_values(array_diff($this->pinned, [$field]));
        $this->offered = array_values(array_filter(
            $this->offered,
            fn (array $existing): bool => $existing['field'] !== $field,
        ));
    }

    /**
     * @param  list<array<string, mixed>>  $options
     * @param  array<string, int>  $limits
     */
    public function offerAdCopySelection(array $options, array $limits, bool $optional = false): void
    {
        $this->offer(
            field: 'ad_copy_selection',
            question: 'Which ad-copy variation should we use?',
            options: $options,
            optional: $optional,
        );

        $this->offered[array_key_last($this->offered)]['copy_limits'] = $limits;
    }

    /**
     * Search keywords, each with its own match type.
     *
     * The suggestions were offered as PHRASE and only as PHRASE, because that
     * is the match type they are generated with, so a buyer who wanted one of
     * them broad or exact had to retype it into Other in Google's shorthand to
     * get it. Reported after the release: "ai suggestion for keywords can be
     * added only in phrase match, need option to add as broad and exact."
     *
     * The match types travel with the question rather than being assumed by
     * the renderer, because Google's three are the platform's answer and not
     * this screen's.
     *
     * More than one per keyword, asked for after the first release: "need
     * options to choose 1, 2 or all 3 match types in keyword selection".
     * Google treats a text at each match type as its own criterion and runs
     * them together, so one row can produce up to three keywords.
     *
     * @param  list<array<string, mixed>>  $options
     * @param  list<string>  $matchTypes
     */
    public function offerSearchKeywords(
        string $question,
        array $options,
        array $matchTypes,
        ?string $otherHint = null,
        ?string $otherPlaceholder = null,
    ): void {
        $this->offer(
            field: 'google_search_keywords',
            question: $question,
            options: $options,
            multiple: true,
            allowOther: true,
            otherHint: $otherHint,
            otherPlaceholder: $otherPlaceholder,
        );

        if ($this->offered === []) {
            return;
        }

        $this->offered[array_key_last($this->offered)]['keyword_form'] = [
            'match_types' => $matchTypes,
            'several_match_types' => true,
        ];
    }

    /** What the ad copy should highlight: always asked before the first copy is written. */
    public function offerCopyEmphasis(): void
    {
        $this->offer(
            field: 'copy_emphasis',
            question: 'What should these ads highlight?',
            options: [
                ['value' => 'Key Benefits & Features', 'label' => 'Key Benefits & Features',
                    'hint' => 'Highlight top product advantages and unique value',
                    'sends' => 'Emphasize key benefits and features in the ad copy.'],
                ['value' => 'Special Promotion & Discount', 'label' => 'Special Promotion & Discount',
                    'hint' => 'Drive conversions with a deal, savings, or promo',
                    'sends' => 'Emphasize a special promotion and discount in the ad copy.'],
                ['value' => 'Customer Trust & Social Proof', 'label' => 'Customer Trust & Social Proof',
                    'hint' => 'Build confidence with ratings, reviews, and satisfaction guarantee',
                    'sends' => 'Emphasize customer trust, reviews, and social proof in the ad copy.'],
            ],
            allowOther: true,
        );
    }

    /**
     * @param  list<string>  $countries
     * @param  array<string, list<string>>  $kindsByCountry
     */
    public function offerLocationScope(string $platform, array $countries, int $revision, array $kindsByCountry): void
    {
        $countryList = implode(', ', array_map(
            fn (string $code): string => class_exists(\Locale::class) ? (\Locale::getDisplayRegion('-'.$code, 'en') ?: $code) : $code,
            $countries,
        ));
        $singleCountry = count($countries) === 1;
        $options = [
            ['value' => 'whole', 'label' => $singleCountry ? 'Whole country' : 'Whole countries',
                'hint' => $singleCountry ? 'Reach people across the selected country.' : 'Reach people across all selected countries.', 'revision' => $revision,
                'sends' => 'Keep whole-country targeting at revision '.$revision.'.'],
        ];

        if ($platform !== 'linkedin') {
            array_push($options,
                ['value' => 'city', 'label' => 'Specific cities', 'hint' => 'Search and choose exact cities in the selected countries.', 'revision' => $revision,
                    'sends' => 'Search for a city within '.$countryList.'.'],
                ['value' => 'region', 'label' => 'States or regions', 'hint' => 'Search and choose exact states or provinces.', 'revision' => $revision,
                    'sends' => 'Search for a state or region within '.$countryList.'.']);
        }

        if (in_array('US', $countries, true)
            && ($platform === 'linkedin' || in_array('dma', $kindsByCountry['US'] ?? [], true))) {
            $options[] = ['value' => 'dma', 'label' => $platform === 'meta' ? 'US market areas' : 'US DMA markets',
                'hint' => 'Search this platform’s market areas by name.', 'revision' => $revision,
                'sends' => 'Search for a US DMA market by name.'];
        }

        $postalCountries = array_values(array_filter($countries,
            fn (string $code): bool => in_array('postal', $kindsByCountry[$code] ?? [], true)));

        if ($postalCountries !== []) {
            $options[] = ['value' => 'postal', 'label' => 'Specific postal codes (ZIP Codes)',
                'hint' => 'Target exact ZIP codes, postcodes or pincodes.', 'revision' => $revision,
                'sends' => 'Target specific postal codes in '.implode(', ', $postalCountries).'.'];
        }

        if (collect($kindsByCountry)->contains(fn (array $kinds): bool => $kinds !== [])) {
            $options[] = ['value' => 'list', 'label' => 'Paste a list', 'hint' => 'States, cities, markets or postal codes, many at once.',
                'revision' => $revision, 'sends' => 'Open advanced targeting to paste a list of places.'];
        }

        $this->offer(
            field: 'location_scope',
            question: 'Where within '.$countryList.' should this campaign run?',
            options: $options,
        );
    }

    /**
     * The advanced targeting form: one paste box per kind the campaign can target.
     *
     * @param  list<string>  $countries
     * @param  array<string, list<string>>  $kindsByCountry
     */
    public function offerLocationList(array $countries, array $kindsByCountry, int $revision): void
    {
        $this->offer(
            field: 'location_list',
            question: 'Advanced targeting: paste the places to target',
            options: [['value' => 'check', 'label' => 'Check places']],
        );

        $this->offered[array_key_last($this->offered)]['location_list'] = [
            'countries' => array_values($countries),
            'kinds' => $kindsByCountry,
            'revision' => $revision,
            'max' => LocationListResolver::MAX_ENTRIES,
        ];
    }

    /**
     * Pasted places matched against the provider, for the user to confirm.
     *
     * @param  list<array{kind: string, input: string, status: string, options: list<array{external_id: string, label: string}>, reason?: string}>  $entries
     * @param  list<array{value: string, label: string}>  $options
     */
    public function offerLocationReview(string $countryCode, int $revision, array $entries, array $options): void
    {
        $this->offer(
            field: 'location_list_review',
            question: 'Review the places to target in '.$countryCode,
            options: $options,
            multiple: true,
        );

        $this->offered[array_key_last($this->offered)]['review'] = [
            'country_code' => $countryCode,
            'revision' => $revision,
            'entries' => $entries,
        ];
    }

    /** @param list<string> $countries */
    public function offerLocationSearch(string $kind, array $countries, string $platform, ?int $revision = null): void
    {
        $this->offer(
            field: 'location_search',
            question: match ($kind) {
                'city' => 'Search for a city',
                'dma' => 'Search for a US market area',
                default => 'Search for a state or region',
            },
            options: [['value' => 'search', 'label' => 'Search']],
        );

        $this->offered[array_key_last($this->offered)]['search'] = [
            'kind' => $kind,
            'platform' => $platform,
            'countries' => array_values($countries),
            'revision' => $revision,
            'catalog_places' => collect($countries)->mapWithKeys(fn (string $country): array => [
                $country => $this->locationCatalog->choices($platform, $kind, $country),
            ])->all(),
        ];
    }

    /** @return list<array<string, mixed>> */
    public function all(): array
    {
        return $this->offered;
    }

    /**
     * Take what was offered and forget it.
     *
     * Drained rather than read so a later turn cannot re-show a question that
     * has already been answered.
     *
     * @return list<array<string, mixed>>
     */
    public function drain(): array
    {
        $offered = $this->offered;
        $this->offered = [];
        $this->pinned = [];
        $this->ignored = [];

        return $offered;
    }
}
