<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Targeting\LocationCatalogImporter;
use App\Campaigns\Targeting\LocationDiscovery;
use App\Campaigns\Targeting\LocationListResolver;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\ArtifactFieldSource;
use App\Models\GoogleAdsConnection;
use App\Models\PlatformLocation;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

class ChooseLocation implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly LocationDiscovery $discovery,
        private readonly LocationCatalogImporter $catalogImporter,
        private readonly TargetingSelections $selections,
        private readonly LocationListResolver $listResolver,
    ) {}

    public function description(): Stringable|string
    {
        return 'For a Meta or Google draft campaign, search cities or states/regions within a selected country '
            .'and offer the exact matching places for the user to choose. Call with country_code, kind '
            .'and query to search; pass an external_id from those results to select it. Never guess a place ID. '
            .'Call with no arguments after countries are selected to offer whole-country, city, or state targeting. '
            .'Use scope=whole only after the user chooses the offered whole-country option, with its targeting revision. '
            .'If geography is already selected, call with change_scope=true only when the user asks to change it. '
            .'An offered scope=city, scope=region, or US scope=dma choice opens a country-aware search field; wait for the user to enter a place name. '
            .'For Google Search, operation=exclude selects a verified city or region to exclude while retaining its selected country. '
            .'A selected city or region narrows its country; call again to add another place. '
            .'Omit query to list selected places. Pass offer_removal=true only when the user asks to remove one, then remove_external_id to remove it. '
            .'When a brief has shared places, pass shared_place_id from the pending list when selecting the equivalent provider place. '
            .'Only use place_intent_mode=override or clear when the user explicitly wants to replace or remove shared place targeting. '
            .'For Google, refine common names with a comma and state or province, e.g. Springfield, Illinois. '
            .'Google Search, Meta, and LinkedIn can select a verified US market (kind=dma) after the user chooses it. Provider market boundaries and IDs differ. '
            .'For a radius, use kind=radius with user-confirmed latitude, longitude, distance and km/mi; omit the center to list existing radii. '
            .'Use kind=presence to offer Google Search presence-only or presence-or-interest choices. Radius exclusions are unavailable.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'scope' => $schema->string()->description('whole only, after the user selects the offered whole-country option.'),
            'change_scope' => $schema->boolean()->description('Offer geography scope choices again only when the user asks to change existing targeting.'),
            'country_code' => $schema->string()->description('Selected two-letter country code, e.g. US. Required when searching or removing a place.'),
            'operation' => $schema->string()->description('include (default), or exclude for a Google Search city/region.'),
            'kind' => $schema->string()->description('city or region (state/province), US dma, radius, or presence for a Google Search location matching preference.'),
            'query' => $schema->string()->description('At least two characters of the city or region name; omit to list current selections.'),
            'catalog_places' => $schema->array()->items($schema->string())->description('Database location IDs selected from the offered city, region, or DMA checkboxes for country_code.'),
            'page' => $schema->integer()->description('Meta search page 1 to 4. Google supports only page 1; refine its query instead.'),
            'external_id' => $schema->string()->description('Exact provider key from a search result. Omit to offer choices.'),
            'remove_external_id' => $schema->string()->description('Exact provider ID of a currently selected city or region to remove.'),
            'offer_removal' => $schema->boolean()->description('true only when the user asks to remove a selected city or region; shows them to choose from.'),
            'shared_place_id' => $schema->integer()->description('Brief shared place ID from the pending list. Use when choosing its exact equivalent on this platform.'),
            'place_intent_mode' => $schema->string()->description('inherit, override, or clear shared city/state intent. Only change after an explicit user choice.'),
            'expected_revision' => $schema->integer()->description('Targeting revision returned by the search, to reject stale selections.'),
            'latitude' => $schema->number()->description('Confirmed center latitude for kind=radius; do not infer a city center.'),
            'longitude' => $schema->number()->description('Confirmed center longitude for kind=radius.'),
            'radius' => $schema->number()->description('Radius distance from 1 to 50, for kind=radius.'),
            'radius_unit' => $schema->string()->description('km or mi for kind=radius.'),
            'confirmed_center' => $schema->boolean()->description('True only after the user confirms the exact coordinates, country, distance, and unit.'),
            'remove_selection_id' => $schema->integer()->description('Saved radius selection ID returned by the list; removes only that Google Search radius.'),
            'presence_mode' => $schema->string()->description('PRESENCE or PRESENCE_OR_INTEREST, after the user chooses an offered Google Search location option.'),
        ];
    }

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

        $args = $request->all();

        if (filled($args['place_intent_mode'] ?? null)) {
            if (! in_array($campaign->platform, ['meta', 'google', 'linkedin'], true)) {
                return $this->json(['ok' => false, 'error' => 'Shared place targeting is available for Meta, Google, and LinkedIn campaigns only.']);
            }

            try {
                $mode = strtolower(trim((string) $args['place_intent_mode']));
                $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'shared_place_mode'
                    && (string) ($choice['focus_type'] ?? '') === (string) $campaign->getMorphClass()
                    && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey()
                );

                if ($offered === null || ! collect($offered['options'] ?? [])->contains(fn (array $option): bool => $option['value'] === $mode)) {
                    return $this->json(['ok' => false, 'error' => 'Show the shared place choices and wait for the user to select an override or clear.']);
                }

                if ($campaign->platform === 'linkedin' && $mode !== 'clear') {
                    return $this->json(['ok' => false, 'error' => 'LinkedIn supports an explicit clear of shared city/state intent, but cannot select a replacement city or state yet.']);
                }

                $set = $this->selections->setPlaceIntentMode($campaign, $mode, isset($args['expected_revision']) ? (int) $args['expected_revision'] : null);
                $this->workspace->recordSource($campaign, 'locations', ArtifactFieldSource::USER_STATED);

                return $this->json(['ok' => true, 'place_intent_mode' => $mode, 'revision' => $set->revision]);
            } catch (RuntimeException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }

        if ($campaign->platform === 'linkedin') {
            $pending = $this->selections->pendingSharedPlaces($campaign);

            if ($pending !== []) {
                $this->offerSharedPlaceMode(true);

                return $this->json([
                    'ok' => false,
                    'pending_shared_places' => $pending,
                    'revision' => $campaign->targetingSet()->value('revision') ?? 0,
                    'error' => 'LinkedIn cannot verify city or state targeting. Ask the user whether this campaign may target its selected whole countries instead.',
                ]);
            }

            if (in_array(strtolower((string) ($args['kind'] ?? '')), ['city', 'region', 'state', 'province'], true)
                || in_array(strtolower((string) ($args['scope'] ?? '')), ['city', 'region'], true)) {
                return $this->json([
                    'ok' => false,
                    'error' => 'LinkedIn city and state selection is unavailable because its location search does not confirm place type and parent. Country and verified US DMA targeting remain available.',
                ]);
            }
        }

        if (! in_array($campaign->platform, ['meta', 'google', 'linkedin'], true) || $campaign->isPublished()) {
            return $this->json(['ok' => false, 'error' => 'Location selection is available for draft campaigns only.']);
        }

        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Verify the ad account before searching locations.']);
        }

        $platform = (string) $campaign->platform;
        $platformName = match ($platform) {
            'meta' => 'Meta', 'google' => 'Google Ads', default => 'LinkedIn',
        };
        $selectionOperation = strtolower(trim((string) ($args['operation'] ?? 'include')));

        if (! in_array($selectionOperation, ['include', 'exclude'], true)
            || ($selectionOperation === 'exclude' && ($platform !== 'google' || ($campaign->campaign_type ?: 'search') !== 'search'))) {
            return $this->json(['ok' => false, 'error' => 'City and region exclusions are available for Google Search drafts only.']);
        }

        if ($selectionOperation === 'exclude' && filled($args['shared_place_id'] ?? null)) {
            return $this->json(['ok' => false, 'error' => 'A shared place must be included or explicitly cleared; it cannot be resolved by an exclusion.']);
        }

        $selectedCountries = $this->selections->countries($campaign);
        // A specific place chosen alongside a scope is the more specific answer.
        $scope = filled($args['external_id'] ?? null) ? '' : strtolower(trim((string) ($args['scope'] ?? '')));

        if (in_array($scope, ['whole', 'city', 'region', 'dma', 'postal', 'list'], true)) {
            $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'location_scope'
                && (string) ($choice['focus_type'] ?? '') === (string) $campaign->getMorphClass()
                && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());
            $selectedOption = collect($offered['options'] ?? [])->firstWhere('value', $scope);

            if ($selectedOption === null || ! isset($selectedOption['revision'])) {
                return $this->json(['ok' => false, 'error' => 'Offer the geography choices and wait for the user to select one.']);
            }

            $revision = (int) ($args['expected_revision'] ?? $selectedOption['revision']);

            if ($revision !== (int) $selectedOption['revision']
                || $revision !== (int) ($campaign->targetingSet()->value('revision') ?? 0)) {
                return $this->json(['ok' => false, 'error' => 'Targeting changed since these choices were shown. Review the current locations.']);
            }

            if ($scope === 'list') {
                $this->choices->offerLocationList($selectedCountries, collect($selectedCountries)
                    ->mapWithKeys(fn (string $code): array => [$code => $this->listResolver->kindsFor($campaign, $code)])->all(), $revision);

                return $this->json(['ok' => true, 'scope' => 'list',
                    'note' => 'The advanced targeting form is on screen. Wait for the user to paste their places.']);
            }

            if ($scope === 'postal') {
                $this->choices->offerLocationList($selectedCountries, collect($selectedCountries)
                    ->mapWithKeys(fn (string $code): array => [$code => in_array('postal', $this->listResolver->kindsFor($campaign, $code), true) ? ['postal'] : []])->all(), $revision);

                return $this->json(['ok' => true, 'scope' => 'postal',
                    'note' => 'The postal-code form is on screen. Ask the user to paste postal codes for the selected country.']);
            }

            if ($scope !== 'whole') {
                if (($campaign->targetingSet()->first()?->options['place_intent_mode'] ?? null) === 'clear') {
                    $this->selections->setPlaceIntentMode($campaign, 'override', $revision);
                }

                $this->choices->offerLocationSearch($scope, $scope === 'dma' ? ['US'] : $selectedCountries, $platform,
                    $campaign->targetingSet()->value('revision') ?? 0);

                return $this->json(['ok' => true, 'scope' => $scope, 'countries' => $selectedCountries,
                    'note' => 'A country-aware place search is on screen. Wait for the user to enter a name, then offer exact provider matches.']);
            }

            try {
                $set = $this->selections->chooseWholeCountries($campaign, $revision);
                $this->workspace->recordSource($campaign, 'locations', ArtifactFieldSource::USER_STATED);

                return $this->json(['ok' => true, 'scope' => 'whole', 'countries' => $selectedCountries, 'revision' => $set->revision]);
            } catch (RuntimeException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }

        if ($scope !== '') {
            return $this->json(['ok' => false, 'error' => 'Choose whole countries, or search a specific city or state.']);
        }

        if ($args === [] || ($args['change_scope'] ?? null) === true) {
            if ($selectedCountries === []) {
                return $this->json(['ok' => false, 'error' => 'Choose countries before choosing a place or market.']);
            }

            if ($args === [] && $this->selections->hasCompletedGeographyScope($campaign)) {
                return $this->json(['ok' => true, 'countries' => $selectedCountries,
                    'revision' => $campaign->targetingSet()->value('revision') ?? 0,
                    'note' => 'Geography has already been selected. Move to the next campaign step.']);
            }

            if (collect($this->choices->all())->contains(fn (array $choice): bool => in_array($choice['field'] ?? null,
                ['location_search', 'meta_location', 'google_location', 'google_location_exclude', 'linkedin_location'], true))) {
                return $this->json(['ok' => true, 'note' => 'The place search or exact provider results are already on screen. Wait for the user to choose.']);
            }

            $revision = $campaign->targetingSet()->value('revision') ?? 0;
            $kindsByCountry = collect($selectedCountries)->mapWithKeys(fn (string $code): array => [
                $code => $this->listResolver->kindsFor($campaign, $code),
            ])->all();
            $this->choices->offerLocationScope($platform, $selectedCountries, $revision, $kindsByCountry);

            return $this->json(['ok' => true, 'countries' => $selectedCountries, 'revision' => $revision,
                'note' => 'Ask the user to choose an offered location scope. Search by name after a specific-place choice; never assume a provider ID.']);
        }

        if ($platform === 'google') {
            // The campaign's own account, not the configured one.
            //
            // This demanded they be the same, which was true while the allow
            // list held one account and stopped being true when it was opened
            // and the flow began asking which of the manager's children to buy
            // on. Mohsin's campaign was on 2099157735 and the configured
            // customer is 3460855874, so every attempt to narrow his targeting
            // came back "Not accepted: location search" - three times, for
            // regions and for cities, with nothing on screen saying why.
            //
            // A geoTargetConstant is not account-scoped: it means the same
            // thing on every customer, so the account here only decides who
            // the read is attributed to. Whether that account may be reached
            // at all is the allow list's answer, and it is asked of every call
            // on the way out.
            if (GoogleAdsConnection::shared() === null) {
                return $this->json(['ok' => false, 'error' => GoogleAdsConnection::missingReason()]);
            }

            if (blank($campaign->ad_account_id)) {
                return $this->json(['ok' => false, 'error' => 'Verify the Google Ads account before choosing locations.']);
            }
        }

        $countryCode = strtoupper(trim((string) ($args['country_code'] ?? '')));
        $requestedKind = strtolower(trim((string) ($args['kind'] ?? '')));
        $kind = match ($requestedKind) {
            'state', 'province' => 'region',
            default => $requestedKind,
        };
        $term = trim((string) ($args['query'] ?? ''));
        $page = (int) ($args['page'] ?? 1);

        if (($selectionOperation === 'exclude' || $kind === 'dma')
            && (filled($args['external_id'] ?? null) || filled($args['remove_external_id'] ?? null))
            && ! isset($args['expected_revision'])) {
            return $this->json(['ok' => false, 'error' => 'Provide the targeting revision from the search or selected-place list.']);
        }

        if (! preg_match('/^[A-Z]{2}$/D', $countryCode)) {
            return $this->json(['ok' => false, 'error' => 'Provide a two-letter country code.']);
        }

        try {
            if (array_key_exists('catalog_places', $args) && $args['catalog_places'] !== []) {
                $ids = $args['catalog_places'];
                $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'location_search'
                    && (string) ($choice['focus_type'] ?? '') === (string) $campaign->getMorphClass()
                    && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());
                if (! in_array($kind, ['city', 'region', 'dma'], true) || $selectionOperation !== 'include'
                    || ! in_array($countryCode, $selectedCountries, true)
                    || ($offered['search']['kind'] ?? null) !== $kind
                    || ! in_array($countryCode, $offered['search']['countries'] ?? [], true)
                    || ! isset($offered['search']['revision'])
                    || (int) $offered['search']['revision'] !== (int) ($campaign->targetingSet()->value('revision') ?? 0)
                    || ! is_array($ids) || ! array_is_list($ids) || count($ids) > 20
                    || collect($ids)->contains(fn (mixed $id): bool => ! is_string($id) || ! ctype_digit($id))
                    || count($ids) !== count(array_unique($ids))) {
                    return $this->json(['ok' => false, 'error' => 'Choose places from the offered database list for this country.']);
                }

                $stored = PlatformLocation::query()->with('location')->whereKey($ids)->get()->keyBy(fn (PlatformLocation $mapping): string => (string) $mapping->getKey());

                if ($stored->count() !== count($ids) || collect($ids)->contains(function (string $id) use ($stored, $platform, $kind, $countryCode): bool {
                    $mapping = $stored->get($id);

                    return $mapping?->platform !== $platform || ! in_array($mapping->status, ['verified', 'unverified'], true)
                        || $mapping->location?->type !== $kind || $mapping->location->country_code !== $countryCode;
                })) {
                    return $this->json(['ok' => false, 'error' => 'A listed place changed. Search again for an exact provider location.']);
                }

                $mappings = array_map(fn (string $id): PlatformLocation => $this->discovery->select(
                    $platform, $kind, $countryCode, $stored[$id]->location->name,
                    $stored[$id]->external_id, $campaign->ad_account_id,
                ), $ids);
                $revision = (int) $offered['search']['revision'];

                $set = DB::transaction(function () use ($campaign, $mappings, $revision, $kind, $platform) {
                    foreach ($mappings as $mapping) {
                        $set = match (true) {
                            $kind === 'dma' && $platform === 'google' => $this->selections->addGoogleDma($campaign, $mapping, $revision),
                            $kind === 'dma' => $this->selections->addPlatformDma($campaign, $mapping, $revision),
                            default => $this->selections->addCampaignLocation($campaign, $mapping, $revision),
                        };
                        $revision = $set->revision;
                    }

                    return $set;
                });
                $this->workspace->recordSource($campaign, 'locations', ArtifactFieldSource::USER_STATED);

                return $this->json(['ok' => true, 'selected' => array_map(fn (PlatformLocation $mapping): string => (string) $mapping->provider_name, $mappings),
                    'revision' => $set->revision,
                    'note' => 'These places are saved. Continue to the next step; do not search for, confirm or offer to remove them.']);
            }

            if ($kind === 'presence') {
                if ($platform !== 'google' || ($campaign->campaign_type ?: 'search') !== 'search'
                    || $selectionOperation !== 'include'
                    || ! in_array($countryCode, $this->selections->countries($campaign), true)) {
                    return $this->json(['ok' => false, 'error' => 'Location presence choices are available for Google Search drafts with a selected country.']);
                }

                $mode = strtoupper(trim((string) ($args['presence_mode'] ?? '')));

                if ($mode === '') {
                    $this->choices->offer(
                        field: 'google_location_presence',
                        question: 'Should Google reach people in the selected locations only, or also people interested in them?',
                        options: [
                            ['value' => 'PRESENCE', 'label' => 'In selected locations', 'sends' => 'Use Google presence-only location matching.'],
                            ['value' => 'PRESENCE_OR_INTEREST', 'label' => 'In or interested in', 'sends' => 'Use Google presence-or-interest location matching.'],
                        ],
                    );

                    return $this->json(['ok' => true, 'current' => $this->selections->googlePresenceMode($campaign), 'revision' => $campaign->targetingSet()->value('revision') ?? 0]);
                }

                $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'google_location_presence'
                    && (string) ($choice['focus_type'] ?? '') === (string) $campaign->getMorphClass()
                    && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());

                if ($offered === null || ! collect($offered['options'] ?? [])->contains(fn (array $option): bool => $option['value'] === $mode)
                    || ! isset($args['expected_revision'])) {
                    return $this->json(['ok' => false, 'error' => 'Offer the presence choices and use the current targeting revision after the user selects one.']);
                }

                $set = $this->selections->setGooglePresenceMode($campaign, $mode, (int) $args['expected_revision']);
                $this->workspace->recordSource($campaign, 'locations', ArtifactFieldSource::USER_STATED);

                return $this->json(['ok' => true, 'presence_mode' => $mode, 'revision' => $set->revision]);
            }

            if ($kind === 'radius') {
                if ($platform !== 'google' || ($campaign->campaign_type ?: 'search') !== 'search'
                    || $selectionOperation !== 'include' || filled($args['external_id'] ?? null)
                    || filled($args['shared_place_id'] ?? null)
                    || ! in_array($countryCode, $this->selections->countries($campaign), true)) {
                    return $this->json(['ok' => false, 'error' => 'Radius targeting requires a Google Search draft and one of its selected countries. Radius exclusions are unsupported.']);
                }

                if (isset($args['remove_selection_id'])) {
                    if (! isset($args['expected_revision'])) {
                        return $this->json(['ok' => false, 'error' => 'Provide the current targeting revision to remove a radius.']);
                    }

                    $set = $this->selections->removeGoogleRadius($campaign, $countryCode, (int) $args['remove_selection_id'], (int) $args['expected_revision']);

                    return $this->json(['ok' => true, 'revision' => $set->revision, 'note' => 'Radius removed. Review the remaining locations before publishing.']);
                }

                if (! isset($args['latitude'], $args['longitude'], $args['radius'], $args['radius_unit'])) {
                    return $this->json([
                        'ok' => true,
                        'selected' => $this->selections->selectedGoogleRadii($campaign),
                        'revision' => $campaign->targetingSet()->value('revision') ?? 0,
                        'note' => 'Ask the user for an exact map point, country, distance, and unit before adding a radius. Never substitute a city center.',
                    ]);
                }

                if (! isset($args['expected_revision']) || ! is_numeric($args['latitude'])
                    || ! is_numeric($args['longitude']) || ! is_numeric($args['radius'])) {
                    return $this->json(['ok' => false, 'error' => 'Provide numeric coordinates, distance, unit, and the current targeting revision.']);
                }

                $latitude = round((float) $args['latitude'], 6);
                $longitude = round((float) $args['longitude'], 6);
                $radius = round((float) $args['radius'], 2);
                $unit = strtolower(trim((string) $args['radius_unit']));

                if (! is_finite($latitude) || ! is_finite($longitude) || ! is_finite($radius)
                    || $latitude <= -90 || $latitude >= 90 || $longitude <= -180 || $longitude >= 180
                    || $radius < 1 || $radius > 50 || ! in_array($unit, ['km', 'mi'], true)) {
                    return $this->json(['ok' => false, 'error' => 'Use a valid map point and a radius of 1 to 50 km or mi.']);
                }

                $revision = (int) $args['expected_revision'];
                $label = sprintf('Radius %.2F %s around %.6F, %.6F (%s)', $radius, $unit, $latitude, $longitude, $countryCode);
                $choiceKey = hash('sha256', implode('|', [$campaign->getKey(), $revision, $countryCode, $label]));

                if (($args['confirmed_center'] ?? null) !== true) {
                    $this->choices->offer(
                        field: 'google_radius_confirmation',
                        question: 'Is this the exact map point and radius you want to target?',
                        options: [[
                            'value' => $choiceKey, 'label' => $label,
                            'sends' => 'Confirm targeting '.$label.' at revision '.$revision.'.',
                        ]],
                    );

                    return $this->json(['ok' => true, 'needs_confirmation' => true, 'label' => $label, 'revision' => $revision]);
                }

                $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'google_radius_confirmation'
                    && (string) ($choice['focus_type'] ?? '') === (string) $campaign->getMorphClass()
                    && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());

                if ($offered === null || ! collect($offered['options'] ?? [])->contains(fn (array $option): bool => $option['value'] === $choiceKey)) {
                    return $this->json(['ok' => false, 'error' => 'Offer this exact center and distance for user confirmation before saving it.']);
                }

                $set = $this->selections->addGoogleRadius(
                    $campaign, $countryCode, $latitude, $longitude, $radius, $unit, $revision,
                );
                $this->workspace->recordSource($campaign, 'locations', ArtifactFieldSource::USER_STATED);

                return $this->json([
                    'ok' => true,
                    'selected' => $this->selections->selectedGoogleRadii($campaign),
                    'revision' => $set->revision,
                    'note' => 'The reviewed circle replaces whole-country targeting for this country. Publication still needs approval and provider readback.',
                ]);
            }

            if ($kind === 'dma') {
                if ($countryCode !== 'US' || $selectionOperation !== 'include'
                    || ($platform === 'google' && ($campaign->campaign_type ?: 'search') !== 'search')
                    || filled($args['shared_place_id'] ?? null)
                    || ! in_array('US', $this->selections->countries($campaign), true)) {
                    return $this->json(['ok' => false, 'error' => 'DMA selection requires a supported draft with US selected. Markets cannot exclude or resolve a shared city.']);
                }
            } elseif ($platform === 'linkedin') {
                return $this->json(['ok' => false, 'error' => 'LinkedIn place selection supports verified US DMA markets only.']);
            }

            if (filled($args['remove_external_id'] ?? null)) {
                $set = $selectionOperation === 'exclude'
                    ? $this->selections->removeGoogleLocationExclusion($campaign, $countryCode, (string) $args['remove_external_id'], isset($args['expected_revision']) ? (int) $args['expected_revision'] : null)
                    : $this->selections->removeCampaignLocation($campaign, $countryCode, (string) $args['remove_external_id'], isset($args['expected_revision']) ? (int) $args['expected_revision'] : null);

                return $this->json([
                    'ok' => true,
                    'revision' => $set->revision,
                    'note' => $selectionOperation === 'exclude'
                        ? 'Location exclusion removed. The selected country remains targeted.'
                        : 'Location removed. If this was the last selected place in the country, the whole country is targeted again.',
                ]);
            }

            if ($term === '') {
                $selected = $this->selections->selectedCampaignLocations($campaign, $countryCode, $selectionOperation, $kind === 'dma' ? 'dma' : null);
                $pending = array_values(array_filter($this->selections->pendingSharedPlaces($campaign),
                    fn (array $place): bool => $place['country_code'] === $countryCode,
                ));

                if ($pending !== []) {
                    $this->offerSharedPlaceMode(false);
                }

                if ($selected === []) {
                    return $this->json([
                        'ok' => true,
                        'selected' => [],
                        'pending_shared_places' => $pending,
                        'revision' => $campaign->targetingSet()->value('revision') ?? 0,
                        'note' => $selectionOperation === 'exclude'
                            ? 'No cities or regions are excluded in this country.'
                            : ($pending === []
                            ? 'No cities or regions are selected in this country. The whole country is targeted.'
                            : 'These shared places still need an exact provider selection before publishing. Search each name and pass its shared_place_id, or ask the user to explicitly override or clear them.'),
                    ]);
                }

                $revision = $campaign->targetingSet()->value('revision') ?? 0;

                if (($args['offer_removal'] ?? false) !== true) {
                    return $this->json(['ok' => true, 'selected' => $selected, 'pending_shared_places' => $pending, 'revision' => $revision,
                        'note' => 'These places are already saved. Continue to the next step unless the user asked to change them.']);
                }

                $this->choices->offer(
                    field: $platform.'_location_'.$selectionOperation.'_removal',
                    question: $kind === 'dma' ? 'Which market should be removed?'
                        : ($selectionOperation === 'exclude' ? 'Which excluded city or region should be removed?' : 'Which city or region should be removed?'),
                    options: array_map(fn (array $place): array => [
                        'value' => $place['external_id'],
                        'label' => $place['label'],
                        'sends' => sprintf('Remove %s %s location ID %s from %s at targeting revision %d', $platformName, $selectionOperation, $place['external_id'], $countryCode, $revision),
                    ], $selected),
                );

                return $this->json(['ok' => true, 'selected' => $selected, 'pending_shared_places' => $pending, 'revision' => $revision]);
            }

            if (! in_array($countryCode, $this->selections->countries($campaign), true)) {
                return $this->json(['ok' => false, 'error' => 'Choose the country on this campaign before selecting one of its cities or regions.']);
            }

            if (filled($args['external_id'] ?? null)) {
                [$mapping, $set] = DB::transaction(function () use ($campaign, $platform, $kind, $countryCode, $term, $args, $page, $selectionOperation): array {
                    $mapping = $this->discovery->select($platform, $kind, $countryCode, $term, (string) $args['external_id'], $campaign->ad_account_id, $page);
                    $set = match (true) {
                        $kind === 'dma' && $platform === 'google' => $this->selections->addGoogleDma($campaign, $mapping, isset($args['expected_revision']) ? (int) $args['expected_revision'] : null),
                        $kind === 'dma' => $this->selections->addPlatformDma($campaign, $mapping, isset($args['expected_revision']) ? (int) $args['expected_revision'] : null),
                        $selectionOperation === 'exclude' => $this->selections->addGoogleLocationExclusion($campaign, $mapping, isset($args['expected_revision']) ? (int) $args['expected_revision'] : null),
                        default => $this->selections->addCampaignLocation(
                            $campaign,
                            $mapping,
                            isset($args['expected_revision']) ? (int) $args['expected_revision'] : null,
                            isset($args['shared_place_id']) ? (int) $args['shared_place_id'] : null,
                        ),
                    };

                    return [$mapping, $set];
                });
                $this->workspace->recordSource($campaign, 'locations', $this->workspace->wasOffered($platform.'_location'.($selectionOperation === 'exclude' ? '_exclude' : ''))
                    ? ArtifactFieldSource::USER_STATED
                    : ArtifactFieldSource::MODEL_INFERRED);

                return $this->json([
                    'ok' => true,
                    'selected' => $mapping->provider_name,
                    'country_code' => $countryCode,
                    'revision' => $set->revision,
                    'pending_shared_places' => $this->selections->pendingSharedPlaces($campaign),
                    'note' => match (true) {
                        $kind === 'dma' => 'This exact provider market narrows US targeting. Search again to add another market.',
                        $selectionOperation === 'exclude' => 'This exact city or region is excluded. The selected country remains targeted.',
                        default => 'This country is now narrowed to its selected cities or regions. Search again to add another place.',
                    },
                ]);
            }

            $matches = $this->discovery->search($platform, $kind, $countryCode, $term, $campaign->ad_account_id, $page);
            $this->catalogImporter->store($matches);

            $alreadySelected = collect($this->selections->selectedCampaignLocations($campaign, $countryCode, $selectionOperation, $kind === 'dma' ? 'dma' : null))
                ->pluck('external_id')->map(fn (mixed $id): string => (string) $id)->all();
            $repeated = array_values(array_filter($matches, fn (array $match): bool => in_array((string) $match['external_id'], $alreadySelected, true)));
            $matches = array_values(array_filter($matches, fn (array $match): bool => ! in_array((string) $match['external_id'], $alreadySelected, true)));

            if ($matches === [] && $repeated !== []) {
                return $this->json(['ok' => true, 'already_selected' => array_column($repeated, 'label'),
                    'note' => 'Already selected. Continue to the next step; do not offer it again.']);
            }

            if ($matches === []) {
                if ($selectionOperation === 'include' && in_array($kind, ['city', 'region', 'dma'], true)) {
                    $this->choices->offerLocationSearch($kind, $kind === 'dma' ? ['US'] : $selectedCountries, $platform,
                        $campaign->targetingSet()->value('revision') ?? 0);
                }

                return $this->json(['ok' => false, 'error' => 'No matching places on this page. Try a more specific search or an earlier page.']);
            }

            $revision = $campaign->targetingSet()->value('revision') ?? 0;
            // Exact places answer the scope question; showing both lets the user pick contradictory answers.
            $this->choices->withdraw('location_scope');
            $this->choices->offer(
                field: $platform.'_location'.($selectionOperation === 'exclude' ? '_exclude' : ''),
                question: 'Which '.match ($kind) {
                    'city' => 'city', 'dma' => 'market area', default => 'state or region'
                }.' should this campaign '.($selectionOperation === 'exclude' ? 'exclude' : 'target').'?',
                options: array_map(fn (array $match): array => [
                    'value' => $match['external_id'],
                    'arguments' => [
                        'country_code' => $countryCode,
                        'operation' => $selectionOperation,
                        'kind' => $kind,
                        'query' => $term,
                        'page' => $page,
                        'external_id' => $match['external_id'],
                        'expected_revision' => $revision,
                    ],
                    'label' => $match['label'],
                    'hint' => $platformName.' ID '.$match['external_id'],
                    'sends' => sprintf(
                        '%s %s %s (%s ID %s) from search "%s" in %s, page %d, targeting revision %d',
                        $selectionOperation === 'exclude' ? 'Exclude' : 'Target',
                        $kind,
                        $match['label'],
                        $platformName,
                        $match['external_id'],
                        $term,
                        $countryCode,
                        $page,
                        $revision,
                    ),
                ], $matches),
            );

            return $this->json([
                'ok' => true,
                'matches' => count($matches),
                'page' => $page,
                'revision' => $revision,
                'pending_shared_places' => $this->selections->pendingSharedPlaces($campaign),
                'note' => count($matches) === 25
                    ? ($platform === 'meta' && $page < 4
                        ? 'Matching places are on screen. If the right one is missing, search the next page or refine the name.'
                        : 'Matching places are on screen. If the right one is missing, refine the name; for Google, add the state or province after a comma.')
                    : 'Matching places are on screen. Ask the user to choose the exact place.',
            ]);
        } catch (RuntimeException|InvalidArgumentException|ConnectionException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    private function offerSharedPlaceMode(bool $linkedin): void
    {
        $options = [[
            'value' => 'clear',
            'label' => 'Target whole countries',
            'hint' => 'Remove shared city and state restrictions for this campaign.',
            'sends' => 'Explicitly clear the shared city and state targeting for this campaign and target its selected whole countries.',
        ]];

        if (! $linkedin) {
            $options[] = [
                'value' => 'override',
                'label' => 'Choose different places',
                'hint' => 'Keep this campaign’s selected places instead of the brief’s shared places.',
                'sends' => 'Explicitly override the brief’s shared cities and states for this campaign. I will choose different provider places.',
            ];
        }

        $this->choices->offer(
            field: 'shared_place_mode',
            question: $linkedin
                ? 'LinkedIn cannot target the shared cities or states. Target the selected whole countries instead?'
                : 'Change the shared cities and states for this campaign? To keep them, search and select each exact provider place.',
            options: $options,
        );
    }
}
