<?php

namespace App\Campaigns\Targeting;

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

/**
 * The advertiser's own name, so keyword suggestions can leave it out.
 *
 * Asked for directly: "keywords should be generic and non-brand". A buyer
 * running Search is buying intent they do not already have. Somebody typing the
 * advertiser's name has already found them, so bidding on it mostly pays Google
 * for a click that was coming anyway, and on a small account it eats the budget
 * that was meant to find new people.
 *
 * Two sources, because either alone is thin. The page title carries the name as
 * the advertiser writes it, which is how LandingPageAnalysis::businessName()
 * reads it. The host carries it as they registered it, which catches the cases a
 * title misses - "iblockads.org" where the title says "Browse the Web Without
 * Ads", or a title that is pure marketing copy with no name in it at all.
 *
 * Deliberately only the advertiser's own name. A competitor's brand is a
 * legitimate and common thing to bid on, and nothing here should decide that for
 * the buyer.
 */
class BrandTerms
{
    /**
     * Words too generic to treat as a brand even when they are in the name.
     *
     * "Shop", "online" and "store" appear in a great many business names and in
     * a great many genuinely generic searches. Dropping every term containing
     * them would remove most of what a retailer should be bidding on.
     */
    private const TOO_GENERIC = [
        'shop', 'store', 'online', 'app', 'web', 'site', 'group', 'company',
        'limited', 'ltd', 'inc', 'llc', 'the', 'and', 'for', 'com', 'org',
        'net', 'official', 'home', 'free', 'best', 'new', 'get', 'buy',
    ];

    /**
     * Brand tokens for this page, lowercased.
     *
     * The host decides, and the title only confirms it.
     *
     * Both used to count equally, and the title is not a name. Where there is
     * no separator in it, businessName() returns the whole thing, and where
     * there is no title at all it returns the first heading - so a page titled
     * "Flights to Italy" made "flights" and "italy" brand terms and the
     * suggestion "cheap flights to italy" was dropped as the advertiser's own
     * name. On a page whose title is a sentence about the product, which is
     * most landing pages, that quietly removed the best keywords it had.
     *
     * So a title word is a brand term only when it is also the host: "iblockads"
     * on iblockads.org, which is a name appearing in both places and cannot be
     * a coincidence. Anything the title says that the domain does not is
     * treated as a description, because that is what it usually is.
     *
     * Equality rather than containment, and this is the part that matters on a
     * descriptive domain. stockprices.com yields the single token
     * "stockprices"; splitting it would yield "stock" and "prices" and take out
     * "stock analysis", "stock market" and every other thing that account
     * actually wants to bid on. isBrand() still catches "stock prices today",
     * because the joined words contain the whole host.
     *
     * @return list<string>
     */
    public function forPage(?LandingPageAnalysis $analysis): array
    {
        if ($analysis === null) {
            return [];
        }

        $host = $this->usable($this->tokens($this->registrableHost($analysis->url)));

        $confirmed = array_values(array_filter(
            $this->usable($this->tokens($analysis->businessName())),
            static fn (string $token): bool => in_array($token, $host, true),
        ));

        return array_values(array_unique([...$host, ...$confirmed]));
    }

    /**
     * Tokens long enough and specific enough to stand for a name.
     *
     * @param  list<string>  $tokens
     * @return list<string>
     */
    private function usable(array $tokens): array
    {
        return array_values(array_filter(
            $tokens,
            fn (string $token): bool => mb_strlen($token) >= 3
                && ! in_array($token, self::TOO_GENERIC, true),
        ));
    }

    /**
     * Whether a keyword leans on the advertiser's own name.
     *
     * Token equality rather than substring. "ads" inside "iblockads" would
     * otherwise take out "ad blocker ads", and a brand that happens to contain a
     * common word would quietly remove half the list.
     *
     * @param  list<string>  $brandTokens
     */
    public function isBrand(string $keyword, array $brandTokens): bool
    {
        if ($brandTokens === []) {
            return false;
        }

        $words = $this->tokens($keyword);

        if ($words === []) {
            return false;
        }

        foreach ($words as $word) {
            if (in_array($word, $brandTokens, true)) {
                return true;
            }
        }

        // A brand written as one word inside a longer one: "iblockadsapp", or
        // the host "iblockads" against the keyword "iblockads extension" once
        // the tokeniser has split it. Checked against whole brand tokens only,
        // and only when the brand token is long enough that a chance collision
        // is unlikely.
        $joined = implode('', $words);

        foreach ($brandTokens as $brand) {
            if (mb_strlen($brand) >= 5 && str_contains($joined, $brand)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Keep the generic terms, drop the advertiser's own.
     *
     * Never returns an empty list where the input was not empty: a page whose
     * every suggestion carries the brand would otherwise leave the buyer with no
     * keywords at all and no way to see why. Better to hand back what there is
     * and let the step say it looks brand-heavy.
     *
     * @param  list<string>  $keywords
     * @return list<string>
     */
    public function withoutBrand(array $keywords, array $brandTokens): array
    {
        if ($keywords === [] || $brandTokens === []) {
            return $keywords;
        }

        $generic = array_values(array_filter(
            $keywords,
            fn (string $keyword): bool => ! $this->isBrand($keyword, $brandTokens),
        ));

        return $generic === [] ? $keywords : $generic;
    }

    /** The registrable part of the host, without www or the public suffix. */
    private function registrableHost(string $url): string
    {
        $host = (string) (parse_url($url, PHP_URL_HOST) ?: '');

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

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

        // Second from the end on an ordinary host, which is the name rather
        // than the suffix. Multi-part suffixes such as .co.uk leave the suffix
        // behind instead, and TOO_GENERIC drops those.
        return count($labels) >= 2 ? $labels[count($labels) - 2] : $labels[0];
    }

    /** @return list<string> */
    private function tokens(string $value): array
    {
        $words = preg_split('/[^\pL\pN]+/u', Str::lower(trim($value))) ?: [];

        return array_values(array_filter($words, static fn (string $word): bool => $word !== ''));
    }
}
