<?php

namespace App\Services;

use App\DTOs\LandingPageAnalysis;
use App\Services\Keywords\AiLandingPageKeywords;
use App\Support\PublicHttp;
use DOMDocument;
use DOMXPath;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use RuntimeException;
use Throwable;

/**
 * Reads a public landing page so the chat can suggest instead of interrogate.
 *
 * This is the first step of a campaign on every platform, which is why it lives
 * here rather than beside one platform's tools: the same page produces the
 * Meta objective, the Google keywords and the ad copy for both.
 *
 * Nothing here decides anything. It reports what the page says, and the caller
 * offers it as a suggestion the user can accept or overrule.
 */
class LandingPageAnalyzer
{
    private const MAX_HTML_BYTES = 2_000_000;

    private const MAX_TEXT_CHARS = 3000;

    private const MAX_REVIEW_TEXT_CHARS = 8000;

    /**
     * @throws RuntimeException when the page cannot or should not be read
     */
    public function analyze(string $url, bool $renderShell = false): LandingPageAnalysis
    {
        $host = parse_url($url, PHP_URL_HOST);

        if (! is_string($host) || $host === '') {
            throw new RuntimeException('That does not look like a web address. Check the URL and try again.');
        }

        // Both cases refuse the fetch, but they need different things from the
        // user: a typo needs correcting, a private address needs a public page.
        // Reported as one message each rather than one message for both.
        match ($this->reachability($host)) {
            'private' => throw new RuntimeException(
                'Use a public landing page URL. Local and private network addresses are not allowed.'
            ),
            'unresolvable' => throw new RuntimeException(
                "[{$host}] could not be found. Check the address is spelled correctly and is publicly reachable."
            ),
            default => null,
        };

        try {
            // Every hop checked, not just the one the user typed. The guard
            // above covers the first request; redirects are where a public
            // host hands the fetch to an internal one.
            $response = PublicHttp::send(
                Http::withHeaders(PublicHttp::browserHeaders())->connectTimeout(5)->timeout(15),
                $url,
            );
        } catch (Throwable $exception) {
            report($exception);

            throw new RuntimeException('The landing page could not be reached. Check the URL and try again.');
        }

        if ($response->failed()) {
            throw new RuntimeException('The landing page could not be read (HTTP '.$response->status().').');
        }

        $analysis = $this->parse($url, substr((string) $response->body(), 0, self::MAX_HTML_BYTES));

        // A page whose content only exists after its JavaScript runs is read
        // again in a browser.
        //
        // lucos.com answers 200 with 1362 bytes - a doctype, a CSP meta tag, a
        // favicon, a viewport and one script tag - so this produced a title and
        // nothing else, and every ad written from it said "Visit lucos.com.
        // Explore lucos.com to learn more." Four of Kaushal's five
        // conversations went that way, and the fault reads as bad copywriting
        // rather than as a page we could not see.
        //
        // Only when the first read came back empty, because rendering costs a
        // browser launch and several seconds. iblockads.org, attestpath.ai and
        // rebates.com are 13 to 43 times larger and never reach this.
        if ($this->looksClientRendered($analysis) && ($renderShell || (bool) config('scraping.puppeteer.enabled'))) {
            $rendered = app(RenderedPageFetcher::class)->fetch($url, $renderShell);

            if (filled($rendered)) {
                $second = $this->parse($url, substr($rendered, 0, self::MAX_HTML_BYTES));

                // Kept only if it is actually better. A render that fails in
                // its own way - a consent wall, a bot check - can return less
                // than the plain fetch did, and replacing a thin analysis with
                // an empty one helps nobody.
                if (! $this->looksClientRendered($second)) {
                    return $second;
                }
            }
        }

        return $analysis;
    }

    /**
     * Whether the HTML we read carried no content of its own.
     *
     * A title with no description, no headings and almost no text is the
     * signature of an app shell. Any one of those alone is ordinary - plenty of
     * real pages omit a meta description - so all three have to hold.
     */
    private function looksClientRendered(LandingPageAnalysis $analysis): bool
    {
        return $analysis->headings === []
            && trim($analysis->description) === ''
            && mb_strlen(trim($analysis->text)) < 200;
    }

