<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Briefs;
use App\Campaigns\Objectives;
use App\Campaigns\Platforms\Platforms;
use App\Campaigns\Targeting\CountryCatalog;
use App\Campaigns\Targeting\LocationListResolver;
use App\Campaigns\Targeting\MetaDetailedTargeting;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Services\AI\AudienceInterestPhrases;
use App\Services\Meta\Meta;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Collection;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

/**
 * Audience, countries and placements for the campaign in focus.
 *
 * Stored on the campaign itself, which on Meta are then written to its ad set
 * on publish.
 */
class SetTargeting implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly Platforms $platforms,
        private readonly Briefs $briefs,
        private readonly CountryCatalog $countries,
        private readonly TargetingSelections $selections,
        private readonly LocationListResolver $locationLists,
        private readonly Meta $meta,
        private readonly AudienceInterestPhrases $audiencePhrases,
        private readonly MetaDetailedTargeting $detailedTargeting,
    ) {}

    /**
     * Where this campaign's platform can actually put an ad.
     *
     * Not a constant, because the constant is Meta's. Asking a Google campaign
     * whether to run on Messenger, and then writing "facebook" to it, is what
     * happened before this: the list offered and the list validated against were
     * both {@see Objectives::PLACEMENTS} regardless of the platform in focus.
     *
     * An empty list means the platform does not model placements yet. That is
     * not the same as "no placements chosen", so nothing is offered or written,
     * and {@see LaunchFlow} treats the step as inapplicable
     * rather than leaving it outstanding forever.
     *
     * @return list<string>
     */
    private function supportedPlacements(Campaign $campaign): array
    {
        // Asked of the campaign, so the channel can answer. placements() is
        // every network the platform supports; what this campaign can run on
        // is narrower, and offering more put the Search network on a Display
        // campaign. See ADisplayCampaignIsNotOfferedSearchNetworksTest.
        return $this->platforms->for($campaign)->placementsFor(
            (string) $campaign->objective,
            $campaign->campaign_type,
        );
    }

    private function supportsDevices(Campaign $campaign): bool
    {
        return in_array($campaign->platform, ['meta', 'google'], true);
    }

    public function description(): Stringable|string
    {
        return 'Set audience and placement on the campaign in focus: countries, age range, '
            .'genders, devices and placements. Call with no arguments to offer choices '
            .'for anything not yet set. For Meta, offer the audience step, then demographics, '
            .'interests or behaviors. Search the chosen branch and save only options the user '
            .'selects from current Meta results.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'countries' => $schema->array()->items($schema->string())
                ->description('Two-letter ISO codes (e.g. ["US", "GB"]). Omit to offer the searchable global country list.'),
            'section' => $schema->string()->description('Internal flow hint: placements, devices, countries, or Meta audience/demographics. Omit for the first missing targeting choice.'),
            'audience_mode' => $schema->string()->description('Meta audience choice: broad, demographics, interests, behaviors, done, remove, suggestions, or retargeting.'),
            'audience_category' => $schema->string()->description('Meta audience category inside the chosen group, such as education, work, or technology.'),
            'audience_facet' => $schema->string()->description('Meta audience detail inside the chosen category, such as education_level, job_titles, or yoga.'),
            'facet_query' => $schema->string()->description('Search text for the current Meta audience detail. Never save this text as targeting.'),
            'detailed_ids' => $schema->array()->items($schema->string())->description('field|id values selected from the current Meta detailed targeting options.'),
            'remove_detailed' => $schema->array()->items($schema->string())->description('Saved field|id targeting to remove.'),
            'interest_ideas' => $schema->string()->description('User-entered Meta audience ideas. Search these with Meta and offer exact matches; never save the raw prose as targeting.'),
            'interest_ids' => $schema->array()->items($schema->string())->description('Interest IDs selected from the current Meta results only.'),
            'age_min' => $schema->integer()->description('Minimum age, 13 to 65.'),
            'age_max' => $schema->integer()->description('Maximum age, 13 to 65.'),
            'genders' => $schema->array()->items($schema->integer())
                ->description('1 for male, 2 for female. Omit to reach everyone.'),
            'devices' => $schema->array()->items($schema->string())
                ->description('Any of mobile, desktop. Omit for both.'),
            // Deliberately does not list the values. The list is the platform's,
            // and this description is written once for every campaign, so naming
            // Meta's placements here told the model to offer Messenger on a
            // Google campaign. Calling with no placements puts the right ones on
            // screen for whichever platform is in focus.
            'placements' => $schema->array()->items($schema->string())
                ->description('Where the ads should appear. The accepted values depend on the '
                    .'platform this campaign runs on, so omit this to have the valid ones listed '
                    .'for the user to pick from rather than guessing them.'),
        ];
    }

    /** Placements are a closed list, so every one of them can be a button. */
    private function offerPlacements(Campaign $campaign): void
    {
        $supported = $this->supportedPlacements($campaign);

        if ($supported === []) {
            return;
        }

        $this->choices->offer(
            field: 'placements',
            question: 'Where should the ads appear?',
            options: array_map(fn (string $p): array => [
                'value' => $p,
                'label' => $p === 'threads' ? 'Threads + Instagram Feed' : ucfirst(str_replace('_', ' ', $p)),
                'sends' => $p === 'threads'
                    ? 'Run on Threads and Instagram Feed, which Meta requires for Threads ads.'
                    : 'Run on '.$p,
            ], $supported),
            multiple: true,
        );
    }

    /**
     * The hint has to come from the campaign, not from Meta.
     *
     * "Most Meta inventory" was written on the mobile option and shown on every
     * platform, so a Google Search campaign was told about Meta's inventory
     * while choosing its devices. Seen on arb-dev on 25 Sep. Each platform has
     * its own reason to go mobile only, and the one that does not apply is
     * worse than none: it reads as the product not knowing which campaign it is
     * looking at.
     */
    private function mobileHint(Campaign $campaign): ?string
    {
        return match ($campaign->platform) {
            'meta' => 'Most Meta inventory. Worth it when the landing page is built for phones.',
            'google' => 'Most search volume. Worth it when the landing page is built for phones.',
            'linkedin' => 'Where most LinkedIn browsing happens. Worth it when the page is built for phones.',
            default => 'Worth it when the landing page is built for phones.',
        };
    }

    /**
     * Device targeting, which was supported everywhere except in the asking.
     *
     * AdSetSpec has always sent device_platforms and the tool has always
     * accepted them, and nothing ever put the question in front of anyone, so
     * every campaign ran on both whether or not the landing page worked on a
     * phone. Offered as one choice rather than a multi-select: the useful
     * answers are all, one, or the other.
     */
    private function offerDevices(Campaign $campaign): void
    {
        $this->choices->offer(
            field: 'devices',
            question: 'Which devices?',
            options: [
                [
                    'value' => 'mobile,desktop',
                    'label' => 'All devices',
                    'badge' => 'Suggested',
                    'sends' => 'Target both mobile and desktop',
                ],
                [
                    'value' => 'mobile',
                    'label' => 'Mobile only',
                    'hint' => $this->mobileHint($campaign),
                    'sends' => 'Target mobile only',
                ],
                [
                    'value' => 'desktop',
                    'label' => 'Desktop only',
                    'sends' => 'Target desktop only',
                ],
            ],
        );
    }

    /**
     * Record the countries on the brief so no later platform has to ask.
     *
     * Never overwritten. The brief holds what the buyer first said, and a
     * campaign given its own narrower list afterwards must not quietly
     * redefine where the whole brief runs. The campaign keeps its own value
     * either way; this is only what the next platform inherits.
     *
     * @param  list<string>  $countries
     */
    private function rememberCountries(array $countries): void
    {
        $brief = $this->briefs->current();

        if ($countries === [] || $brief === null || filled($brief->locations['countries'] ?? null)) {
            return;
        }

        $this->selections->rememberBriefCountries($brief, $countries);
    }

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

        if ($campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'Audience and location targeting cannot be changed on a published campaign. Create a new campaign for a different audience.',
            ]);
        }

        $arguments = $request->all();

        if (filled($arguments['devices'] ?? null) && ! $this->supportsDevices($campaign)) {
            return $this->json(['ok' => false, 'error' => 'LinkedIn does not support device targeting; no device restriction was saved.']);
        }

        $availableCountries = $this->countries->names();
        $countries = array_values(array_unique(array_filter(array_map(
            fn ($c) => strtoupper(trim((string) $c)),
            (array) ($arguments['countries'] ?? $this->selections->countries($campaign)),
        ))));

        $section = (string) ($arguments['section'] ?? '');
        $specialCategories = (array) ($campaign->special_ad_categories ?? []);
        $demographicsAllowed = $specialCategories === [] || $specialCategories === ['NONE'];

        if ($section === 'audience') {
            if ($campaign->platform !== 'meta' || $specialCategories !== ['NONE']) {
                return $this->json(['ok' => false, 'error' => 'Audience refinement is available only for Meta campaigns without a declared special ad category.']);
            }

            if (array_key_exists('audience_demographics', $this->workspace->sourcesFor($campaign))) {
                $this->offerAudienceModes($campaign);
            } else {
                $this->offerDemographics($campaign);
            }

            $summary = $this->detailedTargeting->summary($campaign);
            $hasSelection = $summary !== '' && $summary !== 'Saved targeting needs review.';

            return $this->json(['ok' => true, 'note' => $hasSelection
                ? 'Keep this audience is on screen. Wait for that choice before the next campaign step.'
                : 'Choose age and gender first, then choose the audience type. Wait for the user.']);
        }

        if ($campaign->platform === 'meta' && (array_key_exists('remove_detailed', $arguments)
            || array_key_exists('detailed_ids', $arguments)
            || filled($arguments['audience_facet'] ?? null)
            || filled($arguments['facet_query'] ?? null)
            || filled($arguments['audience_category'] ?? null))) {
            if (array_key_exists('remove_detailed', $arguments)) {
                return $this->detailedTargeting->remove($campaign, (array) $arguments['remove_detailed']);
            }

            if (array_key_exists('detailed_ids', $arguments)) {
                return $this->detailedTargeting->save($campaign, (array) $arguments['detailed_ids']);
            }

            if (filled($arguments['audience_facet'] ?? null) || filled($arguments['facet_query'] ?? null)) {
                return $this->detailedTargeting->openFacet(
                    $campaign,
                    (string) ($arguments['audience_facet'] ?? ''),
                    (string) ($arguments['facet_query'] ?? ''),
                );
            }

            return $this->detailedTargeting->offerCategory($campaign, (string) $arguments['audience_category']);
        }

        if (array_key_exists('audience_mode', $arguments)) {
            if ($campaign->platform !== 'meta' || $specialCategories !== ['NONE']) {
                return $this->json(['ok' => false, 'error' => 'Audience refinement is unavailable for this Meta special ad category.']);
            }

            if (in_array($arguments['audience_mode'], ['demographics', 'interests', 'behaviors'], true)) {
                return $this->detailedTargeting->offerGroup($campaign, (string) $arguments['audience_mode']);
            }

            if ($arguments['audience_mode'] === 'done') {
                return $this->detailedTargeting->keep($campaign);
            }

            if ($arguments['audience_mode'] === 'remove') {
                return $this->detailedTargeting->offerRemoval($campaign);
            }

            if ($arguments['audience_mode'] === 'broad') {
                return $this->saveBroadAudience($campaign);
            }

            if ($arguments['audience_mode'] === 'custom') {
                $this->offerDemographics($campaign);

                return $this->json(['ok' => true, 'note' => 'Age and gender choices are on screen. Wait for the user.']);
            }

            if ($arguments['audience_mode'] === 'suggestions') {
                $interestIds = array_values(array_unique(array_map('strval', (array) ($arguments['interest_ids'] ?? []))));

                if ($interestIds !== []) {
                    $modeChoice = collect($this->workspace->pendingChoices())->firstWhere('field', 'meta_audience_mode');
                    $suggestion = collect($modeChoice['options'] ?? [])->firstWhere('value', 'suggestions');
                    $suggestedIds = array_values(array_map('strval', (array) data_get($suggestion, 'arguments.interest_ids', [])));

                    if ($interestIds !== $suggestedIds || $suggestedIds === []) {
                        return $this->json(['ok' => false, 'error' => 'The page suggestions changed. Ask again to refresh them.']);
                    }

                    return $this->saveInterestMatches($campaign, $interestIds, $suggestedIds);
                }

                return $this->json(['ok' => true,
                    'note' => 'Use the stored landing-page analysis to infer three to five relevant Meta interest search terms. Search them with interest_ideas and show the returned Meta options. Do not save until the user selects actual matches.']);
            }

            if ($arguments['audience_mode'] === 'retargeting') {
                return $this->json(['ok' => true,
                    'note' => 'Call campaign__create_website_audience to choose an account pixel and an event it has recorded, then show its final review choices. Create nothing until the user confirms.']);
            }

            return $this->json(['ok' => false, 'error' => 'Choose broad targeting, suggested interests, or retargeting.']);
        }

        if (filled($arguments['interest_ideas'] ?? null)) {
            if ($campaign->platform !== 'meta' || $specialCategories !== ['NONE']) {
                return $this->json(['ok' => false, 'error' => 'Interest targeting is unavailable for this Meta special ad category.']);
            }

            return $this->offerInterestMatches(
                $campaign,
                (string) $arguments['interest_ideas'],
                (array) ($arguments['interest_ids'] ?? []),
            );
        }

        if (array_key_exists('interest_ids', $arguments)) {
            if ($campaign->platform !== 'meta' || $specialCategories !== ['NONE']) {
                return $this->json(['ok' => false, 'error' => 'Interest targeting is unavailable for this campaign or its special ad category.']);
            }

            return $this->saveInterestMatches($campaign, (array) $arguments['interest_ids']);
        }

        if ($section === 'demographics') {
            if ($campaign->platform !== 'meta'
                || $specialCategories !== ['NONE']) {
                return $this->json(['ok' => false, 'error' => 'Age and gender refinements are available only for Meta campaigns without a declared special ad category.']);
            }

            $this->offerDemographics($campaign);

            return $this->json(['ok' => true, 'note' => 'Age and gender choices are on screen. Wait for the user.']);
        }

        if ($invalid = array_diff($countries, array_keys($availableCountries))) {
            return $this->json([
                'ok' => false,
                'error' => 'Unrecognised country codes: '.implode(', ', $invalid).'. Choose countries from the list.',
            ]);
        }

        $supported = $this->supportedPlacements($campaign);
        $requestedPlacements = array_values(array_filter(array_map(
            fn ($value): string => strtolower(trim((string) $value)),
            (array) ($arguments['placements'] ?? []),
        )));
        $unsupported = array_diff($requestedPlacements, $supported);

        if ($unsupported !== []) {
            return $this->json([
                'ok' => false,
                'error' => 'These networks or placements cannot be saved for this campaign: '.implode(', ', $unsupported).'.',
                'supported' => $supported,
            ]);
        }

        if (filled($arguments['countries'] ?? null) && in_array($campaign->platform, ['meta', 'google', 'linkedin'], true)) {
            try {
                $this->countries->resolve((string) $campaign->platform, $countries, $campaign->ad_account_id);
            } catch (RuntimeException|ConnectionException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }

        $devices = $this->limitTo($arguments['devices'] ?? null, Objectives::DEVICES);
        $placements = $this->limitTo($arguments['placements'] ?? null, $supported);
        $demographicsChanged = array_key_exists('age_min', $arguments)
            || array_key_exists('age_max', $arguments)
            || array_key_exists('genders', $arguments);

        if ($demographicsChanged && ($campaign->platform !== 'meta' || ! $demographicsAllowed)) {
            return $this->json(['ok' => false, 'error' => 'Age and gender refinements are available only for Meta campaigns without a declared special ad category.']);
        }

        foreach (['age_min', 'age_max'] as $ageField) {
            if (array_key_exists($ageField, $arguments) && $arguments[$ageField] === null) {
                return $this->json(['ok' => false, 'error' => 'Choose an age range, or omit age fields to keep the current range. Null ages are not supported.']);
            }
        }

        $ageMin = (int) ($arguments['age_min'] ?? $campaign->audience['age_min'] ?? 18);
        $ageMax = (int) ($arguments['age_max'] ?? $campaign->audience['age_max'] ?? 65);

        if ($demographicsChanged && ($ageMin < 13 || $ageMax > 65 || $ageMin > $ageMax)) {
            return $this->json(['ok' => false, 'error' => 'Choose a valid age range from 13 to 65.']);
        }

        $genders = array_map('intval', (array) (array_key_exists('genders', $arguments)
            ? $arguments['genders']
            : ($campaign->audience['genders'] ?? [])));

        if ($demographicsChanged && array_diff($genders, [1, 2]) !== []) {
            return $this->json(['ok' => false, 'error' => 'Gender targeting must use the available Meta options.']);
        }

        if (($arguments['devices'] ?? null) && $devices === []) {
            return $this->json(['ok' => false, 'error' => 'Devices must be mobile and/or desktop.']);
        }

        if (($arguments['placements'] ?? null) && $placements === []) {
            return $this->json([
                'ok' => false,
                'error' => $supported === []
                    ? $this->platforms->for($campaign)->name().' does not take placements here, so leave them unset.'
                    : 'Unrecognised placements.',
                'supported' => $supported,
            ]);
        }

        $audience = array_filter([
            'age_min' => isset($arguments['age_min']) ? $ageMin : ($campaign->audience['age_min'] ?? null),
            'age_max' => isset($arguments['age_max']) ? $ageMax : ($campaign->audience['age_max'] ?? null),
            'genders' => $genders ?: null,
            'devices' => $devices ?: ($campaign->audience['devices'] ?? null),
            'meta_audience_mode' => $campaign->audience['meta_audience_mode'] ?? null,
            'meta_interests' => $campaign->audience['meta_interests'] ?? null,
            'meta_detailed' => $campaign->audience['meta_detailed'] ?? null,
        ], fn ($v) => $v !== null && $v !== []);

        if (array_key_exists('countries', $arguments)) {
            $this->selections->saveCampaignCountries($campaign, $countries);
        }

        $campaign->update([
            'audience' => $audience,
            'placements' => $placements ?: $campaign->placements,
        ]);

        // Countries belong to the brief, not to one platform's campaign.
        //
        // locations has been in SHARED_WITH_BRIEF since the trait was written,
        // and nothing ever wrote it, so the fallback it describes could never
        // fire: every platform started with none and was asked again. "Where
        // should this run" has one answer for a brief, and the buyer gave it
        // three times on arb-dev on 25 Sep.
        //
        // Placements and devices stay on the campaign. Meta sells Messenger
        // and Google sells Search, so those genuinely differ per platform;
        // countries never do.
        $this->rememberCountries($countries);

        // Only what was actually put on screen and answered counts as the
        // user's. Countries and placements were being recorded as theirs while
        // the model chose both without asking.
        //
        // And only what this call set at all. Answering countries used to stamp
        // a source on placements and audience too, so a field nobody had
        // touched inherited the provenance of one that had been.
        $audienceFieldsOffered = $this->workspace->wasOffered('devices')
            || $this->workspace->wasOffered('meta_audience_mode')
            || $this->workspace->wasOffered('meta_interest_selection')
            || $this->workspace->wasOffered('meta_age_range')
            || $this->workspace->wasOffered('meta_gender');
        $audienceChanged = $demographicsChanged || filled($arguments['devices'] ?? null);
        $touched = [
            'locations' => [$this->workspace->wasOffered('countries'), filled($arguments['countries'] ?? null)],
            'audience' => [$audienceFieldsOffered, $audienceChanged],
            'placements' => [$this->workspace->wasOffered('placements'), filled($arguments['placements'] ?? null)],
        ];

        foreach ($touched as $field => [$wasOffered, $changed]) {
            if (! $changed) {
                continue;
            }

            $this->workspace->recordSource($campaign, $field, $wasOffered
                ? ArtifactFieldSource::USER_STATED
                : ArtifactFieldSource::MODEL_INFERRED);
        }

        if ($demographicsChanged && $this->workspace->wasOffered('meta_age_range')) {
            $this->workspace->recordSource($campaign, 'audience_demographics', ArtifactFieldSource::USER_STATED);
        }

        if ($demographicsChanged
            && $this->workspace->wasOffered('meta_age_range')
            && blank($campaign->audience['meta_audience_mode'] ?? null)) {
            $this->offerAudienceModes($campaign);

            return $this->json([
                'ok' => true,
                'campaign_id' => $campaign->id,
                'audience' => $campaign->fresh()->audience,
                'note' => 'Age and gender are saved. Choose the audience type next.',
            ]);
        }

        if (array_key_exists('countries', $arguments)) {
            $kindsByCountry = collect($countries)->mapWithKeys(fn (string $code): array => [
                $code => $this->locationLists->kindsFor($campaign, $code),
            ])->all();
            $this->choices->offerLocationScope(
                (string) $campaign->platform,
                $countries,
                (int) ($campaign->targetingSet()->value('revision') ?? 0),
                $kindsByCountry,
            );

            return $this->json(['ok' => true, 'campaign_id' => $campaign->id, 'countries' => $countries,
                'placements' => $campaign->placements,
                'audience' => $campaign->audience,
                'note' => 'Countries are saved with whole-country targeting as the default. The location choices are on screen; wait for the user.']);
        }

        $shouldOfferNext = $section !== '' || $arguments === [];

        if ($shouldOfferNext) {
            $nextSection = $section;

            if ($nextSection === '') {
                $nextSection = match (true) {
                    $this->supportedPlacements($campaign) !== [] && blank($campaign->placements) => 'placements',
                    $this->supportsDevices($campaign) && blank($campaign->audience['devices'] ?? null) => 'devices',
                    $this->selections->countries($campaign) === [] => 'countries',
                    default => '',
                };
            }

            if ($nextSection === 'placements'
                && $this->supportedPlacements($campaign) !== [] && blank($campaign->placements)) {
                $this->offerPlacements($campaign);

                return $this->json(['ok' => true, 'note' => 'Placement choices are on screen. Wait for the user.']);
            }

            if ($nextSection === 'devices' && $this->supportsDevices($campaign)
                && blank($campaign->audience['devices'] ?? null)) {
                $this->offerDevices($campaign);

                return $this->json(['ok' => true, 'note' => 'Device choices are on screen. Wait for the user.']);
            }

            if ($nextSection === 'countries' && $this->selections->countries($campaign) === []) {
                $verified = $this->countries->verified((string) $campaign->platform);
                $platformName = $this->platforms->for($campaign)->name();

                // "Check at publish" read as a warning about the country and
                // was asked about by name: a buyer seeing it beside a country
                // they know is fine has no way to tell what they are supposed
                // to check. It was never about the country. Every platform has
                // its own id for a place, and this says whether we are holding
                // a confirmed one yet - see CountryCatalog::verified(), which
                // only counts a confirmation from the last 30 days, so a
                // country drifts out of it by sitting still.
                //
                // So the badge is the positive signal only, and the thing that
                // actually happens is in the hint rather than implied by a
                // phrase that sounds like homework.
                $this->choices->offer(
                    field: 'countries',
                    question: 'Which countries should this run in? Search by country name or code and select all that apply.',
                    options: array_map(fn (string $code): array => [
                        'value' => $code,
                        'label' => $availableCountries[$code],
                        'hint' => isset($verified[$code])
                            ? $code
                            : $code.' · we confirm the '.$platformName.' location id when you publish',
                        'badge' => isset($verified[$code]) ? 'Verified' : null,
                        'sends' => 'Target '.$availableCountries[$code],
                    ], array_keys($availableCountries)),
                    multiple: true,
                );

                return $this->json(['ok' => true, 'note' => 'Country choices are on screen. Wait for the user.']);
            }
        }

        return $this->json([
            'ok' => true,
            'campaign_id' => $campaign->id,
            'countries' => $countries,
            'audience' => $audience,
            'placements' => $campaign->placements,
        ]);
    }

    /** @return list<string> */
    private function limitTo(mixed $given, array $allowed): array
    {
        return array_values(array_intersect(
            array_map(fn ($v) => strtolower(trim((string) $v)), (array) $given),
            $allowed,
        ));
    }

    private function offerAudienceModes(Campaign $campaign): void
    {
        $phrases = $this->pageAudiencePhrases($campaign);
        $matches = $this->suggestedInterestMatches($campaign, $phrases);
        $interestIds = array_column($matches, 'id');
        $interestNames = array_column($matches, 'name');
        $suggestionHint = $matches !== []
            ? 'AI-selected interests from this page: '.implode(', ', $phrases).'.'
            : 'No relevant Meta interests were found from this page. Choose another audience option.';

        $summary = $this->detailedTargeting->summary($campaign);
        $hasSelection = $summary !== '' && $summary !== 'Saved targeting needs review.';
        $options = [
            ['value' => 'suggestions', 'label' => 'AI suggestions from this page', 'badge' => 'Suggested',
                'hint' => $suggestionHint,
                'disabled' => $matches === [],
                'arguments' => ['interest_ids' => $interestIds],
                'sends' => $matches !== []
                    ? 'Use the AI-selected interests: '.implode(', ', $interestNames).'.'
                    : 'AI interest suggestions are unavailable for this page.'],
            ['value' => 'demographics', 'label' => 'Demographics',
                'hint' => 'Education, work, relationship, family and life events.',
                'sends' => 'Refine the Meta audience with demographics.'],
            ['value' => 'interests', 'label' => 'Interests',
                'hint' => 'Business, technology, entertainment, shopping, hobbies, fitness and more.',
                'sends' => 'Refine the Meta audience with interests.'],
            ['value' => 'behaviors', 'label' => 'Behaviors',
                'hint' => 'Digital activity, purchase, travel and device use, where Meta still offers them.',
                'sends' => 'Refine the Meta audience with behaviors.'],
            ['value' => 'broad', 'label' => 'Broad audience',
                'hint' => 'Reach broadly within the selected age range and gender, without interest targeting.',
                'sends' => 'Use broad Meta audience targeting.'],
            ['value' => 'retargeting', 'label' => 'Retarget pixel visitors',
                'hint' => 'Build a website audience from an event this account pixel has recorded.',
                'sends' => 'Create a retargeting audience from an observed pixel event and let me review the audience and draft campaign before creating anything.'],
        ];

        if ($hasSelection) {
            array_unshift($options, [
                'value' => 'done',
                'label' => 'Keep this audience',
                'badge' => 'Suggested',
                'sends' => 'Keep this Meta audience.',
            ]);
            $options[] = [
                'value' => 'remove',
                'label' => 'Remove a selection',
                'sends' => 'Remove Meta audience targeting.',
            ];
        }

        $this->choices->offer(
            field: 'meta_audience_mode',
            question: $hasSelection
                ? 'Who should see these ads? Current audience: '.$summary.'.'
                : 'Who should see these ads?',
            options: $options,
            allowOther: true,
            otherLabel: 'Custom interest ideas',
            otherHint: 'Edit the page-based ideas or describe the interests you want to target.',
            otherPlaceholder: 'e.g. doctors, medical students',
            otherValue: implode(', ', $phrases),
            otherPosition: 1,
        );
    }

    /**
     * Phrases for this page, asked of the model once and kept on the brief.
     *
     * The audience step is offered again after age and gender, and again if the
     * buyer comes back to it. A campaign with no ad account cannot search Meta,
     * so it does not spend a model call on phrases that cannot be used.
     *
     * @return list<string>
     */
    private function pageAudiencePhrases(Campaign $campaign): array
    {
        if (blank($campaign->ad_account_id)) {
            return [];
        }

        $brief = $this->briefs->current();
        $analysis = $brief?->pageAnalysis();

        if ($brief === null || $analysis === null) {
            return [];
        }

        $stored = $brief->page_analysis['audience_phrases'] ?? null;

        if (is_array($stored) && $stored !== []) {
            return array_values(array_filter(
                array_map(strval(...), $stored),
                fn (string $phrase): bool => $phrase !== '',
            ));
        }

        $phrases = $this->audiencePhrases->forPage($analysis);

        if ($phrases !== []) {
            $page = $brief->page_analysis;
            $page['audience_phrases'] = $phrases;
            $brief->update(['page_analysis' => $page]);
        }

        return $phrases;
    }

    /**
     * Meta interests for the OpenAI phrases, keeping a name only when it fits the phrase.
     *
     * @param  list<string>  $phrases
     * @return list<array{id: string, name: string, path: list<string>}>
     */
    private function suggestedInterestMatches(Campaign $campaign, array $phrases): array
    {
        if ($phrases === [] || blank($campaign->ad_account_id)) {
            return [];
        }

        $matches = collect();

        foreach (array_slice($phrases, 0, 5) as $phrase) {
            $matches = $matches->concat($this->matchingInterests($campaign, $phrase)->take(2));
        }

        return $matches
            ->filter(fn (array $match): bool => preg_match('/^[0-9]+$/D', (string) ($match['id'] ?? '')) === 1
                && filled($match['name'] ?? null))
            ->unique(fn (array $match): string => (string) $match['id'])
            ->take(6)
            ->map(fn (array $match): array => [
                'id' => (string) $match['id'],
                'name' => (string) $match['name'],
                'path' => array_values(array_filter(array_map('strval', (array) ($match['path'] ?? [])))),
            ])
            ->values()
            ->all();
    }

    /**
     * @return Collection<int, array<string, mixed>>
     */
    private function matchingInterests(Campaign $campaign, string $phrase): Collection
    {
        $queries = [$phrase];
        $tokens = $this->significantTokens($phrase);
        usort($tokens, fn (string $left, string $right): int => mb_strlen($right) <=> mb_strlen($left));

        if (isset($tokens[0]) && mb_strtolower($tokens[0]) !== mb_strtolower($phrase)) {
            $queries[] = $tokens[0];
        }

        foreach ($queries as $query) {
            try {
                $found = collect($this->meta->targetingInterests((string) $campaign->ad_account_id, $query));
            } catch (RuntimeException|ConnectionException) {
                continue;
            }

            $fitting = $found->filter(fn (array $match): bool => $this->interestFitsPhrase((string) ($match['name'] ?? ''), $phrase));

            if ($fitting->isNotEmpty()) {
                return $fitting->values();
            }
        }

        return collect();
    }

    /**
     * The phrase has to name the same thing as a word in the interest.
     *
     * "yoga" fits "Yoga", and "blocker" fits "Ad blocking" because both reduce
     * to "block". A raw prefix does not: "block" is also the start of
     * "Blockchain" and "Blockbuster", which are different words.
     */
    private function interestFitsPhrase(string $name, string $phrase): bool
    {
        $nameWords = $this->significantTokens($name);
        $phraseTokens = $this->significantTokens($phrase);

        if ($nameWords === [] || $phraseTokens === []) {
            return false;
        }

        foreach ($phraseTokens as $token) {
            foreach ($nameWords as $word) {
                if ($this->stem($token) === $this->stem($word)) {
                    return true;
                }
            }

            if ($this->tokenIsInitials($token, $nameWords)) {
                return true;
            }
        }

        return false;
    }

    private function stem(string $word): string
    {
        foreach (['ing', 'ers', 'er', 'or', 's'] as $suffix) {
            if ($suffix === 's' && str_ends_with($word, 'ss')) {
                continue;
            }

            $stemLength = mb_strlen($word) - mb_strlen($suffix);

            if ($stemLength >= 3 && str_ends_with($word, $suffix)) {
                return mb_substr($word, 0, $stemLength);
            }
        }

        return $word;
    }

    /**
     * "vpn" is the initials of "Virtual private network".
     *
     * Only a vowel-less token, so ordinary words are not treated as acronyms.
     *
     * @param  list<string>  $words
     */
    private function tokenIsInitials(string $token, array $words): bool
    {
        if (mb_strlen($token) < 3 || mb_strlen($token) > 4 || preg_match('/[aeiou]/', $token) === 1) {
            return false;
        }

        $initials = implode('', array_map(
            fn (string $word): string => mb_substr($word, 0, 1),
            $words,
        ));

        return $initials === $token;
    }

    /**
     * @return list<string>
     */
    private function significantTokens(string $text): array
    {
        $words = preg_split('/[^\pL]+/u', mb_strtolower($text)) ?: [];
        $stop = ['the', 'and', 'for', 'with', 'your', 'from', 'this', 'that', 'you', 'our', 'are', 'online', 'free'];

        return array_values(array_filter(
            $words,
            fn (string $word): bool => mb_strlen($word) >= 3 && ! in_array($word, $stop, true),
        ));
    }

    private function offerDemographics(Campaign $campaign): void
    {
        $ageMin = (int) ($campaign->audience['age_min'] ?? 18);
        $ageMax = (int) ($campaign->audience['age_max'] ?? 65);

        $this->choices->offer(
            field: 'meta_age_range',
            question: 'Choose a minimum and maximum age. Meta targets the full range between them.',
            options: [],
            control: [
                'type' => 'age_range',
                'minimum' => 18,
                'maximum' => 65,
                'age_min' => max(18, min(65, $ageMin)),
                'age_max' => max(18, min(65, $ageMax)),
            ],
        );
        $this->choices->offer(
            field: 'meta_gender',
            question: 'Choose a gender setting.',
            options: [
                ['value' => 'all', 'label' => 'All genders', 'badge' => 'Broad', 'sends' => 'Include all genders.'],
                ['value' => '1', 'label' => 'Men', 'sends' => 'Target men.'],
                ['value' => '2', 'label' => 'Women', 'sends' => 'Target women.'],
            ],
        );
    }

    private function saveBroadAudience(Campaign $campaign): string
    {
        $audience = (array) $campaign->audience;
        unset($audience['meta_interests'], $audience['meta_detailed']);
        $audience['meta_audience_mode'] = 'broad';
        $meta = (array) $campaign->meta;
        unset($meta['meta_audience_reviewed'], $meta['meta_audience_facet']);
        $campaign->update(['audience' => $audience, 'meta' => $meta]);
        $this->workspace->recordSource($campaign, 'audience', $this->workspace->wasOffered('meta_audience_mode')
            ? ArtifactFieldSource::USER_STATED : ArtifactFieldSource::MODEL_INFERRED);

        return $this->json(['ok' => true, 'campaign_id' => $campaign->id, 'audience' => $campaign->fresh()->audience,
            'note' => 'Broad audience targeting is set for the selected locations.']);
    }

    /** @param list<string> $retainedIds */
    private function offerInterestMatches(Campaign $campaign, string $ideas, array $retainedIds = []): string
    {
        $terms = $this->interestTerms($ideas);

        if ($terms === []) {
            return $this->json(['ok' => false, 'error' => 'Enter up to five audience ideas, such as doctors or medical students. Locations are set separately.']);
        }

        $previous = collect();

        if ($retainedIds !== []) {
            $oldOffer = collect($this->workspace->pendingChoices())->firstWhere('field', 'meta_interest_selection');
            $oldOptions = collect($oldOffer['options'] ?? []);
            $retained = array_values(array_unique(array_map('strval', $retainedIds)));

            if (array_diff($retained, $oldOptions->pluck('value')->all()) !== []) {
                return $this->json(['ok' => false, 'error' => 'Choose retained interests from the current Meta results.']);
            }

            $previous = $oldOptions->filter(fn (array $option): bool => in_array($option['value'], $retained, true))
                ->map(fn (array $option): array => [
                    'id' => (string) $option['value'],
                    'name' => (string) $option['label'],
                    'path' => [],
                ]);
        }

        try {
            $matches = $previous->concat(collect($terms)->flatMap(fn (string $term): array => $this->meta->targetingInterests(
                (string) $campaign->ad_account_id,
                $term,
            )))->filter(fn (array $match): bool => preg_match('/^[0-9]+$/D', (string) ($match['id'] ?? '')) === 1
                && filled($match['name'] ?? null))
                ->unique(fn (array $match): string => (string) $match['id'])
                ->take(30)
                ->values();
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        if ($matches->isEmpty()) {
            return $this->json(['ok' => false, 'error' => 'Meta found no matching interests. Try a shorter audience idea.']);
        }

        $this->choices->offer(
            field: 'meta_interest_selection',
            question: 'Choose the Meta interests to include.',
            options: $matches->map(function (array $match): array {
                $name = (string) $match['name'];
                $path = collect((array) ($match['path'] ?? []))
                    ->map(fn (mixed $part): string => trim((string) $part))
                    ->reject(fn (string $part): bool => strcasecmp($part, $name) === 0)
                    ->implode(' · ');

                return [
                    'value' => (string) $match['id'],
                    'label' => $name,
                    'hint' => $path,
                    'sends' => 'Include the Meta interest '.$name.'.',
                ];
            })->all(),
            multiple: true,
            allowOther: true,
            otherLabel: 'Custom',
            otherHint: 'Add your own audience idea in plain English.',
            otherPlaceholder: 'e.g. target local dentists, exclude current customers',
        );

        return $this->json(['ok' => true, 'ideas' => $terms,
            'note' => 'Meta matches are on screen. Say they are suggestions and wait for the user to select them.']);
    }

    /** @return list<string> */
    private function interestTerms(string $ideas): array
    {
        $parts = preg_split('/[,;\n]+/u', $ideas, 6, PREG_SPLIT_NO_EMPTY) ?: [];
        $terms = [];

        foreach (array_slice($parts, 0, 5) as $part) {
            $term = preg_replace('/^(?:target|reach|find|show ads to)\s+/iu', '', trim($part)) ?? trim($part);
            $term = preg_replace('/\b(?:in|from|within)\s+(?:the\s+)?(?:u\.?s\.?a?\.?|united states)\b/iu', '', $term) ?? $term;
            $term = preg_replace('/\b(?:etcetera|etc)\.?$/iu', '', $term) ?? $term;
            $term = trim($term, " \t\n\r\0\x0B.,!?-");

            if (mb_strlen($term) >= 2 && mb_strlen($term) <= 80) {
                $terms[] = $term;
            }
        }

        return array_values(array_unique($terms));
    }

    /** @param list<string> $ids */
    private function saveInterestMatches(Campaign $campaign, array $ids, ?array $offeredIdsOverride = null): string
    {
        $ids = array_values(array_unique(array_map('strval', $ids)));
        $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'meta_interest_selection'
            && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());
        $offeredIds = $offeredIdsOverride ?? array_column($offered['options'] ?? [], 'value');

        if ($ids === [] || count($ids) > 20 || array_diff($ids, $offeredIds) !== []) {
            return $this->json(['ok' => false, 'error' => 'Choose interests from the current Meta search results.']);
        }

        try {
            $validated = collect($this->meta->validateTargetingInterests((string) $campaign->ad_account_id, $ids))
                ->keyBy(fn (array $interest): string => (string) ($interest['id'] ?? ''));
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $selected = [];

        foreach ($ids as $id) {
            $interest = $validated->get($id);

            if (! is_array($interest) || ($interest['valid'] ?? false) !== true || blank($interest['name'] ?? null)) {
                return $this->json(['ok' => false, 'error' => 'A selected Meta interest is no longer available. Search again before choosing it.']);
            }

            $selected[] = ['id' => $id, 'name' => (string) $interest['name']];
        }

        $audience = (array) $campaign->audience;
        $audience['meta_audience_mode'] = 'custom';
        $audience['meta_interests'] = $selected;
        $campaign->update(['audience' => $audience]);
        $this->workspace->recordSource($campaign, 'audience', $this->workspace->wasOffered('meta_interest_selection')
            ? ArtifactFieldSource::USER_STATED : ArtifactFieldSource::MODEL_INFERRED);

        return $this->json(['ok' => true, 'campaign_id' => $campaign->id, 'selected' => $selected,
            'note' => 'The selected Meta interests are saved.']);
    }
}
