<?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\LocationDiscovery;
use App\Models\Campaign;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Places a live Meta ad set can target, as buttons.
 *
 * Creation does not use this. A draft still picks a place through
 * choose_location, and this list is not part of that step.
 */
class ListLiveLocations implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly Choices $choices,
        private readonly LocationDiscovery $locations,
    ) {}

    public function description(): Stringable|string
    {
        return 'List places a live Meta ad set can target, as buttons the user can tap. '
            .'With no query, list every state Meta returns for the country already on the ad set. '
            .'More than one state may be chosen. With a query, show the matching cities or states, each '
            .'with its name and key. Nothing is saved here. After they continue, call edit_entity once '
            .'with targeting.geo_locations set to every chosen key, grouped by kind. A state or city '
            .'replaces the country, so omit countries. Do not ask them to name one state first, and do '
            .'not guess a key. Do not use this while creating a campaign.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'ad_set' => $schema->string()
                ->description('The ad set id or its current name.')
                ->required(),
            'query' => $schema->string()
                ->description('Optional. A city or place to search. Omit to list every state in the country already on the ad set.'),
            'kind' => $schema->string()
                ->description('Optional. region for a state, city for a city, or dma for a market. Omit to search states and cities.'),
            'country_code' => $schema->string()
                ->description('Optional. Two-letter country to search. Omit to use the country already on the ad set, or US.'),
            'keep' => $schema->array()->items($schema->object([
                'kind' => $schema->string()->description('region, city, or dma.')->required(),
                'key' => $schema->string()->description('The Meta key already shown for this place.')->required(),
                'name' => $schema->string()->description('The place name already shown.')->required(),
            ]))->description('Optional. Places already chosen. Shown again with the new search matches. Do not drop them and do not invent a key.'),
        ];
    }

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

        if ($campaign === null || $campaign->platform !== 'meta' || ! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'Locations are listed here only for an ad set that is already live. A draft uses choose_location.',
            ]);
        }

        $given = trim((string) ($request->all()['ad_set'] ?? ''));

        if ($given === '') {
            return $this->json(['ok' => false, 'error' => 'Name the ad set whose location should change.']);
        }

        $kind = strtolower(trim((string) ($request->all()['kind'] ?? '')));

        if ($kind !== '' && ! in_array($kind, ['region', 'city', 'dma'], true)) {
            return $this->json(['ok' => false, 'error' => 'Kind is region, city, or dma.']);
        }

        $resolved = $this->resolve($campaign, $given);

        if (isset($resolved['error'])) {
            return $this->json(['ok' => false, 'error' => $resolved['error']]);
        }

        try {
            $live = $this->meta->on($campaign->id, null)->readAdSet($resolved['id'], $campaign->ad_account_id);
        } catch (MetaException $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'The saved location could not be read, so nothing was changed.',
            ]);
        }

        $targeting = is_array($live['targeting'] ?? null) ? $live['targeting'] : [];
        $geo = is_array($targeting['geo_locations'] ?? null) ? $targeting['geo_locations'] : [];
        $current = $this->current($geo);
        $country = $this->country($geo, (string) ($request->all()['country_code'] ?? ''));

        if ($country === null) {
            return $this->json(['ok' => false, 'error' => 'Country code is two letters, such as US.']);
        }

        $query = trim((string) ($request->all()['query'] ?? ''));

        if ($query === '' && ! in_array($kind, ['city', 'dma'], true)) {
            try {
                $states = $this->states((string) $campaign->ad_account_id, $country);
            } catch (Throwable $exception) {
                return $this->json([
                    'ok' => false,
                    'error' => $exception->getMessage(),
                    'current' => $current,
                    'note' => 'The state list could not be read. Nothing was changed.',
                ]);
            }

            $this->offer($resolved['id'], [], $states, allowOther: false, question: 'Which states should this ad set target?');

            return $this->json([
                'ok' => true,
                'ad_set_id' => $resolved['id'],
                'current' => $current,
                'country_code' => $country,
                'matches' => $states,
                'note' => $states === []
                    ? 'Meta returned no states for that country. Say so and do not invent a key.'
                    : 'Every state Meta returned is listed, with its name and key. More than one may be chosen. Do not ask the user to search one state at a time. Wait for Continue. Then call edit_entity once with every chosen region key in one targeting.geo_locations, and omit countries.',
            ]);
        }

        if ($query === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Name the city or market to search for. Leave the query empty to list every state.',
            ]);
        }

        try {
            $matches = $this->matches((string) $campaign->ad_account_id, $country, $query, $kind);
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'current' => $current,
                'note' => 'The location search could not be read. Nothing was changed.',
            ]);
        }

        $kept = $this->kept($request->all()['keep'] ?? []);
        $listed = $this->merge($kept, $matches);
        $this->offer($resolved['id'], [], $listed);

        return $this->json([
            'ok' => true,
            'ad_set_id' => $resolved['id'],
            'current' => $current,
            'country_code' => $country,
            'kept' => $kept,
            'matches' => $matches,
            'note' => $listed === []
                ? 'Meta has no place matching that name. Say so and do not invent a key.'
                : 'The buttons are Meta\'s matches, each with its name and key. More than one may be chosen. Wait for Continue. Then call edit_entity once with every chosen key in one targeting.geo_locations, and omit countries. A new search must pass keep with the places already chosen.',
        ]);
    }

    /**
     * @param  list<array{kind: string, key: string, name: string}>  $current
     * @param  list<array{kind: string, key: string, name: string, label: string}>  $matches
     */
    private function offer(string $adSetId, array $current, array $matches, bool $allowOther = true, string $question = 'Which places should this ad set target?'): void
    {
        $options = [];

        foreach ($current as $place) {
            $options[] = [
                'value' => 'current:'.$place['kind'].':'.$place['key'],
                'label' => 'Current: '.$place['name'],
                'hint' => 'ID '.$place['key'],
                'badge' => 'Current',
                'sends' => sprintf(
                    'Ad set %s already targets %s (%s key %s). Do not change the location until a search result is chosen.',
                    $adSetId,
                    $place['name'],
                    $place['kind'],
                    $place['key'],
                ),
            ];
        }

        foreach ($matches as $place) {
            $options[] = [
                'value' => $place['kind'].':'.$place['key'],
                'label' => $place['label'].' · '.$place['kind'],
                'hint' => 'ID '.$place['key'],
                'sends' => sprintf(
                    'On ad set %s, include %s (%s key %s). Call edit_entity once with entity_type ad_set, id %s, and targeting.geo_locations set to every included place in this message. Put regions under regions, cities under cities, and markets under geo_markets, each as {"key":"%s"}. Do not include countries.',
                    $adSetId,
                    $place['name'],
                    $place['kind'],
                    $place['key'],
                    $adSetId,
                    $place['key'],
                ),
            ];
        }

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

        $this->choices->offer(
            'live_location',
            $question,
            $options,
            multiple: true,
            allowOther: $allowOther,
            otherLabel: 'Search',
            otherHint: 'Search Meta for a city or state that is not listed.',
            otherPlaceholder: 'New York',
        );
    }

    /**
     * @return list<array{kind: string, key: string, name: string, label: string}>
     */
    private function states(string $account, string $country): array
    {
        $states = [];

        foreach ($this->locations->regions('meta', $country, $account) as $candidate) {
            $states[] = [
                'kind' => 'region',
                'key' => (string) $candidate['external_id'],
                'name' => (string) $candidate['name'],
                'label' => (string) $candidate['label'],
            ];

            if (count($states) >= 200) {
                return $states;
            }
        }

        return $states;
    }

    /**
     * @return list<array{kind: string, key: string, name: string, label: string}>
     */
    private function matches(string $account, string $country, string $query, string $kind): array
    {
        $kinds = $kind === '' ? ['region', 'city'] : [$kind];
        $matches = [];
        $seen = [];

        foreach ($kinds as $one) {
            foreach ($this->locations->search('meta', $one, $country, $query, $account) as $candidate) {
                $key = (string) $candidate['external_id'];
                $identity = $one.':'.$key;

                if (isset($seen[$identity])) {
                    continue;
                }

                $seen[$identity] = true;
                $matches[] = [
                    'kind' => $one,
                    'key' => $key,
                    'name' => (string) $candidate['name'],
                    'label' => (string) $candidate['label'],
                ];

                if (count($matches) >= 25) {
                    return $matches;
                }
            }
        }

        return $matches;
    }

    /**
     * @param  list<array{kind: string, key: string, name: string, label: string}>  $kept
     * @param  list<array{kind: string, key: string, name: string, label: string}>  $matches
     * @return list<array{kind: string, key: string, name: string, label: string}>
     */
    private function merge(array $kept, array $matches): array
    {
        $listed = [];
        $seen = [];

        foreach ([...$kept, ...$matches] as $place) {
            $identity = $place['kind'].':'.$place['key'];

            if (isset($seen[$identity])) {
                continue;
            }

            $seen[$identity] = true;
            $listed[] = $place;

            if (count($listed) >= 25) {
                return $listed;
            }
        }

        return $listed;
    }

    /**
     * @return list<array{kind: string, key: string, name: string, label: string}>
     */
    private function kept(mixed $given): array
    {
        if (! is_array($given)) {
            return [];
        }

        $places = [];

        foreach ($given as $place) {
            if (! is_array($place)) {
                continue;
            }

            $kind = strtolower(trim((string) ($place['kind'] ?? '')));
            $key = trim((string) ($place['key'] ?? ''));
            $name = trim((string) ($place['name'] ?? ''));

            if (! in_array($kind, ['region', 'city', 'dma'], true) || $key === '' || $name === '') {
                continue;
            }

            if (preg_match('/^[\pL\pN .\x27,&():-]{1,80}$/uD', $key) !== 1) {
                continue;
            }

            $places[] = [
                'kind' => $kind,
                'key' => $key,
                'name' => $name,
                'label' => $name,
            ];
        }

        return $places;
    }

    /**
     * @param  array<string, mixed>  $geo
     * @return list<array{kind: string, key: string, name: string}>
     */
    private function current(array $geo): array
    {
        $places = [];

        foreach ((array) ($geo['countries'] ?? []) as $code) {
            if (! is_string($code) || preg_match('/^[A-Za-z]{2}$/D', $code) !== 1) {
                continue;
            }

            $code = strtoupper($code);
            $places[] = [
                'kind' => 'country',
                'key' => $code,
                'name' => $code === 'US' ? 'United States' : $code,
            ];
        }

        foreach (['regions' => 'region', 'cities' => 'city', 'zips' => 'ZIP', 'geo_markets' => 'market'] as $field => $kind) {
            foreach ((array) ($geo[$field] ?? []) as $place) {
                if (! is_array($place)) {
                    continue;
                }

                $key = trim((string) ($place['key'] ?? ''));
                $name = trim((string) ($place['name'] ?? ''));

                if ($key === '' || $name === '') {
                    continue;
                }

                $places[] = ['kind' => $kind, 'key' => $key, 'name' => $name];
            }
        }

        return $places;
    }

    /**
     * @param  array<string, mixed>  $geo
     */
    private function country(array $geo, string $given): ?string
    {
        $given = strtoupper(trim($given));

        if ($given !== '') {
            return preg_match('/^[A-Z]{2}$/D', $given) === 1 ? $given : null;
        }

        $countries = [];

        foreach ((array) ($geo['countries'] ?? []) as $code) {
            if (is_string($code) && preg_match('/^[A-Za-z]{2}$/D', $code) === 1) {
                $countries[] = strtoupper($code);
            }
        }

        if (count($countries) === 1) {
            return $countries[0];
        }

        return 'US';
    }

    /**
     * @return array{id: string, name: ?string}|array{error: string}
     */
    private function resolve(Campaign $campaign, string $given): array
    {
        try {
            $rows = $this->meta->on($campaign->id, null)
                ->adSets((string) $campaign->external_campaign_id, $campaign->ad_account_id, fresh: true);
        } catch (Throwable $exception) {
            return ['error' => 'The ad sets could not be read, so nothing was changed. '.$exception->getMessage()];
        }

        foreach ($rows as $row) {
            if ((string) ($row['id'] ?? '') === $given) {
                $name = trim((string) ($row['name'] ?? ''));

                return ['id' => $given, 'name' => $name !== '' ? $name : null];
            }
        }

        $matches = array_values(array_filter(
            $rows,
            static fn (array $row): bool => strcasecmp(trim((string) ($row['name'] ?? '')), $given) === 0,
        ));

        if (count($matches) === 1) {
            return ['id' => (string) $matches[0]['id'], 'name' => trim((string) ($matches[0]['name'] ?? $given))];
        }

        if ($matches !== []) {
            return ['error' => 'More than one ad set is named '.$given.'. Nothing was changed.'];
        }

        return ['error' => $given.' is not an ad set id or name in this campaign, so nothing was changed.'];
    }
}