    private function parse(string $url, string $html): LandingPageAnalysis
    {
        $document = new DOMDocument;

        // A space before every tag, before parsing.
        //
        // textContent joins descendants with nothing in between, so a heading
        // marked up as <h1>Block<span>Annoying Ads</span></h1> reads back as
        // "BlockAnnoying Ads". That produced "blockannoying" as a keyword for
        // iblockads.org, which is not a word anybody searches for and would
        // have been bid on as a phrase match.
        //
        // Before every tag rather than only between adjacent ones: the fusing
        // boundary is text meeting a tag, which "><" does not match. Runs of
        // whitespace are collapsed below, so the extra spaces cost nothing.
        $html = str_replace('<', ' <', $html);

        // Real pages are rarely valid HTML, and a warning per malformed tag is
        // not news. The parser recovers on its own.
        @$document->loadHTML($html);
        $xpath = new DOMXPath($document);

        // Code is removed before any text is read out of the page.
        //
        // string(//body) returns every descendant's text, scripts and stylesheets
        // included, and an inline analytics snippet or a block of CSS is on almost
        // every landing page. So "function", "window", "datalayer", "gtag",
        // "webkit", "transition" and "important" were all being counted as things
        // the page is about - and GooglePublisher sends these to Google as PHRASE
        // match keywords on a live Search campaign, where they bid on traffic that
        // has nothing to do with the advertiser.
        //
        // The same text is also what the ad copy is written from, so this is not
        // only a keyword problem: the model was being shown JavaScript and asked
        // what the page sells.
        //
        // Removed from the document rather than filtered afterwards, because a list
        // of code words to exclude is a list that is always one framework behind.
        foreach (iterator_to_array($xpath->query('//script | //style | //noscript | //template') ?: []) as $node) {
            $node->parentNode?->removeChild($node);
        }

        $callsToAction = $this->callsToAction($xpath);
        $fullBody = trim(preg_replace('/\s+/', ' ', (string) $xpath->evaluate('string(//body)')));

        // Product-choice labels can contain the offer, not just a field name.
        foreach (iterator_to_array($xpath->query(
            '//label[not(.//input[@type="radio" or @type="checkbox"])'
            .' and not(.//h1 or .//h2 or .//h3 or .//p or .//ul or .//ol)]'
        ) ?: []) as $node) {
            $node->parentNode?->removeChild($node);
        }

        // Forms and fieldsets may wrap the whole offer. Remove controls and
        // marked validation messages, not their structural ancestors.
        foreach (iterator_to_array($xpath->query(
            '//input | //select | //option | //textarea | //datalist | //output'
            .' | //*[@data-valmsg-for or (@role="alert" and (ancestor::form or ancestor::fieldset))'
            .' or contains(concat(" ", normalize-space(@class), " "), " invalid-feedback ")'
            .' or contains(concat(" ", normalize-space(@class), " "), " field-validation-error ")'
            .' or contains(concat(" ", normalize-space(@class), " "), " validation-message ")]'
        ) ?: []) as $node) {
            $node->parentNode?->removeChild($node);
        }

        // Some signup templates print validation as unmarked sibling spans.
        foreach (iterator_to_array($xpath->query('//form//span[not(*)] | //fieldset//span[not(*)]') ?: []) as $node) {
            $message = trim(preg_replace('/\s+/', ' ', $node->textContent));

            if (preg_match('/^(?:please (?:provide|enter|select)\b.*\b(?:name|email|address|phone|password|state|country)\b|it must contain a valid email address\b)/i', $message)) {
                $node->parentNode?->removeChild($node);
            }
        }

        $headings = $this->headingTexts($xpath, '//h1 | //h2', 8);
        $subheadings = $this->headingTexts($xpath, '//h3', 12);
        $body = trim(preg_replace('/\s+/', ' ', (string) $xpath->evaluate('string(//body)')));
        $text = mb_substr($body, 0, self::MAX_TEXT_CHARS);
        $title = trim((string) $xpath->evaluate('string(//title)'));

        $analysis = new LandingPageAnalysis(
            url: $url,
            title: $title,
            description: trim((string) $xpath->evaluate('string(//meta[@name="description"]/@content)')),
            headings: $headings,
            text: $text,
            keywords: $this->keywords($text, $title, $headings, $subheadings),
            subheadings: $subheadings,
            callsToAction: $callsToAction,
            // Price choices may live in controls; copy must exclude their noise.
            prices: $this->prices(mb_substr($fullBody, 0, self::MAX_REVIEW_TEXT_CHARS)),
            reviewText: mb_substr($body, 0, self::MAX_REVIEW_TEXT_CHARS),
            socialDescription: $this->socialDescription($xpath),
            sameHostLinks: $this->sameHostLinks($xpath, $url),
        );

        // And then ask a model, which sees the whole page rather than its
        // headings alone. Asked for by name: "it should be recommended by AI
        // based on the content on the landing page". The phrases above remain
        // the floor - AiLandingPageKeywords returns nothing when the call fails
        // or the feature is off, and a Search campaign cannot publish with no
        // keyword at all.
        $suggested = app(AiLandingPageKeywords::class)->forPage($analysis);

        return $suggested === [] ? $analysis : $analysis->withKeywords($suggested);
    }

