<?php

namespace Tests\Feature;

use App\Services\LandingPageAnalyzer;
use Illuminate\Support\Facades\Http;
use Laravel\Ai\Ai;
use Laravel\Ai\StructuredAnonymousAgent;
use Tests\TestCase;

/**
 * "It should be recommended by AI based on the content on the landing page."
 *
 * The suggestions were a word-frequency count, then the page's own headings cut
 * into clauses. The count could only make single words - "browse", "trackers",
 * "seconds" - and the headings are better but still not searches: "browse with
 * complete freedom" is a real phrase off a real page that nobody types into
 * Google.
 *
 * So a model is given the page and asked what a buyer would search for. The
 * extraction stays underneath as the floor, because this is a network call: it
 * can fail, be throttled, or be refused outright - the AI keys are restricted
 * by IP, so outside that range it returns nothing - and a Search campaign
 * cannot be published with no keywords at all.
 */
class AiProposesTheSearchKeywordsTest extends TestCase
{
    private const PAGE = <<<'HTML'
    <html><head><title>iblockads</title>
    <meta name="description" content="Block ads and trackers in Chrome.">
    </head><body>
    <h1>Browse the Web Without Ads &amp; Trackers</h1>
    <h2>Browse with Complete Freedom</h2>
    <h2>Start Blocking Ads in Seconds</h2>
    <p>Block ads and trackers while you browse. A cleaner browsing experience
    in seconds, with complete freedom to browse.</p>
    </body></html>
    HTML;

    protected function setUp(): void
    {
        parent::setUp();

        // phpunit.xml turns this off for the suite, because otherwise every
        // test that analyses a page would make a model call.
        config(['google-ads.ai_landing_page_keywords' => true]);

        Http::fake(['https://example.com/*' => Http::response(self::PAGE)]);
    }

    private function keywords(): array
    {
        return app(LandingPageAnalyzer::class)->analyze('https://example.com/offer')->keywords;
    }

    public function test_the_models_keywords_are_the_ones_used(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'keywords' => ['ad blocker for chrome', 'block pop up ads', 'stop web trackers'],
        ]]);

        $this->assertSame(
            ['ad blocker for chrome', 'block pop up ads', 'stop web trackers'],
            $this->keywords(),
        );
    }

    /** The page's own phrases are not what a buyer searches for. */
    public function test_the_page_phrases_are_replaced_rather_than_appended(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'keywords' => ['ad blocker for chrome', 'block pop up ads'],
        ]]);

        // Once: each analyse consumes a queued fake response, and a second
        // call would fall back and pass for the wrong reason.
        $keywords = $this->keywords();

        $this->assertNotContains('browse with complete freedom', $keywords);
        $this->assertNotContains('start blocking ads in seconds', $keywords);
        $this->assertSame(['ad blocker for chrome', 'block pop up ads'], $keywords);
    }

    /**
     * Nothing the model returns is trusted, but the shape is Google's.
     *
     * A keyword is a bid target and a bid target is money, so the answer is
     * still filtered - to what Google will take, which is at most ten words
     * and eighty characters, and nothing else. This also dropped anything
     * under two words, which was ours: "browse" is a search people make, and
     * the ask was to let Google decide. See NoCapOnKeywordSuggestionsTest.
     */
    public function test_a_sentence_is_dropped_and_a_single_word_is_kept(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'keywords' => [
                'browse',
                'the best possible ad blocking extension for the chrome web browser today',
                'ad blocker for chrome',
                '',
                'block pop up ads',
            ],
        ]]);

        $this->assertSame(['browse', 'ad blocker for chrome', 'block pop up ads'], $this->keywords());
    }

    /** Match-type markers mean something here and are not the model's to send. */
    public function test_markers_are_stripped_from_what_the_model_returns(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'keywords' => ['"ad blocker for chrome"', '[block pop up ads]', '-free ad blocker'],
        ]]);

        $this->assertSame(
            ['ad blocker for chrome', 'block pop up ads', 'free ad blocker'],
            $this->keywords(),
        );
    }

    public function test_duplicates_and_casing_collapse(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'keywords' => ['Ad Blocker For Chrome', 'ad blocker for chrome', 'AD BLOCKER FOR CHROME'],
        ]]);

        $this->assertSame(['ad blocker for chrome'], $this->keywords());
    }

    /**
     * The floor. An unreachable model must not stop a campaign being built.
     *
     * Simulate the outage without depending on credentials or network access.
     */
    public function test_the_pages_own_phrases_are_used_when_the_model_cannot_be_reached(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [
            fn (mixed ...$arguments): never => throw new \RuntimeException('Provider unavailable'),
        ]);

        $keywords = $this->keywords();

        $this->assertNotEmpty($keywords, 'a Search campaign cannot publish with no keywords');
        $this->assertContains('browse the web without ads', $keywords);
        Ai::assertAgentWasPrompted(StructuredAnonymousAgent::class, fn ($prompt): bool => str_contains(
            (string) $prompt->prompt, 'Browse the Web Without Ads',
        ));
    }

    /** And with the feature off, no call is attempted at all. */
    public function test_nothing_is_asked_when_the_feature_is_off(): void
    {
        config(['google-ads.ai_landing_page_keywords' => false]);

        $this->assertContains('browse the web without ads', $this->keywords());
    }

    /** An empty answer is not an answer. */
    public function test_an_empty_list_falls_back_rather_than_leaving_no_keywords(): void
    {
        Ai::fakeAgent(StructuredAnonymousAgent::class, [[
            'keywords' => [],
        ]]);

        $this->assertNotEmpty($this->keywords());
    }
}
