<?php

namespace App\Campaigns\Targeting;

use App\DTOs\LandingPageAnalysis;
use Illuminate\Support\Str;

/**
 * Sitelinks and callouts, read off the landing page rather than invented.
 *
 * Both are campaign level ad assets and both are among the cheapest things a
 * Search campaign can have: they take more of the results page, give the buyer
 * more ways in, and cost nothing extra. SERP-1834 lists them and nothing here
 * built them, so every Google campaign this product has published went out
 * without any.
 *
 * The content comes from the page itself. Sitelinks are the page's own links to
 * the same host, which is exactly what a sitelink is - another page on the
 * advertiser's site, with the label the advertiser gave it. Callouts are the
 * page's calls to action and subheadings, which are the advertiser's own short
 * claims. Nothing is written here that the advertiser did not already say, which
 * matters because an ad asset is published copy and the product has no business
 * inventing it.
 *
 * Google's limits are hard refusals rather than truncation points, so anything
 * over them is dropped instead of cut: a sitelink trimmed mid-word reads worse
 * than one that is absent.
 */
class GoogleAdAssets
{
    /** Google refuses a sitelink whose visible text is longer than this. */
    public const SITELINK_TEXT_LIMIT = 25;

    /** And either of its two optional description lines. */
    public const SITELINK_DESCRIPTION_LIMIT = 35;

    /** Callout text has the same bound as sitelink text. */
    public const CALLOUT_LIMIT = 25;

    /**
     * Four of each is what Google shows; more are stored and rotated.
     *
     * Kept low deliberately. The bound that matters is not Google's maximum but
     * how many of these come off a page before the quality drops, and a page's
     * fifth-best link is usually its privacy policy.
     */
    public const MOST_SITELINKS = 4;

    public const MOST_CALLOUTS = 4;

    /**
     * Link labels that are navigation furniture rather than a destination worth
     * buying a click to. Matched whole, lowercased.
     */
    private const NOT_WORTH_LINKING = [
        'home', 'login', 'log in', 'login to continue', 'sign in', 'signin', 'register',
        'sign up', 'signup', 'subscribe', 'subscribe now', 'continue', 'get started',
        'privacy', 'privacy policy', 'terms', 'terms of service', 'terms of use',
        'terms and conditions', 'refund policy', 'return policy', 'shipping policy',
        'cookies', 'cookie policy', 'legal', 'imprint', 'sitemap', 'accessibility',
        'disclaimer', 'disclosures', 'faq', 'faqs', 'help', 'support', 'contact',
        'contact us', 'about', 'about us', 'careers', 'press', 'blog',
        'uninstall', 'uninstall instructions', 'unsubscribe', 'manage preferences',
        'back', 'next', 'previous', 'more', 'read more', 'learn more', 'know more',
        'see more', 'show more', 'view all', 'click here', 'here',
        'menu', 'search', 'cart', 'basket', 'checkout', 'account', 'my account',
        'dashboard', 'profile', 'settings', 'logout', 'log out',
        'facebook', 'twitter', 'instagram', 'linkedin', 'youtube', 'tiktok',
    ];

    /**
     * Link text that is a row of data rather than a destination.
     *
     * stockprices.com lists its tickers as links, so the page's "same host
     * links" included "PRSO Peraso Inc. +54.13%" and "BRZE Braze, Inc.
     * +51.70%" - and both were published as sitelinks on a live ad. A list of
     * anything is a list of links on a page that lists things, and no blocklist
     * of labels catches that. What catches it is the shape: a price, a
     * percentage, a ticker, a date.
     */
    private const LOOKS_LIKE_DATA = [
        // A percentage or a signed number: "+54.13%", "-2.1".
        '/[-+]?\d+(\.\d+)?\s*%/u',
        '/^[-+]\s*\d/u',
        // Money anywhere in the label.
        '/[$£€¥]\s*\d/u',
        // An all-caps ticker of 2 to 5 letters followed by more words.
        '/^[A-Z]{2,5}\b\s+\S/u',
        // A bare date or time.
        '/\b\d{1,2}[\/-]\d{1,2}([\/-]\d{2,4})?\b/u',
    ];