    /**
     * Pages on this site the landing page links to.
     *
     * @return list<array{url: string, label: string}>
     */
    private function sameHostLinks(DOMXPath $xpath, string $pageUrl): array
    {
        $links = [];

        foreach ($xpath->query('//a[@href]') ?: [] as $node) {
            $url = $this->absoluteSameHostUrl((string) $node->getAttribute('href'), $pageUrl);

            if ($url === null) {
                continue;
            }

            $label = trim(preg_replace('/\s+/', ' ', $node->textContent) ?? '');
            $key = strtolower((string) parse_url($url, PHP_URL_HOST)).rtrim((string) parse_url($url, PHP_URL_PATH), '/');
            $links[$key] = [
                'url' => $url,
                'label' => mb_substr($label, 0, 80),
            ];

            if (count($links) >= 15) {
                break;
            }
        }

        return array_values($links);
    }

    private function absoluteSameHostUrl(string $href, string $pageUrl): ?string
    {
        $href = trim($href);

        if ($href === '' || str_starts_with($href, '#') || str_starts_with($href, 'mailto:') || str_starts_with($href, 'tel:') || str_starts_with($href, 'javascript:')) {
            return null;
        }

        if (str_starts_with($href, '//')) {
            $href = 'https:'.$href;
        }

        $parts = parse_url($pageUrl);
        $host = is_string($parts['host'] ?? null) ? $parts['host'] : '';

        if ($host === '') {
            return null;
        }

        $scheme = is_string($parts['scheme'] ?? null) && $parts['scheme'] !== '' ? $parts['scheme'] : 'https';
        $origin = $scheme.'://'.$host.(empty($parts['port']) ? '' : ':'.$parts['port']);

        if (preg_match('#^https?://#i', $href) !== 1) {
            if (str_starts_with($href, '/')) {
                $href = $origin.$href;
            } else {
                $directory = isset($parts['path']) ? (preg_replace('#/[^/]*$#', '/', (string) $parts['path']) ?? '/') : '/';
                $href = $origin.$directory.$href;
            }
        }

        $linkHost = strtolower((string) (preg_replace('/^www\./', '', (string) parse_url($href, PHP_URL_HOST)) ?? ''));
        $pageHost = strtolower((string) (preg_replace('/^www\./', '', $host) ?? ''));

        if ($linkHost === '' || $linkHost !== $pageHost) {
            return null;
        }

        $path = (string) (parse_url($href, PHP_URL_PATH) ?: '/');

        return $scheme.'://'.parse_url($href, PHP_URL_HOST).$path;
    }

    /**
     * @return list<string>
     */
    private function headingTexts(DOMXPath $xpath, string $query, int $limit): array
    {
        return collect($xpath->query($query) ?: [])
            ->map(fn ($node): string => trim(preg_replace('/\s+/', ' ', $node->textContent)))
            ->filter()
            ->unique()
            ->take($limit)
            ->values()
            ->all();
    }

    /**
     * Buttons and short links, without the navigation every site repeats.
     *
     * @return list<string>
     */
    private function callsToAction(DOMXPath $xpath): array
    {
        $skip = [
            'about', 'account', 'blog', 'careers', 'contact', 'cookie', 'cookies', 'home',
            'log in', 'login', 'menu', 'privacy', 'privacy policy', 'search', 'sign in',
            'terms', 'terms of service',
        ];
        $calls = [];

        foreach ($xpath->query('//button | //input[@type="submit" or @type="button"] | //a') ?: [] as $node) {
            $text = $node->nodeName === 'input'
                ? (string) $node->getAttribute('value')
                : $node->textContent;
            $text = trim(preg_replace('/\s+/', ' ', $text) ?? '');
            $lower = mb_strtolower($text);

            if (mb_strlen($text) < 2 || mb_strlen($text) > 40 || in_array($lower, $skip, true)) {
                continue;
            }

            $calls[$lower] = $text;

            if (count($calls) >= 12) {
                break;
            }
        }

        return array_values($calls);
    }

    /**
     * @return list<string>
     */
    private function prices(string $text): array
    {
        preg_match_all('/(?:[$£€]\s?\d[\d,]*(?:\.\d{2})?|\d[\d,]*(?:\.\d{2})?\s?(?:USD|EUR|GBP))/u', $text, $matches);
        $prices = [];

        foreach ($matches[0] ?? [] as $price) {
            $price = trim(preg_replace('/\s+/', ' ', (string) $price) ?? '');

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

            $prices[$price] = $price;

            if (count($prices) >= 8) {
                break;
            }
        }

        return array_values($prices);
    }

