<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Services\Meta\MetaException;
use RuntimeException;

/**
 * Turns pasted lists of places into reviewed provider matches.
 *
 * Every entry is searched with the same provider search the single-place flow
 * uses, so a pasted list can never select something a one-at-a-time search
 * would not have offered. Nothing is saved here.
 */
class LocationListResolver
{
    /** Each entry is one provider search, so a check is capped to keep a chat turn responsive. */
    public const MAX_ENTRIES = 30;

    /** How many candidates an ambiguous entry offers. */
    private const MAX_OPTIONS = 5;

    public function __construct(
        private readonly LocationDiscovery $discovery,
        private readonly TargetingSelections $selections,
    ) {}

    /**
     * The kinds a campaign can target by list on its platform.
     *
     * @return list<string>
     */
    public function kindsFor(Campaign $campaign, string $countryCode): array
    {
        $dma = $countryCode === 'US'
            && ($campaign->platform !== 'google' || ($campaign->campaign_type ?: 'search') === 'search');

        return match ($campaign->platform) {
            'meta', 'google' => array_values(array_filter(['region', 'city', $dma ? 'dma' : null, 'postal'])),
            default => [],
        };
    }

    /**
     * Named places use lines or semicolons so city/state qualifiers stay together.
     * Postal codes may also be separated by commas.
     *
     * @return list<string>
     */
    public function split(string $raw, bool $commaSeparated = false): array
    {
        $raw = trim($raw);

        if ($raw === '') {
            return [];
        }

        $parts = preg_split($commaSeparated ? '/[\r\n;,]+/' : '/[\r\n;]+/', $raw) ?: [];

        return array_values(array_unique(array_filter(array_map(
            fn (string $part): string => trim(preg_replace('/\s+/u', ' ', $part) ?? ''),
            $parts,
        ), fn (string $part): bool => $part !== '')));
    }

    /**
     * @param  array<string, list<string>>  $lists  kind => entries
     * @return list<array{kind: string, input: string, status: string, options: list<array{external_id: string, label: string}>, reason?: string}>
     */
    public function resolve(Campaign $campaign, string $countryCode, array $lists): array
    {
        $kinds = $this->kindsFor($campaign, $countryCode);
        $total = array_sum(array_map('count', $lists));

        if ($total > self::MAX_ENTRIES) {
            throw new RuntimeException(sprintf('Check up to %d places at a time. This list has %d.', self::MAX_ENTRIES, $total));
        }

        $entries = [];

        foreach ($lists as $kind => $inputs) {
            if ($inputs === []) {
                continue;
            }

            if (! in_array($kind, $kinds, true)) {
                throw new RuntimeException(ucfirst($this->kindLabel($kind)).' targeting is not available for this campaign and country.');
            }

            $selected = array_column($this->selections->selectedCampaignLocations($campaign, $countryCode, 'include', $kind), 'external_id');
            $matched = [];

            foreach ($inputs as $input) {
                $entry = $this->resolveOne($campaign, $countryCode, $kind, $input, $selected);

                if ($entry['status'] === 'matched') {
                    $externalId = $entry['options'][0]['external_id'];

                    if (in_array($externalId, $matched, true)) {
                        continue;
                    }

                    $matched[] = $externalId;
                }

                $entries[] = $entry;
            }
        }

        return $entries;
    }

    /**
     * @param  list<string>  $selected  provider IDs already targeted for this kind
     * @return array{kind: string, input: string, status: string, options: list<array{external_id: string, label: string}>, reason?: string}
     */
    private function resolveOne(Campaign $campaign, string $countryCode, string $kind, string $input, array $selected): array
    {
        [$name, $qualifier] = array_pad(array_map('trim', explode(',', $input, 2)), 2, '');
        $entry = ['kind' => $kind, 'input' => $input, 'status' => 'missing', 'options' => []];

        try {
            $candidates = $this->discovery->search((string) $campaign->platform, $kind, $countryCode, $name, $campaign->ad_account_id);
        } catch (MetaException $exception) {
            // A throttled or unauthorised lookup is not "not found"; reporting every place missing would be wrong.
            throw $exception;
        } catch (RuntimeException|\InvalidArgumentException $exception) {
            return [...$entry, 'reason' => $exception->getMessage()];
        }

        if ($qualifier !== '') {
            $candidates = array_values(array_filter($candidates,
                fn (array $candidate): bool => $this->matchesQualifier($candidate['label'], $qualifier)));
        }

        $exact = array_values(array_filter($candidates,
            fn (array $candidate): bool => $this->sameName($kind, $candidate['name'], $name)));

        // A lone result that only adds detail ("New York" -> "New York, NY") is the same place.
        if ($exact === [] && count($candidates) === 1
            && str_starts_with(mb_strtolower($candidates[0]['name']), mb_strtolower($name))) {
            $exact = $candidates;
        }
        $shown = array_slice($exact !== [] ? $exact : $candidates, 0, self::MAX_OPTIONS);
        $options = array_map(fn (array $candidate): array => [
            'external_id' => $candidate['external_id'],
            'label' => $candidate['label'],
        ], $shown);

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

        if (count($exact) === 1 && in_array($exact[0]['external_id'], $selected, true)) {
            return [...$entry, 'status' => 'already', 'options' => $options];
        }

        return [...$entry, 'status' => count($exact) === 1 ? 'matched' : 'ambiguous', 'options' => $options];
    }

    private function sameName(string $kind, string $candidate, string $input): bool
    {
        if ($kind === 'postal') {
            $normalise = fn (string $value): string => strtoupper(preg_replace('/\s+/', '', $value) ?? '');

            return $normalise($candidate) === $normalise($input);
        }

        return mb_strtolower(trim($candidate)) === mb_strtolower(trim($input));
    }

    private function matchesQualifier(string $label, string $qualifier): bool
    {
        $normalise = fn (string $value): string => trim(mb_strtolower(preg_replace('/[^\pL\pN]+/u', ' ', $value) ?? ''));
        $labelParts = array_map($normalise, explode(',', $label));
        $qualifierParts = array_values(array_filter(array_map($normalise, explode(',', $qualifier))));

        foreach ($qualifierParts as $part) {
            if (! in_array($part, $labelParts, true)) {
                return false;
            }
        }

        return $qualifierParts !== [];
    }

    public function kindLabel(string $kind): string
    {
        return match ($kind) {
            'region' => 'state or region',
            'city' => 'city',
            'dma' => 'market area',
            'postal' => 'postal code',
            default => $kind,
        };
    }
}