    /**
     * Sitelinks for this page: another page on the same site, by its own label.
     *
     * @return list<array{text: string, final_url: string}>
     */
    public function sitelinksFor(?LandingPageAnalysis $analysis): array
    {
        if ($analysis === null) {
            return [];
        }

        $landing = rtrim($analysis->url, '/');
        $sitelinks = [];
        $seenText = [];
        $seenUrl = [];

        foreach ($analysis->sameHostLinks as $link) {
            $text = $this->tidy((string) ($link['label'] ?? ''));
            $url = trim((string) ($link['url'] ?? ''));

            if ($text === '' || $url === '' || rtrim($url, '/') === $landing) {
                continue;
            }

            $key = Str::lower($text);

            if (mb_strlen($text) > self::SITELINK_TEXT_LIMIT
                || in_array($key, self::NOT_WORTH_LINKING, true)
                || $this->looksLikeData($text)
                || isset($seenText[$key])
                || isset($seenUrl[rtrim($url, '/')])
                || ! str_starts_with($url, 'http')) {
                continue;
            }

            $seenText[$key] = true;
            $seenUrl[rtrim($url, '/')] = true;
            $sitelinks[] = ['text' => $text, 'final_url' => $url];

            if (count($sitelinks) === self::MOST_SITELINKS) {
                break;
            }
        }

        // Google will not serve a lone sitelink, so one is worse than none: it
        // is published, occupies the account, and never shows.
        return count($sitelinks) >= 2 ? $sitelinks : [];
    }

    /**
     * Callouts for this page: the advertiser's own short claims.
     *
     * @return list<string>
     */
    public function calloutsFor(?LandingPageAnalysis $analysis): array
    {
        if ($analysis === null) {
            return [];
        }

        $callouts = [];
        $seen = [];

        foreach ([...$analysis->callsToAction, ...$analysis->subheadings, ...$analysis->headings] as $candidate) {
            $text = $this->tidy((string) $candidate);
            $key = Str::lower($text);

            if ($text === '' || mb_strlen($text) > self::CALLOUT_LIMIT || isset($seen[$key])) {
                continue;
            }

            // A callout is a claim, not a question or an instruction to the
            // reader. "Why choose us?" and "Enter your email" both read as the
            // page talking to somebody already on it.
            if (preg_match('/[?]$/u', $text) === 1
                || in_array($key, self::NOT_WORTH_LINKING, true)
                || $this->looksLikeData($text)
                || preg_match('/^(enter|type|paste|submit|click|tap|select|choose|fill|login|log in|sign in|sign up|subscribe|continue|register)\b/i', $text) === 1) {
                continue;
            }

            $seen[$key] = true;
            $callouts[] = $text;

            if (count($callouts) === self::MOST_CALLOUTS) {
                break;
            }
        }

        // Same reasoning as sitelinks: Google needs two to show any.
        return count($callouts) >= 2 ? $callouts : [];
    }

    /**
     * Google's fixed header list for a structured snippet.
     *
     * Not free text. Google accepts only these, and a snippet whose header does
     * not describe its values reads worse than no snippet at all - "Amenities:
     * Ad Blocker, Tracker Blocking" is a wrong answer dressed as a feature.
     *
     * The map is from a word the page uses to the header it implies. Anything
     * that does not match produces no snippet, deliberately: guessing a header
     * is how this feature embarrasses an advertiser.
     */
    private const HEADER_HINTS = [
        'course' => 'Courses', 'training' => 'Courses', 'class' => 'Courses',
        'degree' => 'Degree programs', 'programme' => 'Degree programs', 'program' => 'Degree programs',
        'destination' => 'Destinations', 'city' => 'Destinations', 'cities' => 'Destinations',
        'hotel' => 'Featured hotels', 'resort' => 'Featured hotels',
        'insurance' => 'Insurance coverage', 'cover' => 'Insurance coverage', 'policy' => 'Insurance coverage',
        'model' => 'Models', 'brand' => 'Brands',
        'neighborhood' => 'Neighborhoods', 'neighbourhood' => 'Neighborhoods',
        'service' => 'Service catalog', 'services' => 'Service catalog',
        'show' => 'Shows', 'style' => 'Styles', 'amenity' => 'Amenities', 'amenities' => 'Amenities',
        'type' => 'Types', 'category' => 'Types', 'categories' => 'Types',
    ];