    private function socialDescription(DOMXPath $xpath): string
    {
        $description = trim((string) $xpath->evaluate(
            'string(//meta[@property="og:description" or @name="twitter:description"]/@content)'
        ));

        return mb_substr($description, 0, 500);
    }

    /**
     * English words that are never worth bidding on.
     *
     * Only the ones five characters or more, because shorter words are already
     * dropped. Not a general stop-word list: "free", "best" and "cheap" are
     * short or genuinely wanted in ad keywords, so this is confined to function
     * words and the furniture every website has.
     *
     * @var list<string>
     */
    private const NOT_KEYWORDS = [
        'about', 'above', 'after', 'again', 'against', 'along', 'already', 'although', 'always',
        'among', 'another', 'anything', 'around', 'because', 'become', 'been', 'before', 'being',
        'below', 'between', 'both', 'cannot', 'could', 'doing', 'during', 'each', 'either',
        'enough', 'especially', 'even', 'ever', 'every', 'everything', 'from', 'further', 'getting',
        'given', 'gives', 'going', 'have', 'having', 'here', 'however', 'into', 'itself', 'just',
        'keep', 'like', 'made', 'make', 'makes', 'many', 'might', 'more', 'most', 'much', 'must',
        'need', 'needs', 'never', 'often', 'once', 'only', 'other', 'others', 'ourselves', 'over',
        'own', 'perhaps', 'please', 'rather', 'really', 'same', 'should', 'simply', 'since',
        'some', 'something', 'still', 'such', 'take', 'takes', 'than', 'that', 'their', 'theirs',
        'them', 'themselves', 'then', 'there', 'therefore', 'these', 'they', 'thing', 'things',
        'this', 'those', 'through', 'today', 'together', 'under', 'until', 'upon', 'used', 'using',
        'very', 'want', 'wants', 'well', 'were', 'what', 'when', 'where', 'whether', 'which',
        'while', 'will', 'with', 'within', 'without', 'working', 'works', 'would', 'your',
        'yours', 'yourself',
        // The furniture, present on almost every page and meaningless as a bid.
        'click', 'clicks', 'contact', 'cookie', 'cookies', 'email', 'home', 'learn', 'menu',
        'page', 'pages', 'policy', 'privacy', 'read', 'reserved', 'rights', 'search', 'site',
        'submit', 'terms', 'thanks', 'welcome', 'website',
    ];

    /**
     * Keywords worth bidding on, from what the page is about.
     *
     * Was a frequency count of anything five characters or more, described in
     * this docblock as "a prompt for the user, not a keyword strategy". That
     * stopped being true: GooglePublisher sends these to Google as PHRASE match
     * keywords on a live Search campaign, so they are bid targets and nobody
     * sees them in between. iblockads.org produced "about", "works",
     * "experience", "online" and "smoother", every one of which would match a
     * great deal of traffic that has nothing to do with an ad blocker.
     *
     * Three changes. Function words and page furniture are dropped outright. A
     * word has to be repeated, which is what "the words the page repeats" meant
     * all along. And the title and headings are weighted, because that is where
     * a page says what it sells: an advertiser's brand usually appears once in
     * the body and cannot win on frequency.
     *
     * The repetition rule is relaxed rather than enforced when it would leave
     * too little: a short page can say something once and mean it, and an empty
     * list blocks the publish gate entirely.
     *
     * A fourth change, and the one the buyers noticed: these are phrases now.
     *
     * Everything above still produced single words, because a frequency count
     * of a page can only produce single words. iblockads.org came out as
     * "browse, trackers, cleaner, complete, freedom, start, blocking, seconds,
     * browsing" and every one of those went to Google as a PHRASE match bid
     * target. "browse" alone matches most of the internet. Reported as
     * "irrelevant keywords suggestion", and it is: a one-word phrase match is
     * not a keyword strategy, it is a bill.
     *
     * So the page's own phrases come first - its title and its headings, which
     * is where a page says what it sells, cut into clauses and kept whole. Then
     * the word count underneath, because a phrase list of two is thin and the
     * publish gate needs something. Nothing here is invented: every phrase is a
     * run of words the page actually printed.
     *
     * @param  list<string>  $headings
     * @param  list<string>  $subheadings
     * @return list<string>
     */
    private function keywords(string $text, string $title = '', array $headings = [], array $subheadings = []): array
    {
        $phrases = $this->phrases($title, $headings, $subheadings);

        $words = fn (string $source): Collection => collect(preg_split('/[^\p{L}\p{N}]+/u', mb_strtolower($source)) ?: [])
            ->filter(fn (string $word): bool => mb_strlen($word) >= 5)
            ->reject(fn (string $word): bool => in_array($word, self::NOT_KEYWORDS, true))
            ->reject(fn (string $word): bool => ctype_digit($word));

        // The title and headings lead outright rather than competing on count.
        // "adblocker" appears once on iblockads.org, in the title, and is the
        // most valuable thing on the page to bid on; a frequency weighting left
        // it ranked below "smoother".
        $leading = $words($title.' '.implode(' ', $headings))->countBy()->sortDesc()->keys();

        $counted = $words($text)->countBy()->sortDesc();
        // Phrases win outright where the page gave enough of them, rather than
        // being padded out to ten with single words. Padding is what kept
        // "browse" and "seconds" in a list that already held "browse the web
        // without ads": a worse keyword does not become acceptable by sitting
        // underneath a better one, and the buyer has to read and untick it.
        if (count($phrases) >= self::FEWEST_PHRASES) {
            return $phrases;
        }

        // When the page has too few phrases to stand alone, title and heading
        // terms lead, then body terms fill the list with the page's actual offer.
        $chosen = collect($phrases)->merge($leading)->merge($counted->keys())->unique();

        return $chosen->values()->all();
    }

