<?php

namespace Tests\Feature;

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

/**
 * "Irrelevant keywords suggestion."
 *
 * The suggestions were a word-frequency count, so they could only ever be
 * single words. iblockads.org produced "browse, trackers, cleaner, complete,
 * freedom, start, blocking, seconds, browsing" and GooglePublisher sent them to
 * Google as PHRASE match keywords on a live Search campaign. "browse" on phrase
 * match matches most of the internet, and nobody saw the list in between.
 *
 * An earlier round of this had already dropped function words and weighted the
 * title, which is why the docblock on keywords() reads as solved. It was not:
 * the shape was still one word per suggestion, and that is the complaint.
 *
 * So the page's own phrases come first, cut from its title and headings on
 * punctuation and kept whole. Nothing is invented: every phrase is a run of
 * words the page printed.
 */
class KeywordSuggestionsArePhrasesNotWordsTest extends TestCase
{
    /** The real iblockads headings, which are what was reported. */
    private const PAGE = <<<'HTML'
    <html><head><title>iblockads</title>
    <meta name="description" content="Block ads and trackers.">
    </head><body>
    <h1>Browse the Web Without Ads &amp; Trackers</h1>
    <h2>Everything you need for a cleaner web</h2>
    <h2>How It Works</h2>
    <h2>Browse with Complete Freedom</h2>
    <h2>Start Blocking Ads in Seconds</h2>
    <p>Browse the web without ads. Trackers blocked. A cleaner browsing
    experience in seconds, with complete freedom to browse. Browsing is
    smoother and the web is cleaner. Start blocking in seconds.</p>
    </body></html>
    HTML;

    private function analyse(string $html = self::PAGE): array
    {
        Http::fake(['https://example.com/*' => Http::response($html)]);

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

    public function test_the_suggestions_are_phrases(): void
    {
        $keywords = $this->analyse();

        $this->assertNotEmpty($keywords);

        foreach ($keywords as $keyword) {
            $this->assertGreaterThan(
                1,
                count(preg_split('/\s+/u', $keyword) ?: []),
                sprintf('"%s" is a single word, which is the bug: phrase match on one word buys everything.', $keyword),
            );
        }
    }

    public function test_the_words_that_were_reported_are_gone(): void
    {
        $keywords = $this->analyse();

        // Every one of these was a suggestion on the reported campaign.
        foreach (['browse', 'trackers', 'cleaner', 'complete', 'freedom', 'start', 'blocking', 'seconds', 'browsing'] as $word) {
            $this->assertNotContains($word, $keywords);
        }
    }

    public function test_the_page_heading_survives_its_ampersand(): void
    {
        // "Browse the Web Without Ads & Trackers" read whole is seven words and
        // was dropped for being too long, which lost the best phrase on the
        // page. The ampersand is a separator, not a word.
        $this->assertContains('browse the web without ads', $this->analyse());
    }

    public function test_the_phrases_are_the_pages_own_words(): void
    {
        $keywords = $this->analyse();

        $this->assertContains('browse with complete freedom', $keywords);
        $this->assertContains('start blocking ads in seconds', $keywords);
    }

    /** Page furniture is not a bid target. */
    public function test_a_clause_of_nothing_but_function_words_is_dropped(): void
    {
        $this->assertNotContains('how it works', $this->analyse());
    }

    /**
     * A page with no usable headings still has to produce something.
     *
     * An empty list blocks the publish gate, and a Search campaign with no
     * keyword cannot run, so the word count stays as the floor rather than the
     * default.
     */
    public function test_a_page_with_no_phrases_still_suggests_something(): void
    {
        $keywords = $this->analyse(<<<'HTML'
        <html><head><title>Shop</title></head><body>
        <p>Mattresses. Mattresses and pillows. Pillows, mattresses, bedding.
        Bedding and mattresses for bedrooms. Mattresses.</p>
        </body></html>
        HTML);

        $this->assertNotEmpty($keywords, 'an empty list blocks the publish gate outright');
    }
}
