<?php

namespace App\DTOs;

use Illuminate\Support\Str;

/**
 * What a landing page says about itself.
 *
 * Deliberately platform-neutral. This is the first thing the chat learns about
 * a campaign, before anyone has chosen Meta or Google, and everything it
 * produces is a suggestion rather than a decision: the page is evidence, not an
 * instruction.
 */
readonly class LandingPageAnalysis
{
    /**
     * @param  list<string>  $headings
     * @param  list<string>  $keywords  most frequent meaningful words, longest first
     * @param  list<string>  $subheadings
     * @param  list<string>  $callsToAction
     * @param  list<string>  $prices
     * @param  list<array{url: string, label: string}>  $sameHostLinks
     */
    public function __construct(
        public string $url,
        public string $title,
        public string $description,
        public array $headings,
        public string $text,
        public array $keywords,
        public array $subheadings = [],
        public array $callsToAction = [],
        public array $prices = [],
        public string $reviewText = '',
        public string $socialDescription = '',
        public array $sameHostLinks = [],
    ) {}

    /** The advertiser's name as the page presents it, best effort. */
    /**
     * The same page with a different keyword list.
     *
     * The analysis is readonly and its keywords are decided last: the model
     * that proposes them is given the finished page to look at, so they cannot
     * be computed inside the constructor call that builds it. See
     * LandingPageAnalyzer::analyze() and AiLandingPageKeywords.
     *
     * @param  list<string>  $keywords
     */
    public function withKeywords(array $keywords): self
    {
        return new self(
            url: $this->url,
            title: $this->title,
            description: $this->description,
            headings: $this->headings,
            text: $this->text,
            keywords: $keywords,
            subheadings: $this->subheadings,
            callsToAction: $this->callsToAction,
            prices: $this->prices,
            reviewText: $this->reviewText,
            socialDescription: $this->socialDescription,
            sameHostLinks: $this->sameHostLinks,
        );
    }

    public function businessName(): string
    {
        $brand = trim((string) preg_split('/\s+[|\-–—:]\s+/u', $this->title)[0]);

        if ($brand !== '' && ! in_array(mb_strtolower($brand), ['home', 'homepage', 'welcome', 'index', 'untitled'], true)) {
            return $brand;
        }

        // Form labels such as "You are?*" or "Email*" are headings on some pages, not names.
        foreach ($this->headings as $heading) {
            $heading = trim($heading);

            if ($heading !== '' && ! preg_match('/[?*:]$/u', $heading)) {
                return $heading;
            }
        }

        return '';
    }

    /**
     * A campaign name a person would recognise.
     *
     * The site first, because that is what the buyer is working on and the one
     * thing in the name that is not a guess. It used to be the page's title up
     * to the first separator, so stockprices.com/landing - titled "Trade
     * Smarter - ..." - published as trade-smarter_mohsin-khan-u5_GOOGLE_... and
     * nothing in the name said which site it was for. Asked for directly:
     * "make sure the campaign name starts with the project name or site name".
     * iblockads only ever looked right by luck, its title starting with its own
     * brand.
     *
     * The title is still the fallback, for a landing URL that cannot be parsed.
     *
     * No platform in the name: the same brief can produce a campaign on several
     * platforms, and "Acme - Google Ads" would be wrong on half of them.
     */
    public function campaignName(): string
    {
        $site = $this->siteName();
        $page = Str::slug($this->businessName());

        if ($site === '') {
            return $this->businessName() !== '' ? $this->businessName() : 'New campaign';
        }

        // The site, then what the page is about. Site alone would name every
        // campaign on a site the same thing - stockprices.com/landing and
        // stockprices.com/offers are two campaigns a buyer runs separately -
        // and the page's own words are what tell them apart.
        //
        // Not repeated where the page is already named after the site, which
        // is why iblockads.org stays "iblockads" rather than becoming
        // "iblockads-iblockads".
        if ($page === '' || $page === $site || str_starts_with($page, $site.'-')) {
            return $page === '' ? $site : $page;
        }

        return $site.'-'.$page;
    }

    /**
     * The site the landing page belongs to, as a person would say it.
     *
     * www comes off because nobody calls the project "www". A real subdomain
     * stays, because offers.example.com and example.com are two things a buyer
     * runs separately and the name has to tell them apart.
     *
     * The suffix comes off with a short list of the two-part ones rather than
     * the public suffix list: a wrong guess here only costs a clumsier name,
     * and carrying the whole list for that is not worth it. What matters is
     * that .co.uk does not leave "co" as the site's name.
     */
    private function siteName(): string
    {
        $host = Str::lower((string) (parse_url($this->url, PHP_URL_HOST) ?: ''));

        if ($host === '' || filter_var($host, FILTER_VALIDATE_IP) !== false) {
            return '';
        }

        $labels = array_values(array_filter(explode('.', Str::replaceStart('www.', '', $host))));

        if (count($labels) > 1) {
            array_pop($labels);
        }

        // "bargains.co.uk" is left as bargains.co by the pop above.
        if (count($labels) > 1 && in_array(end($labels), self::SECOND_LEVEL_SUFFIXES, true)) {
            array_pop($labels);
        }

        return Str::slug(implode('-', $labels));
    }

    /**
     * The second-level suffixes this product actually meets.
     *
     * Not the public suffix list. These are the ones that would otherwise name
     * a campaign "co" or "com".
     */
    private const SECOND_LEVEL_SUFFIXES = ['co', 'com', 'net', 'org', 'gov', 'edu', 'ac', 'or', 'ne'];

    /** @return list<string> candidate headlines, longest-standing first */
    public function headlines(): array
    {
        return array_values(array_unique(array_filter([$this->title, ...$this->headings])));
    }

    /** @return list<string> candidate descriptions */
    public function descriptions(): array
    {
        return array_values(array_filter([
            $this->description,
            $this->text !== '' ? mb_substr($this->text, 0, 90) : null,
        ]));
    }

    /**
     * What the page looks like it is for, in plain words.
     *
     * A shop page wants sales, a form wants leads, an article wants traffic.
     * Returned as the brief's vocabulary rather than any platform's, so the
     * same answer maps onto Meta's OUTCOME_SALES and Google's conversion goal.
     *
     * A guess, and treated as one everywhere it is used: it is offered as a
     * suggestion with its reason shown, never written as though the user said
     * it. Null when the page gives no clear signal, because a wrong suggestion
     * is worse than none.
     *
     * @return array{outcome: string, because: string}|null
     */
    public function suggestedOutcome(): ?array
    {
        $haystack = mb_strtolower($this->title.' '.$this->description.' '.implode(' ', $this->headings).' '.$this->text);

        // Ordered by how strongly each signal implies intent. A page selling
        // something often also has a newsletter form, so the checkout wins.
        $signals = [
            'sales' => ['add to cart', 'add to basket', 'buy now', 'checkout', 'free shipping', 'in stock', 'order now'],
            'leads' => ['get a quote', 'request a demo', 'book a call', 'contact us', 'sign up', 'free trial', 'subscribe'],
        ];

        foreach ($signals as $outcome => $phrases) {
            foreach ($phrases as $phrase) {
                if (str_contains($haystack, $phrase)) {
                    return ['outcome' => $outcome, 'because' => 'the page says "'.$phrase.'"'];
                }
            }
        }

        return null;
    }

    /** @return array<string, mixed> */
    public function toArray(): array
    {
        return [
            'url' => $this->url,
            'page' => [
                'title' => $this->title,
                'description' => $this->description,
                'headings' => $this->headings,
                'text' => $this->text,
            ],
            'suggestions' => [
                'campaign_name' => $this->campaignName(),
                'business_name' => $this->businessName(),
                'headlines' => $this->headlines(),
                'descriptions' => $this->descriptions(),
                'keywords' => implode(', ', $this->keywords),
            ],
        ];
    }
}