    /**
     * Enough phrases to stand on their own without single words beneath them.
     *
     * Three is what a Search ad group wants at minimum anyway, and it is the
     * same floor the responsive search ad uses for headlines. Below it the word
     * count is still better than handing the buyer an empty question.
     */
    private const FEWEST_PHRASES = 3;

    /**
     * The phrases the page printed, longest-standing first.
     *
     * Cut on punctuation rather than on word windows. A page writes "Block
     * pop-ups, banners and autoplay ads" and the useful bid targets are the
     * clauses, not every three-word slice of them: sliding a window produces
     * "and autoplay ads" and "pop ups banners and", which read as nonsense in
     * an auction and as carelessness on a report.
     *
     * Two to five words. One word is the bug this replaces, and anything longer
     * than five is a sentence that nobody searches for.
     *
     * @param  list<string>  $headings
     * @param  list<string>  $subheadings
     * @return list<string>
     */
    private function phrases(string $title, array $headings, array $subheadings): array
    {
        $phrases = [];

        foreach ([$title, ...$headings, ...$subheadings] as $source) {
            // The title's trailing brand, as pages write it: "Page Name | Brand"
            // or "Page Name - Brand". Cut on the separator rather than stripped
            // by name, because this runs before anything knows the brand.
            // "&" counts as a separator, not a word. "Browse the Web Without
            // Ads & Trackers" is two clauses, and read whole it is seven words
            // and was thrown away - which lost the best phrase on the page.
            foreach (preg_split('/[|&\x{2013}\x{2014},.;:!?\/()\[\]]+|\s[-–]\s/u', (string) $source) ?: [] as $clause) {
                $clause = trim(preg_replace('/\s+/u', ' ', mb_strtolower($clause)) ?? '');

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

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

                if (count($words) < 2 || count($words) > 5) {
                    continue;
                }

                // A clause of nothing but function words - "and more", "how it
                // works" - describes the page rather than what it sells.
                $meaningful = array_filter(
                    $words,
                    static fn (string $word): bool => mb_strlen($word) >= 4
                        && ! in_array($word, self::NOT_KEYWORDS, true),
                );

                if ($meaningful === []) {
                    continue;
                }

                $phrases[$clause] = true;
            }
        }

        return array_keys($phrases);
    }

    /**
     * Whether this host may be fetched, and if not, why not.
     *
     * A landing page URL arrives from whoever is chatting and the server will
     * fetch it, so without this the chat is a request-forgery tool pointed at
     * our own network. The name is resolved rather than pattern-matched,
     * because a perfectly public hostname can point at a private address.
     *
     * Anything that does not resolve is refused as well. That is deliberate: a
     * name we cannot resolve is a name we cannot vouch for.
     *
     * @return 'public'|'private'|'unresolvable'
     */
    private function reachability(string $host): string
    {
        $host = strtolower(rtrim($host, '.'));

        if ($host === 'localhost' || str_ends_with($host, '.local')) {
            return 'private';
        }

        $ip = gethostbyname($host);

        // gethostbyname hands back what it was given when it cannot resolve.
        if ($ip === $host && filter_var($host, FILTER_VALIDATE_IP) === false) {
            return 'unresolvable';
        }

        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false
            ? 'private'
            : 'public';
    }
}
