<?php

namespace App\Services\Keywords;

use App\DTOs\LandingPageAnalysis;
use App\Services\AI\TextProviderFailover;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;

use function Laravel\Ai\agent;

/**
 * Search keywords for a landing page, chosen rather than counted.
 *
 * Asked for directly, twice: "irrelevant keywords suggestion", and "it should
 * be recommended by AI based on the content on the landing page".
 *
 * What it replaces is a word-frequency count, which could only ever produce
 * single words - iblockads.org gave "browse, trackers, cleaner, complete,
 * freedom, start, blocking, seconds, browsing", and every one of those went to
 * Google as a PHRASE match bid target. Cutting the page's own headings into
 * clauses fixed the shape, but a heading is what the page chose to shout, not
 * what a buyer types into Google: "browse with complete freedom" is a real
 * phrase off a real page and nobody searches for it.
 *
 * So the page is described to a model and it proposes the searches. The
 * deterministic extraction stays underneath as the floor - see
 * LandingPageAnalyzer::keywords() - because this costs a network call that can
 * fail, be rate limited, or be unreachable entirely: the AI keys are restricted
 * by IP, so on a machine outside that range this returns nothing at all and the
 * flow has to carry on regardless.
 *
 * Nothing here is trusted. The model is asked for 2 to 5 word phrases and the
 * answer is filtered to 2 to 5 word phrases, because the thing being built is a
 * list of bid targets and a bid target is money.
 */
class AiLandingPageKeywords
{
    /**
     * Google's own keyword limits, and the only ones here.
     *
     * There were three more and all three were ours: at most fifteen
     * keywords, and each of two to five words. A page with thirty searches in
     * it offered fifteen and the buyer never knew the rest existed, and
     * "stocks" was dropped for being one word, which is a search people make.
     * Removed on the ask - let Google decide - so what is left is what Google
     * refuses: over ten words, or over eighty characters.
     */
    private const MOST_WORDS = 10;

    private const MOST_CHARACTERS = 80;

    /**
     * Keyword phrases for this page, or an empty list if the model cannot help.
     *
     * @return list<string>
     */
    public function forPage(?LandingPageAnalysis $analysis): array
    {
        if ($analysis === null || ! config('google-ads.ai_landing_page_keywords', true)) {
            return [];
        }

        $brief = $this->pageBrief($analysis);

        // Nothing to describe, nothing to ask about. A page that yielded no
        // title and no headings is one the fetch did not really get.
        if ($brief === '') {
            return [];
        }

        try {
            $response = agent(
                instructions: 'You choose Google Search keywords for an advertiser, from a description '
                    .'of the page their ad will send people to. You return the searches a buyer would '
                    .'actually type when they want what this page sells, and nothing else.',
                schema: fn (JsonSchema $schema) => [
                    'keywords' => $schema->array()
                        ->items($schema->string())
                        ->description('Lowercase Google Search keyword phrases, at most 10 words each.')
                        ->required(),
                ],
            )->prompt($this->prompt($brief), provider: TextProviderFailover::providers());

            $keywords = $this->clean((array) ($response->toArray()['keywords'] ?? []));

            Log::info('AI landing page keywords', [
                'url' => $analysis->url,
                'returned' => count((array) ($response->toArray()['keywords'] ?? [])),
                'kept' => count($keywords),
            ]);

            return $keywords;
        } catch (Throwable $e) {
            // Never fatal. A page still has to produce keywords without this,
            // and the publish gate refuses a Search campaign with none, so an
            // unreachable model must not be the reason a buyer cannot launch.
            Log::warning('AI landing page keywords unavailable; falling back to the page\'s own phrases', [
                'url' => $analysis->url,
                'error' => $e->getMessage(),
            ]);

            return [];
        }
    }

    /**
     * The page in the model's words, not ours.
     *
     * Only what the page itself says. No instruction to be creative, because a
     * keyword that is not about this page is worse than one word too few: it is
     * a bid on traffic the advertiser cannot serve.
     */
    private function pageBrief(LandingPageAnalysis $analysis): string
    {
        $parts = array_filter([
            filled($analysis->title) ? 'Page title: '.$analysis->title : null,
            filled($analysis->description) ? 'Meta description: '.$analysis->description : null,
            $analysis->headings !== [] ? 'Headings: '.implode(' | ', array_slice($analysis->headings, 0, 10)) : null,
            $analysis->subheadings !== [] ? 'Subheadings: '.implode(' | ', array_slice($analysis->subheadings, 0, 10)) : null,
            $analysis->callsToAction !== [] ? 'Buttons: '.implode(' | ', array_slice($analysis->callsToAction, 0, 6)) : null,
            filled($analysis->text) ? 'Page text: '.Str::limit($analysis->text, 1200) : null,
        ]);

        return implode("\n", $parts);
    }

    private function prompt(string $brief): string
    {
        return <<<PROMPT
        {$brief}

        Give the Google Search keyword phrases for a Search campaign sending clicks to this page.
        As many as the page genuinely supports: every distinct search a buyer would type when they
        want what it sells, and none that it cannot serve. Do not pad the list to reach a number
        and do not stop short of one.

        Rules:
        - At most 10 words and 80 characters each, lowercase, no punctuation, no quotes or brackets.
        - What a buyer types when they want this, not what the page calls itself. A heading is
          marketing copy; a keyword is a search.
        - Generic, not brand: leave out the advertiser's own name, product name and domain. Somebody
          searching the brand has already found them.
        - Only things this page can actually serve. Do not broaden into adjacent products.
        - No locations unless the page is about a place.
        - Order them most obviously relevant first.
        PROMPT;
    }

    /**
     * @param  array<int|string, mixed>  $keywords
     * @return list<string>
     */
    private function clean(array $keywords): array
    {
        $kept = [];

        foreach ($keywords as $keyword) {
            $keyword = Str::lower(trim((string) preg_replace('/\s+/u', ' ', (string) $keyword)));

            // The markers mean something to this product - phrase, exact,
            // negative - and a model volunteering them would have its intent
            // read as the buyer's. See SearchKeywordSelections::unmark().
            $keyword = trim($keyword, " \t\"'[]()-+");

            if ($keyword === '') {
                continue;
            }

            $words = preg_split('/\s+/u', $keyword) ?: [];

            if (count($words) > self::MOST_WORDS || mb_strlen($keyword) > self::MOST_CHARACTERS) {
                continue;
            }

            $kept[$keyword] = true;
        }

        return array_keys($kept);
    }
}
