<?php

namespace App\Campaigns;

use App\DTOs\LandingPageAnalysis;
use App\Library\CampaignDecision\CampaignPerformanceBrief;
use App\Services\LandingPageAnalyzer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * Reads a landing page during the hourly monitor when that page is the break.
 *
 * The text is cached by URL for a day. A plain download is used first. A
 * JavaScript shell, such as lucos.com, is rendered in a browser by the
 * analyser and kept only when that render has real headings or body text.
 */
class CampaignLandingPageText
{
    public function __construct(private LandingPageAnalyzer $analyzer) {}

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>
     */
    public function fillIfPageIsTheBreak(array $snapshot): array
    {
        if (! CampaignPerformanceBrief::shouldReadLandingPages($snapshot)) {
            return $snapshot;
        }

        $context = is_array($snapshot['creative_context'] ?? null) ? $snapshot['creative_context'] : [];
        $snapshot['creative_context'] = $this->remember($context);

        return $snapshot;
    }

    /**
     * @param  array<string, mixed>  $context
     * @return array<string, mixed>
     */
    public function remember(array $context): array
    {
        $page = is_array($context['landing_page'] ?? null) ? $context['landing_page'] : [];

        if ($this->usable($page)) {
            return $this->withFlow($context, $page);
        }

        $url = $this->fetchUrl($this->landingUrl($context));

        if ($url === '') {
            return $context;
        }

        $cached = Cache::get($this->cacheKey($url));

        if (is_array($cached) && $this->usable($cached)) {
            return $this->withFlow($context, $cached);
        }

        try {
            $analysis = $this->analyzer->analyze($url, renderShell: true);
        } catch (Throwable $exception) {
            Log::warning('Landing page text was not stored', [
                'url' => $url,
                'error' => $exception->getMessage(),
            ]);

            return $context;
        }

        $stored = $this->pageFromAnalysis($analysis);

        if (! $this->usable($stored)) {
            return $context;
        }

        Cache::put($this->cacheKey($url), $stored, now()->addDay());

        return $this->withFlow($context, $stored);
    }

    /**
     * @param  array<string, mixed>  $context
     * @return array<string, mixed>
     */
    public function attachLandingFlow(array $context): array
    {
        $page = is_array($context['landing_page'] ?? null) ? $context['landing_page'] : [];

        if (! $this->usable($page)) {
            return $context;
        }

        return $this->withFlow($context, $page);
    }

    /**
     * @param  array<string, mixed>  $page
     * @param  list<array{url: string, label: string}>  $links
     * @return list<array<string, mixed>>
     */
    private function followFlow(string $startUrl, array $page, array $links): array
    {
        $flow = [array_merge($page, ['url' => $startUrl, 'step' => 1])];
        $seen = [strtolower(rtrim((string) parse_url($startUrl, PHP_URL_PATH), '/') ?: '/')];

        foreach ($this->nextFlowUrls($links, $startUrl) as $nextUrl) {
            $path = strtolower(rtrim((string) parse_url($nextUrl, PHP_URL_PATH), '/') ?: '/');

            if (in_array($path, $seen, true) || count($flow) >= 4) {
                continue;
            }

            $next = $this->fetchStoredPage($nextUrl);

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

            $seen[] = $path;
            $flow[] = array_merge($next, ['url' => $nextUrl, 'step' => count($flow) + 1]);
        }

        return $flow;
    }

    /**
     * @param  list<array{url: string, label: string}>  $links
     * @return list<string>
     */
    private function nextFlowUrls(array $links, string $startUrl): array
    {
        $needles = ['onboarding', 'continue', 'get started', 'sign up', 'signup', 'next', 'start', 'try', 'search'];
        $ranked = [];

        foreach ($links as $link) {
            $url = $this->fetchUrl((string) ($link['url'] ?? ''));
            $label = strtolower((string) ($link['label'] ?? ''));
            $path = strtolower((string) parse_url($url, PHP_URL_PATH));

            if ($url === '' || $url === $startUrl) {
                continue;
            }

            foreach ($needles as $index => $needle) {
                if (str_contains($label, $needle) || str_contains($path, $needle)) {
                    $ranked[$index][] = $url;
                    break;
                }
            }
        }

        $urls = [];

        foreach ($ranked as $group) {
            foreach ($group as $url) {
                $urls[] = $url;
            }
        }

        return array_values(array_unique($urls));
    }

