<?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\Campaigns\Targeting\LocationListResolver;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\PlatformLocation;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\DB;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

/**
 * Advanced targeting: lists of states, cities, markets and postal codes.
 *
 * Sits beside the one-place-at-a-time flow rather than replacing it. A list is
 * checked against the provider, shown for review, and only the places the user
 * confirms are saved, together, at the targeting revision they reviewed.
 */
class TargetLocationList implements Tool
{
    use ActsOnFocusedCampaign;

    /** Tool argument => stored location kind. */
    public const LISTS = ['regions' => 'region', 'cities' => 'city', 'dmas' => 'dma', 'postal_codes' => 'postal'];

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

    public function description(): Stringable|string
    {
        return 'Advanced targeting for a draft campaign: lists of states/regions, cities, US market areas (DMAs) '
            .'and postal codes (pincodes, ZIP codes). Call with no lists to show a form where the user pastes them. '
            .'When the user has already typed a list in chat, pass it in regions, cities, dmas or postal_codes '
            .'with country_code; the matches are shown for review and nothing is saved until the user confirms. '
            .'Use this whenever the user gives more than one place or any postal code. Never guess provider IDs.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'country_code' => $schema->string()->description('Two-letter code of a country already selected on the campaign. Optional when only one is selected.'),
            'regions' => $schema->array()->items($schema->string())->description('State or region names.'),
            'cities' => $schema->array()->items($schema->string())->description('City names. Add the state after a comma when it is ambiguous, e.g. "Springfield, Illinois".'),
            'dmas' => $schema->array()->items($schema->string())->description('US market (DMA) names.'),
            'postal_codes' => $schema->array()->items($schema->string())->description('Postal codes, ZIP codes or pincodes.'),
        ];
    }

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

        $args = $request->all();

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

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

        $countries = $this->selections->countries($campaign);

        if ($countries === []) {
            return $this->json(['ok' => false, 'error' => 'Choose the campaign\'s countries before adding places.']);
        }

        if (array_key_exists('selected', $args)) {
            return $this->save($campaign, (array) $args['selected']);
        }

        if (collect($this->choices->all())->contains(fn (array $choice): bool => ($choice['field'] ?? null) === 'location_list')) {
            return $this->json(['ok' => true, 'note' => 'The targeting form is already on screen. Wait for the user to paste their places.']);
        }

        $lists = [];

        foreach (self::LISTS as $argument => $kind) {
            $value = $args[$argument] ?? [];
            // Items the model passes are one place each, so "Springfield, Missouri" keeps its state.
            $lists[$kind] = is_array($value)
                ? array_values(array_unique(array_filter(array_map(fn (mixed $item): string => trim((string) $item), $value))))
                : $this->resolver->split((string) $value, commaSeparated: $kind === 'postal');
        }

        if (array_sum(array_map('count', $lists)) === 0) {
            $this->choices->offerLocationList($countries, $this->kindsByCountry($campaign, $countries),
                (int) ($campaign->targetingSet()->value('revision') ?? 0));

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

        $countryCode = strtoupper(trim((string) ($args['country_code'] ?? (count($countries) === 1 ? $countries[0] : ''))));

        if (! in_array($countryCode, $countries, true)) {
            return $this->json(['ok' => false, 'error' => 'Choose which selected country these places are in.', 'countries' => $countries]);
        }

        try {
            $entries = $this->resolver->resolve($campaign, $countryCode, $lists);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        return $this->offerReview($campaign, $countryCode, $entries);
    }

    /**
     * @param  list<string>  $countries
     * @return array<string, list<string>>
     */
    private function kindsByCountry(Campaign $campaign, array $countries): array
    {
        return collect($countries)->mapWithKeys(fn (string $code): array => [$code => $this->resolver->kindsFor($campaign, $code)])->all();
    }

    /**
     * @param  list<array{kind: string, input: string, status: string, options: list<array{external_id: string, label: string}>, reason?: string}>  $entries
     */
    private function offerReview(Campaign $campaign, string $countryCode, array $entries): string
    {
        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);
        $options = [];

        foreach ($entries as $entry) {
            if (! in_array($entry['status'], ['matched', 'ambiguous'], true)) {
                continue;
            }

            foreach ($entry['options'] as $option) {
                $options[] = ['value' => $entry['kind'].'|'.$option['external_id'], 'label' => $option['label']];
            }
        }

        $summary = collect($entries)->groupBy('status')->map->count()->all();

        if ($options !== []) {
            $this->choices->offerLocationReview($countryCode, $revision, $entries, $options);
        }

        return $this->json([
            'ok' => true,
            'country_code' => $countryCode,
            'summary' => $summary,
            'missing' => collect($entries)->where('status', 'missing')->pluck('input')->values()->all(),
            'reasons' => collect($entries)->where('status', 'missing')->whereNotNull('reason')
                ->mapWithKeys(fn (array $entry): array => [$entry['input'] => $entry['reason']])->all(),
            'note' => $options === []
                ? 'Nothing new to add: every entry was already selected or not found. Say which were not found and ask the user to check them.'
                : 'The matches are on screen for review. Say how many matched and which were not found, then wait. Nothing is saved yet.',
        ]);
    }

    /** @param list<mixed> $selected */
    private function save(Campaign $campaign, array $selected): string
    {
        $offered = collect($this->workspace->pendingChoices())->first(fn (array $choice): bool => ($choice['field'] ?? null) === 'location_list_review'
            && (string) ($choice['focus_type'] ?? '') === (string) $campaign->getMorphClass()
            && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey());
        $review = $offered['review'] ?? null;

        if (! is_array($review) || $selected === []) {
            return $this->json(['ok' => false, 'error' => 'Show the reviewed places and wait for the user to confirm them.']);
        }

        if ((int) $review['revision'] !== (int) ($campaign->targetingSet()->value('revision') ?? 0)) {
            return $this->json(['ok' => false, 'error' => 'Targeting changed since these places were checked. Check the list again.']);
        }

        foreach ($selected as $value) {
            if (! is_string($value)) {
                return $this->json(['ok' => false, 'error' => 'Choose places from the reviewed list, one per entry.']);
            }
        }

        $selected = array_values(array_unique($selected));

        // Which input each offered value answers, so an ambiguous entry yields one place.
        $inputs = [];
        foreach ($review['entries'] as $index => $entry) {
            if (in_array($entry['status'], ['matched', 'ambiguous'], true)) {
                foreach ($entry['options'] as $option) {
                    $inputs[$entry['kind'].'|'.$option['external_id']] = $index;
                }
            }
        }

        $picked = [];
        foreach ($selected as $value) {
            $index = $inputs[(string) $value] ?? null;

            if (! is_string($value) || $index === null || isset($picked[$index])) {
                return $this->json(['ok' => false, 'error' => 'Choose places from the reviewed list, one per entry.']);
            }

            $picked[$index] = $value;
        }

        $countryCode = (string) $review['country_code'];

        try {
            $mappings = [];
            foreach ($picked as $index => $value) {
                [$kind, $externalId] = explode('|', $value, 2);
                $name = trim(explode(',', $review['entries'][$index]['input'], 2)[0]);
                $mappings[] = [$kind, $this->discovery->select(
                    (string) $campaign->platform, $kind, $countryCode, $name, $externalId, $campaign->ad_account_id,
                )];
            }

            $set = DB::transaction(function () use ($campaign, $mappings, $review) {
                $revision = (int) $review['revision'];

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

                $set = null;
                foreach ($mappings as [$kind, $mapping]) {
                    /** @var PlatformLocation $mapping */
                    $set = match (true) {
                        $kind === 'dma' && $campaign->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;
            });
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

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

        return $this->json([
            'ok' => true,
            'saved' => array_map(fn (array $pair): string => (string) $pair[1]->provider_name, $mappings),
            'revision' => $set?->revision,
            'note' => 'These places are saved and narrow '.$countryCode.' to them. Continue to the next step.',
        ]);
    }
}
