<?php

namespace App\Campaigns\Targeting;

use App\Models\Campaign;
use App\Models\TargetingSet;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class SearchKeywordSelections
{
    /**
     * Google's three, in the order a buyer widens through them.
     *
     * Named because the screen offers them and this class validates them, and
     * those two lists disagreeing is how a match type the UI offers becomes a
     * keyword the save refuses.
     */
    public const MATCH_TYPES = ['BROAD', 'PHRASE', 'EXACT'];

    /**
     * A backstop on a runaway payload, and Google's number rather than ours.
     *
     * There was a product cap of twenty included keywords here. It was this
     * product's own invention, and it was reported the moment a term could be
     * taken at more than one match type: eleven terms at all three is
     * thirty-three criteria, which the cap refused as "at most 20 included
     * keywords", so the buyer typed combinations by hand and published eleven
     * phrase-match terms instead. Asked for and removed - Google takes
     * thousands of keywords in an ad group and whatever it will not take it
     * refuses itself, in its own words.
     *
     * What remains is twenty thousand, which is Google's documented ad-group
     * ceiling, so a payload that has gone wrong fails here with a sentence
     * instead of somewhere inside a provider error. Documented rather than
     * measured: publishing twenty thousand keywords to find out is not a
     * check worth running.
     */
    public const MOST_CRITERIA = 20000;

    public function __construct(private readonly TargetingSelections $locations) {}

    /** @return list<array{text: string, match_type: string, negative: bool, provenance: string}> */
    public function criteria(Campaign $campaign): array
    {
        if ($campaign->platform !== 'google' || ($campaign->campaign_type ?: 'search') !== 'search') {
            return [];
        }

        $options = (array) ($campaign->targetingSet()->first()?->options ?? []);

        if (array_key_exists('google_search_keywords', $options)) {
            return $this->normalise((array) $options['google_search_keywords'], 'user');
        }

        $analysis = $campaign->brief?->pageAnalysis();
        $suggestions = (array) ($analysis?->keywords ?? []);

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

        // The advertiser's own name comes out before anything is offered.
        //
        // Asked for directly: "keywords should be generic and non brand".
        // Page keywords are read off the page, so the brand is usually the most
        // repeated term on it and led the list every time. Somebody searching
        // the advertiser by name has already found them, so those clicks mostly
        // pay for traffic that was coming anyway.
        //
        // withoutBrand gives the list back untouched if every term carries the
        // brand, rather than handing the buyer nothing.
        $suggestions = app(BrandTerms::class)->withoutBrand(
            array_values(array_map('strval', $suggestions)),
            app(BrandTerms::class)->forPage($analysis),
        );

        // Every one the page yielded. This sliced at twenty, which could only
        // ever trim a list the analyser had already capped below it, and both
        // caps were ours rather than Google's.
        return $this->normalise(array_map(
            static fn (mixed $term): array => ['text' => $term, 'match_type' => 'PHRASE'],
            $suggestions,
        ), 'landing_page');
    }

    /** @param list<array<string, mixed>> $keywords */
    public function save(Campaign $campaign, array $keywords, int $expectedRevision): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google'
            || ($campaign->campaign_type ?: 'search') !== 'search') {
            throw new RuntimeException('Keyword selection is available for draft Google Search campaigns only.');
        }

        $criteria = $this->normalise($keywords, 'user');
        $countries = $this->locations->countries($campaign);

        if ($countries === []) {
            throw new RuntimeException('Select the campaign countries before saving Search keywords.');
        }

        return DB::transaction(function () use ($campaign, $criteria, $countries, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first();

            if ($expectedRevision !== ($set?->revision ?? 0)) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            if ($set === null || $set->mode !== 'override') {
                $set = $this->locations->saveCampaignCountries($campaign, $countries, $expectedRevision);
                $set->refresh();
            }

            $set->update([
                'options' => [...(array) ($set->options ?? []), 'google_search_keywords' => $criteria],
                'revision' => $set->revision + 1,
            ]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function clear(Campaign $campaign, int $expectedRevision): TargetingSet
    {
        if ($campaign->isPublished() || $campaign->platform !== 'google') {
            throw new RuntimeException('Only a draft Google campaign can clear Search keyword choices.');
        }

        return DB::transaction(function () use ($campaign, $expectedRevision): TargetingSet {
            $set = TargetingSet::query()->where('campaign_id', $campaign->getKey())->lockForUpdate()->first()
                ?? throw new RuntimeException('This campaign has no selected Search keywords to clear.');

            if ($set->revision !== $expectedRevision) {
                throw new RuntimeException('Targeting changed since it was opened. Review the latest selection and try again.');
            }

            $options = (array) ($set->options ?? []);

            if (! array_key_exists('google_search_keywords', $options)) {
                throw new RuntimeException('This campaign has no selected Search keywords to clear.');
            }

            unset($options['google_search_keywords']);
            $set->update(['options' => $options, 'revision' => $set->revision + 1]);
            $campaign->unsetRelation('targetingSet');

            return $set;
        });
    }

    public function hasExplicitSelection(Campaign $campaign): bool
    {
        return array_key_exists('google_search_keywords', (array) ($campaign->targetingSet()->first()?->options ?? []));
    }

    /**
     * @param  list<array<string, mixed>>  $keywords
     * @return list<array{text: string, match_type: string, negative: bool, provenance: string}>
     */
    /**
     * The same rules the draft path enforces, for the live path to reuse.
     *
     * Editing the keywords on an ad group that is already running goes through
     * edit_entity rather than through save() here, because it addresses one
     * live ad group rather than the campaign's draft selection. The rules must
     * not diverge: one to twenty included terms, at most forty criteria, no
     * duplicates and none both included and excluded. The lower bound is the
     * one that matters most live, where an edit that removed every keyword
     * would leave a Search ad group that cannot serve and no step to fix it.
     *
     * @param  list<array<string, mixed>>  $keywords
     * @return list<array{text: string, match_type: string, negative: bool, provenance: string}>
     */
    public function validated(array $keywords): array
    {
        return $this->normalise($keywords, 'user');
    }

    /**
     * Read Google's keyword shorthand out of the text and into the fields.
     *
     * The buyer types what they type into Google: "quoted" for phrase,
     * [bracketed] for exact, a leading minus to exclude. Those markers say what
     * the match type is, they are not part of the keyword, and Google refuses a
     * keyword whose text still carries them. Without this a buyer who typed
     * [milan flights] got a campaign bidding on the literal brackets, and one
     * who typed -free got a positive keyword for the exact thing they were
     * trying to keep out.
     *
     * A marker beats the match type it arrives with, because the marker is what
     * the buyer wrote and the match type is a reading of it.
     *
     * @return array{0: string, 1: string, 2: mixed}
     */
    private function unmark(string $text, string $matchType, mixed $negative): array
    {
        if (str_starts_with($text, '-')) {
            $text = ltrim(mb_substr($text, 1));
            $negative = true;
        }

        if (mb_strlen($text) > 2 && str_starts_with($text, '"') && str_ends_with($text, '"')) {
            return [trim(mb_substr($text, 1, -1)), 'PHRASE', $negative];
        }

        if (mb_strlen($text) > 2 && str_starts_with($text, '[') && str_ends_with($text, ']')) {
            return [trim(mb_substr($text, 1, -1)), 'EXACT', $negative];
        }

        return [$text, $matchType, $negative];
    }

    private function normalise(array $keywords, string $provenance): array
    {
        if (count($keywords) > self::MOST_CRITERIA) {
            throw new RuntimeException('Choose no more than '.self::MOST_CRITERIA.' Search keyword criteria.');
        }

        $result = [];
        $seen = [];
        $excluded = [];
        $hasIncluded = false;

        foreach ($keywords as $keyword) {
            if (! is_array($keyword) || ! is_string($keyword['text'] ?? null)
                || ! is_string($keyword['match_type'] ?? null)) {
                throw new RuntimeException('Each Search keyword needs text and a match type.');
            }

            $text = trim(preg_replace('/\s+/u', ' ', $keyword['text']) ?? '');
            $matchType = strtoupper(trim($keyword['match_type']));
            $negative = $keyword['negative'] ?? false;

            [$text, $matchType, $negative] = $this->unmark($text, $matchType, $negative);

            if ($text === '' || mb_strlen($text) > 80 || count(preg_split('/\s+/u', $text) ?: []) > 10
                || preg_match('/[\r\n\x00-\x1f]/u', $text) === 1
                || ! in_array($matchType, self::MATCH_TYPES, true)
                || ! is_bool($negative)) {
                throw new RuntimeException('Use 1–10 words and at most 80 characters per keyword, a valid match type, and a boolean negative flag.');
            }

            // One keyword is a text and a match type together, which is what
            // Google counts: "ad blocker" broad, phrase and exact are three
            // criteria and all three run in one ad group - confirmed against
            // 346-085-5874, where keyword_view read all three back. Keying the
            // duplicate check on the text alone refused the second match type
            // for a word as a duplicate, so a buyer could only ever have one.
            //
            // Including and excluding the same text is still a contradiction
            // whatever the match types, so that is checked on the text.
            $key = mb_strtolower($text).'|'.$matchType;
            $sense = mb_strtolower($text);

            if (isset($seen[$key]) || (isset($excluded[$sense]) && $excluded[$sense] !== $negative)) {
                throw new RuntimeException('A Search keyword cannot be duplicated or both included and excluded.');
            }

            $seen[$key] = true;
            $excluded[$sense] = $negative;

            $hasIncluded = $hasIncluded || ! $negative;
            $result[] = [
                'text' => $text,
                'match_type' => $matchType,
                'negative' => $negative,
                'provenance' => $provenance,
            ];
        }

        // No ceiling, only a floor: a Search campaign with nothing to match on
        // cannot run, and the publish gate refuses it anyway.
        if (! $hasIncluded) {
            throw new RuntimeException('Choose at least one included Search keyword.');
        }

        return $result;
    }
}