    /**
     * @return array<string, mixed>|null
     */
    private function fetchStoredPage(string $url): ?array
    {
        $cached = Cache::get($this->cacheKey($url));

        if (is_array($cached) && $this->usable($cached)) {
            return $cached;
        }

        try {
            $analysis = $this->analyzer->analyze($url, renderShell: true);
        } catch (Throwable) {
            return null;
        }

        $stored = $this->pageFromAnalysis($analysis);

        if (! $this->usable($stored)) {
            return null;
        }

        Cache::put($this->cacheKey($url), $stored, now()->addDay());

        return $stored;
    }

    /**
     * @return array<string, mixed>
     */
    private function pageFromAnalysis(LandingPageAnalysis $analysis): array
    {
        return [
            'title' => $this->clip($analysis->title),
            'description' => $this->clip($analysis->description),
            'headings' => array_values(array_filter(array_map(
                fn (mixed $heading): ?string => $this->clip(is_string($heading) ? $heading : null),
                array_slice($analysis->headings, 0, 5),
            ))),
            'text' => $this->clip($analysis->text, 400),
            'same_host_links' => array_slice($analysis->sameHostLinks, 0, 12),
            'fetched_at' => now()->toIso8601String(),
        ];
    }

    /**
     * @param  array<string, mixed>  $context
     * @param  array<string, mixed>  $page
     * @return array<string, mixed>
     */
    private function withFlow(array $context, array $page): array
    {
        $context['landing_page'] = $page;

        if (is_array($context['landing_flow'] ?? null) && $context['landing_flow'] !== []) {
            return $context;
        }

        $url = $this->fetchUrl($this->landingUrl($context));
        $links = is_array($page['same_host_links'] ?? null) ? $page['same_host_links'] : [];
        $context['landing_flow'] = $this->followFlow($url, $page, $links);

        return $context;
    }

    /**
     * A fresh creative read does not include the page text saved on the hourly run.
     *
     * @param  array<string, mixed>  $fresh
     * @param  array<string, mixed>  $stored
     * @return array<string, mixed>
     */
    public function keepStoredPage(array $fresh, array $stored): array
    {
        $storedPage = is_array($stored['landing_page'] ?? null) ? $stored['landing_page'] : [];
        $freshPage = is_array($fresh['landing_page'] ?? null) ? $fresh['landing_page'] : [];

        if ($this->usable($storedPage) && ! $this->usable($freshPage)) {
            $fresh['landing_page'] = $storedPage;
        }

        $storedFlow = is_array($stored['landing_flow'] ?? null) ? $stored['landing_flow'] : [];
        $freshFlow = is_array($fresh['landing_flow'] ?? null) ? $fresh['landing_flow'] : [];

        if ($storedFlow !== [] && $freshFlow === []) {
            $fresh['landing_flow'] = $storedFlow;
        }

        return $fresh;
    }

    /**
     * @param  array<string, mixed>  $page
     */
    private function usable(array $page): bool
    {
        $headings = array_filter(
            is_array($page['headings'] ?? null) ? $page['headings'] : [],
            fn (mixed $heading): bool => is_string($heading) && trim($heading) !== '',
        );

        return $headings !== [] || mb_strlen(trim((string) ($page['text'] ?? ''))) >= 200;
    }

    /**
     * @param  array<string, mixed>  $context
     */
    private function landingUrl(array $context): string
    {
        $url = $context['landing_url'] ?? null;

        if (! is_string($url) || trim($url) === '') {
            $first = $context['landing_urls'][0] ?? null;
            $url = is_string($first) ? $first : '';
        }

        return trim($url);
    }

    private function fetchUrl(string $url): string
    {
        $url = trim(preg_replace('/\{\{[^}]+\}\}/', '', $url) ?? $url);
        $parts = parse_url($url);

        if (! is_array($parts) || ! is_string($parts['host'] ?? null) || $parts['host'] === '') {
            return '';
        }

        $built = ($parts['scheme'] ?? 'https').'://'.$parts['host'].($parts['path'] ?? '/');
        $kept = [];

        if (isset($parts['query']) && is_string($parts['query'])) {
            parse_str($parts['query'], $params);

            foreach ($params as $key => $value) {
                if (! is_string($key) || str_starts_with(strtolower($key), 'utm_') || $value === '' || $value === null) {
                    continue;
                }

                $kept[$key] = $value;
            }
        }

        if ($kept !== []) {
            $built .= '?'.http_build_query($kept);
        }

        return $built;
    }

    private function cacheKey(string $url): string
    {
        return 'campaign-landing-page:'.sha1($url);
    }

    private function clip(?string $value, int $limit = 240): ?string
    {
        if ($value === null) {
            return null;
        }

        $value = trim($value);

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

        return mb_strlen($value) > $limit ? mb_substr($value, 0, $limit) : $value;
    }
}