    /** Google needs at least three values, and shows at most ten. */
    public const FEWEST_SNIPPET_VALUES = 3;

    public const MOST_SNIPPET_VALUES = 10;

    /** A snippet value has the same bound as a callout. */
    public const SNIPPET_VALUE_LIMIT = 25;

    /**
     * A structured snippet for this page, or null when none can be made honestly.
     *
     * Returns null rather than guessing. Two things have to be true: the page
     * has to say what kind of list it is offering, and it has to offer at least
     * three of them. Most pages do neither, and a snippet is an extra - the ad
     * is not worse without one.
     *
     * @return array{header: string, values: list<string>}|null
     */
    public function structuredSnippetFor(?LandingPageAnalysis $analysis, ?string $header = null): ?array
    {
        if ($analysis === null) {
            return null;
        }

        $header = $header !== null ? $this->validHeader($header) : $this->headerFor($analysis);

        if ($header === null) {
            return null;
        }

        $values = [];
        $seen = [];

        foreach ([...$analysis->subheadings, ...array_column($analysis->sameHostLinks, 'label')] as $candidate) {
            $value = $this->tidy((string) $candidate);
            $key = Str::lower($value);

            if ($value === '' || mb_strlen($value) > self::SNIPPET_VALUE_LIMIT || isset($seen[$key])
                || in_array($key, self::NOT_WORTH_LINKING, true)
                || $this->looksLikeData($value)
                || preg_match('/[?]$/u', $value) === 1) {
                continue;
            }

            $seen[$key] = true;
            $values[] = $value;

            if (count($values) === self::MOST_SNIPPET_VALUES) {
                break;
            }
        }

        return count($values) >= self::FEWEST_SNIPPET_VALUES
            ? ['header' => $header, 'values' => $values]
            : null;
    }

    /** The header the page's own words imply, or null when none of them do. */
    private function headerFor(LandingPageAnalysis $analysis): ?string
    {
        $haystack = Str::lower(implode(' ', [
            $analysis->title,
            ...$analysis->headings,
            ...$analysis->subheadings,
        ]));

        foreach (self::HEADER_HINTS as $word => $header) {
            if (preg_match('/\b'.preg_quote($word, '/').'\b/u', $haystack) === 1) {
                return $header;
            }
        }

        return null;
    }

    /** A caller-supplied header, only if Google would accept it. */
    private function validHeader(string $header): ?string
    {
        return self::acceptsHeader($header) ? self::canonicalHeader($header) : null;
    }

    /**
     * Whether Google's fixed list contains this header.
     *
     * Public because the send path checks it too. The derivation above cannot
     * be the only guard: attachCampaignAssets is public, and a caller that
     * built a snippet some other way would otherwise have it refused by Google
     * mid-batch, taking the sitelinks alongside it.
     */
    public static function acceptsHeader(string $header): bool
    {
        return self::canonicalHeader($header) !== null;
    }

    /** The header as Google spells it, or null if it is not one of theirs. */
    private static function canonicalHeader(string $header): ?string
    {
        $header = trim($header);

        foreach (array_unique(array_values(self::HEADER_HINTS)) as $allowed) {
            if (Str::lower($allowed) === Str::lower($header)) {
                return $allowed;
            }
        }

        return null;
    }

    /** Whether this reads as a row of data rather than something to click. */
    private function looksLikeData(string $text): bool
    {
        foreach (self::LOOKS_LIKE_DATA as $pattern) {
            if (preg_match($pattern, $text) === 1) {
                return true;
            }
        }

        return false;
    }

    /** One line, no stray whitespace, no trailing punctuation an asset would not carry. */
    private function tidy(string $value): string
    {
        $value = trim((string) preg_replace('/\s+/u', ' ', $value));

        return rtrim($value, " \t\n\r\0\x0B.,;:|-–—");
    }
}
