<?php

namespace App\Campaigns;

use App\DTOs\LandingPageAnalysis;
use App\Services\LandingPageAnalyzer;
use Throwable;

/**
 * Reads the rest of the site the landing page belongs to.
 *
 * The ad opens on one URL. The homepage and a few linked pages say what the
 * business actually sells, which the landing page alone often does not.
 */
class CampaignWebsiteContext
{
    public function __construct(private LandingPageAnalyzer $analyzer) {}

    /**
     * @return array{host: string, pages: list<array<string, mixed>>}
     */
    public function fromLanding(LandingPageAnalysis $landing): array
    {
        $host = $this->host($landing->url);

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

        $landingKey = $this->key($landing->url);
        $pages = [];
        $seen = [$landingKey => true];
        $home = $this->homeUrl($landing->url);

        if ($home !== null && ! isset($seen[$this->key($home)])) {
            $seen[$this->key($home)] = true;
            $page = $this->read($home, 'homepage');

            if ($page !== null) {
                $pages[] = $page;
            }
        }

        $links = $landing->sameHostLinks;
        usort($links, function (array $left, array $right): int {
            return $this->rank($left) <=> $this->rank($right);
        });
        $added = 0;

        foreach ($links as $link) {
            if ($added >= 2) {
                break;
            }

            $url = (string) ($link['url'] ?? '');
            $key = $this->key($url);

            if ($url === '' || isset($seen[$key]) || $this->skipped($url)) {
                continue;
            }

            $seen[$key] = true;
            $page = $this->read($url, $this->role($url, (string) ($link['label'] ?? '')));

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

            $pages[] = $page;
            $added++;
        }

        if ($pages === []) {
            return [];
        }

        return [
            'host' => $host,
            'pages' => $pages,
        ];
    }

    /**
     * @return array<string, mixed>|null
     */
    private function read(string $url, string $role): ?array
    {
        try {
            $analysis = $this->analyzer->analyze($url);
        } catch (Throwable) {
            return null;
        }

        $text = trim($analysis->reviewText !== '' ? $analysis->reviewText : $analysis->text);

        if ($text === '' && $analysis->title === '') {
            return null;
        }

        return [
            'url' => $analysis->url,
            'role' => $role,
            'title' => $analysis->title !== '' ? $analysis->title : null,
            'description' => ($analysis->description !== '' ? $analysis->description : $analysis->socialDescription) ?: null,
            'headings' => array_slice($analysis->headings, 0, 6),
            'text' => mb_substr($text, 0, 1500),
        ];
    }

    private function homeUrl(string $url): ?string
    {
        $parts = parse_url($url);
        $host = $parts['host'] ?? null;

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

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

        if (! empty($parts['port'])) {
            $origin .= ':'.$parts['port'];
        }

        return $origin.'/';
    }

    private function host(string $url): string
    {
        $host = strtolower((string) parse_url($url, PHP_URL_HOST));

        return (string) (preg_replace('/^www\./', '', $host) ?? $host);
    }

    private function key(string $url): string
    {
        $host = $this->host($url);
        $path = rtrim((string) parse_url($url, PHP_URL_PATH), '/');

        return $host.($path === '' ? '/' : $path);
    }

    /**
     * @param  array{url?: string, label?: string}  $link
     */
    private function rank(array $link): int
    {
        $haystack = strtolower((string) ($link['url'] ?? '').' '.(string) ($link['label'] ?? ''));

        foreach (['about', 'pricing', 'plans', 'price', 'features', 'product', 'solutions', 'how'] as $index => $word) {
            if (str_contains($haystack, $word)) {
                return $index;
            }
        }

        return 100;
    }

    private function role(string $url, string $label): string
    {
        $haystack = strtolower($url.' '.$label);

        foreach (['about', 'pricing', 'plans', 'features', 'product', 'solutions'] as $word) {
            if (str_contains($haystack, $word)) {
                return $word;
            }
        }

        return 'page';
    }

    private function skipped(string $url): bool
    {
        $path = strtolower((string) parse_url($url, PHP_URL_PATH));

        foreach (['privacy', 'terms', 'login', 'signin', 'sign-in', 'cart', 'account', 'cookie', 'wp-admin', 'wp-login'] as $bit) {
            if (str_contains($path, $bit)) {
                return true;
            }
        }

        return false;
    }
}
