<?php

namespace App\Campaigns;

use App\DTOs\LandingPageAnalysis;
use App\Models\Asset;
use App\Models\Campaign;
use App\Models\CampaignAd;
use App\Models\CampaignCreative;
use App\Services\LandingPageAnalyzer;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;

class CampaignCreativeContext
{
    /**
     * Creatives and landing-page text for a campaign created in this app.
     * Whale-only campaigns have no local row, so the AI snapshot records that nothing was found.
     *
     * @return array<string, mixed>
     */
    public function forExternal(string $platform, string $externalCampaignId): array
    {
        $externalCampaignId = trim($externalCampaignId);

        if ($platform === '' || $externalCampaignId === '') {
            return ['found' => false];
        }

        $campaign = Campaign::query()
            ->where('platform', $platform)
            ->where('external_campaign_id', $externalCampaignId)
            ->with(['brief', 'campaignCreatives.creative.asset', 'campaignCreatives.adCopy', 'ads.asset'])
            ->first();

        if ($campaign === null) {
            return $this->indexImages($this->withLandingPage($this->fromWhale($platform, $externalCampaignId)));
        }

        $analysis = $campaign->brief?->pageAnalysis();

        $context = [
            'found' => true,
            'name' => $campaign->name,
            'objective' => $campaign->objective,
            'landing_url' => $campaign->landing_url ?: $campaign->brief?->landing_url,
            'landing_page' => $this->landingPageFromBrief($analysis),
            'creatives' => $campaign->campaignCreatives
                ->take(12)
                ->map(function (CampaignCreative $link): array {
                    $copy = $link->adCopy;

                    return [
                        'creative_id' => (string) ($link->creative_id ?? ''),
                        'title' => $link->creative?->title,
                        'type' => $link->creative?->type,
                        'status' => $link->status,
                        'headline' => $copy?->headline,
                        'primary_text' => $this->clip($copy?->primary_text, 800),
                        'description' => $this->clip($copy?->description, 500),
                        'cta' => $copy?->cta,
                        'images' => $this->storedImages($link->creative?->asset, (string) ($link->creative?->id ?? '')),
                    ];
                })
                ->values()
                ->all(),
            'ads' => $campaign->ads
                ->take(200)
                ->map(fn (CampaignAd $ad): array => [
                    'ad_id' => $ad->external_ad_id,
                    'creative_id' => trim((string) ($ad->external_creative_id ?? '')),
                    'headline' => $ad->headline,
                    'primary_text' => $this->clip($ad->primary_text, 800),
                    'description' => $this->clip($ad->description, 500),
                    'cta' => $ad->cta,
                    'status' => $ad->status,
                    'images' => $this->storedImages($ad->asset, (string) ($ad->external_ad_id ?? $ad->id)),
                ])
                ->values()
                ->all(),
        ];

        $context = $this->indexImages($this->withAdDelivery($this->withLandingPage($context), $platform, $externalCampaignId));

        if ($this->hasAdCopy($context)) {
            return $this->withWhaleImages($context, $platform, $externalCampaignId);
        }

        $whale = $this->indexImages($this->withLandingPage($this->fromWhale($platform, $externalCampaignId)));

        if (($whale['found'] ?? false) === true && $this->hasAdCopy($whale)) {
            return $whale;
        }

        return $context;
    }

    /**
     * @param  array<string, mixed>  $context
     */
    private function hasAdCopy(array $context): bool
    {
        foreach (['ads', 'creatives'] as $key) {
            $rows = $context[$key] ?? [];

            if (! is_array($rows)) {
                continue;
            }

            foreach ($rows as $row) {
                if (! is_array($row)) {
                    continue;
                }

                if (trim((string) ($row['headline'] ?? '')) !== '' || trim((string) ($row['primary_text'] ?? '')) !== '') {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Whale-only campaigns still have ad copy and landing URLs in arb_adops_ads / arb_adops_creatives.
     *
     * @return array<string, mixed>
     */
    private function fromWhale(string $platform, string $externalCampaignId): array
    {
        try {
            if (! Schema::connection('whale')->hasTable('arb_adops_ads')) {
                return ['found' => false];
            }

            $ads = DB::connection('whale')->table('arb_adops_ads')
                ->where('platform', $platform)
                ->where('campaign_id', $externalCampaignId)
                ->limit(200)
                ->get();
        } catch (Throwable) {
            return ['found' => false];
        }

        if ($ads->isEmpty()) {
            return ['found' => false];
        }

        $creativeIds = $ads->pluck('creative_id')->filter()->unique()->values()->all();
        $creatives = collect();

        if ($creativeIds !== []) {
            try {
                if (Schema::connection('whale')->hasTable('arb_adops_creatives')) {
                    $creatives = DB::connection('whale')->table('arb_adops_creatives')
                        ->where('platform', $platform)
                        ->whereIn('creative_id', $creativeIds)
                        ->get()
                        ->keyBy(fn (object $row): string => (string) $row->creative_id);
                }
            } catch (Throwable) {
                $creatives = collect();
            }
        }

        $landingUrls = [];

        $adRows = $ads->take(200)->map(function (object $ad) use ($creatives, &$landingUrls): array {
            $creative = $creatives->get((string) ($ad->creative_id ?? ''));
            $creativeUrl = is_object($creative) ? ($creative->landing_url ?? null) : null;
            $url = $this->clip(is_string($ad->final_url ?? null) ? $ad->final_url : (is_string($creativeUrl) ? $creativeUrl : null), 300);
            $headlines = $this->texts(is_object($creative) ? ($creative->headlines ?? null) : null);

            if (is_string($url) && $url !== '') {
                $landingUrls[$url] = $url;
            }

            $headlines = $this->textList(is_object($creative) ? ($creative->headlines ?? null) : null);
            $adId = (string) ($ad->ad_id ?? '');

            return [
                'ad_id' => $adId,
                'creative_id' => trim((string) ($ad->creative_id ?? '')),
                'name' => $this->clip(is_string($ad->name ?? null) ? $ad->name : null),
                'headline' => $headlines[0] ?? null,
                'headlines' => $headlines,
                'primary_text' => $this->clip(is_object($creative) && is_string($creative->primary_text ?? null) ? $creative->primary_text : null, 800),
                'description' => $this->clip(is_object($creative) && is_string($creative->description ?? null) ? $creative->description : null, 500),
                'cta' => $this->clip(is_object($creative) && is_string($creative->cta ?? null) ? $creative->cta : null, 40),
                'image_url' => $this->firstUrl(is_object($creative) ? ($creative->image_urls ?? null) : null)
                    ?? $this->urlOrNull(is_object($creative) ? ($creative->thumbnail_url ?? null) : null),
                'landing_url' => $url,
                'status' => $this->clip(is_string($ad->effective_status ?? null) ? $ad->effective_status : null, 40),
                'images' => $this->remoteImages($creative, $adId),
            ];
        })->values()->all();

        return $this->withAdDelivery([
            'found' => true,
            'source' => 'whale',
            'landing_url' => array_values($landingUrls)[0] ?? null,
            'landing_urls' => array_slice(array_values($landingUrls), 0, 12),
            'landing_page' => [
                'title' => null,
                'description' => null,
                'headings' => [],
                'subheadings' => [],
                'calls_to_action' => [],
                'prices' => [],
                'text' => null,
            ],
            'creatives' => $adRows,
            'ads' => $adRows,
        ], $platform, $externalCampaignId);
    }

    /**
     * Whale rows store the URL and the ad copy, not the page body. Read the
     * public page so a landing-page verdict can name what is wrong and propose
     * a replacement. A filled brief already has that text.
     *
     * @param  array<string, mixed>  $context
     * @return array<string, mixed>
     */
    private function withLandingPage(array $context): array
    {
        if (($context['found'] ?? false) !== true || ! config('campaign-performance.read_landing_pages', true)) {
            return $context;
        }

        $existing = data_get($context, 'landing_page.text');

        if (is_string($existing) && trim($existing) !== '') {
            return app(CampaignLandingPageText::class)->attachLandingFlow($context);
        }

        $url = $this->publicPageUrl($context);

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

        try {
            $page = Cache::remember(
                'campaign-landing-page:v3:'.sha1($url),
                now()->addHours(12),
                function () use ($url): array {
                    $analyzer = app(LandingPageAnalyzer::class);
                    $analysis = $analyzer->analyze($url);

                    return [
                        'landing_page' => [
                            'title' => $this->clip($analysis->title),
                            'description' => $this->clip(
                                $analysis->description !== '' ? $analysis->description : $analysis->socialDescription,
                                500,
                            ),
                            'headings' => array_slice($analysis->headings, 0, 12),
                            'subheadings' => array_slice($analysis->subheadings, 0, 12),
                            'calls_to_action' => array_slice($analysis->callsToAction, 0, 12),
                            'prices' => array_slice($analysis->prices, 0, 8),
                            'same_host_links' => array_slice($analysis->sameHostLinks, 0, 12),
                            'text' => $this->clip(
                                $analysis->reviewText !== '' ? $analysis->reviewText : $analysis->text,
                                8000,
                            ),
                        ],
                        'website' => app(CampaignWebsiteContext::class)->fromLanding($analysis),
                    ];
                },
            );
        } catch (Throwable) {
            return $context;
        }

        if (! is_array($page)) {
            return $context;
        }

        $landingPage = $page['landing_page'] ?? $page;

        if (is_array($landingPage)) {
            $context['landing_page'] = $landingPage;
        }

        if (is_array($page['website'] ?? null) && ($page['website']['pages'] ?? []) !== []) {
            $context['website'] = $page['website'];
        }

        return app(CampaignLandingPageText::class)->attachLandingFlow($context);
    }

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

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

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

        $parts = parse_url($url);

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

        $scheme = is_string($parts['scheme'] ?? null) && $parts['scheme'] !== '' ? $parts['scheme'] : 'https';
        $path = is_string($parts['path'] ?? null) ? $parts['path'] : '';

        return $scheme.'://'.$parts['host'].$path;
    }

    /**
     * @param  array<string, mixed>  $context
     * @return array<string, mixed>
     */
    private function withAdDelivery(array $context, string $platform, string $externalCampaignId): array
    {
        $windows = $this->adWindows($platform, $externalCampaignId);
        $ads = is_array($context['ads'] ?? null) ? $context['ads'] : [];
        $seen = [];

        foreach ($ads as $index => $ad) {
            if (! is_array($ad)) {
                continue;
            }

            $id = trim((string) ($ad['ad_id'] ?? ''));

            if ($id === '') {
                continue;
            }

            if (isset($windows['7'][$id])) {
                $ads[$index]['last_7_days'] = $windows['7'][$id];
            }

            if (isset($windows['previous_7'][$id])) {
                $ads[$index]['previous_7_days'] = $windows['previous_7'][$id];
            }

            if (isset($windows['30'][$id])) {
                $ads[$index]['last_30_days'] = $windows['30'][$id];
            }

            $seen[$id] = true;

            foreach (['quality_ranking', 'engagement_rate_ranking', 'conversion_rate_ranking'] as $metric) {
                if (isset($windows['quality'][$id][$metric])) {
                    $ads[$index][$metric] = $windows['quality'][$id][$metric];
                }
            }
        }

        foreach (array_keys($windows['30'] + $windows['7']) as $id) {
            if (isset($seen[$id])) {
                continue;
            }

            $row = [
                'ad_id' => $id,
                'name' => $id,
                'status' => '',
            ];

            if (isset($windows['7'][$id])) {
                $row['last_7_days'] = $windows['7'][$id];
            }

            if (isset($windows['previous_7'][$id])) {
                $row['previous_7_days'] = $windows['previous_7'][$id];
            }

            if (isset($windows['30'][$id])) {
                $row['last_30_days'] = $windows['30'][$id];
            }

            $ads[] = $row;
        }

        $context['ads'] = $ads;

        if (($context['source'] ?? null) === 'whale') {
            $context['creatives'] = $ads;
        }
        $seven = array_values($windows['7']);
        usort($seven, function (array $left, array $right): int {
            $leftRate = $left['ctr'] ?? 1;
            $rightRate = $right['ctr'] ?? 1;

            return $leftRate <=> $rightRate ?: ((float) $right['spend'] <=> (float) $left['spend']);
        });
        $context['ad_performance'] = $seven;

        return $context;
    }

    /**
     * @return array{
     *     7: array<string, array<string, mixed>>,
     *     previous_7: array<string, array<string, mixed>>,
     *     30: array<string, array<string, mixed>>,
     *     quality: array<string, array<string, string>>
     * }
     */
    private function adWindows(string $platform, string $externalCampaignId): array
    {
        $since = Carbon::now()->subDays(29)->toDateString();
        $sevenFrom = Carbon::now()->subDays(6)->toDateString();
        $previousFrom = Carbon::now()->subDays(13)->toDateString();
        $totals = ['7' => [], 'previous_7' => [], '30' => []];

        foreach ([0, 1] as $monthsAgo) {
            $table = 'arb_adops_stats_daily_'.Carbon::now()->subMonths($monthsAgo)->format('Ym');

            try {
                if (! Schema::connection('whale')->hasTable($table)) {
                    continue;
                }

                $columns = Schema::connection('whale')->getColumnListing($table);
                $select = ['ad_id', 'stat_date', 'spend', 'impressions'];

                foreach (['clicks', 'link_clicks', 'frequency', 'reach', 'landing_page_views', 'entity_level'] as $optional) {
                    if (in_array($optional, $columns, true)) {
                        $select[] = $optional;
                    }
                }

                $query = DB::connection('whale')->table($table)
                    ->where('platform', $platform)
                    ->where('campaign_id', $externalCampaignId)
                    ->where('stat_date', '>=', $since);

                if (in_array('entity_level', $columns, true)) {
                    $query->where('entity_level', 'ad');
                }

                $rows = $query->get($select);
            } catch (Throwable) {
                continue;
            }

            foreach ($rows as $row) {
                $id = trim((string) ($row->ad_id ?? ''));
                $date = substr((string) ($row->stat_date ?? ''), 0, 10);
                $level = strtolower(trim((string) ($row->entity_level ?? '')));

                if ($id === '' || $date === '' || $id === $externalCampaignId) {
                    continue;
                }

                if ($level !== '' && $level !== 'ad') {
                    continue;
                }

                $linkClicks = isset($row->link_clicks) && is_numeric($row->link_clicks) ? (int) $row->link_clicks : null;
                $allClicks = isset($row->clicks) && is_numeric($row->clicks) ? (int) $row->clicks : null;
                $clicks = $linkClicks ?? $allClicks ?? 0;
                $frequency = isset($row->frequency) && is_numeric($row->frequency) ? (float) $row->frequency : null;
                $lpv = isset($row->landing_page_views) && is_numeric($row->landing_page_views)
                    ? (int) $row->landing_page_views
                    : null;
                $this->addAdDelivery($totals['30'], $id, (float) $row->spend, (int) $row->impressions, $clicks, $frequency, $lpv, $linkClicks);

                if ($date >= $sevenFrom) {
                    $this->addAdDelivery($totals['7'], $id, (float) $row->spend, (int) $row->impressions, $clicks, $frequency, $lpv, $linkClicks);
                } elseif ($date >= $previousFrom) {
                    $this->addAdDelivery($totals['previous_7'], $id, (float) $row->spend, (int) $row->impressions, $clicks, $frequency, $lpv, $linkClicks);
                }
            }
        }

        return [
            '7' => $this->finishAdWindows($totals['7']),
            'previous_7' => $this->finishAdWindows($totals['previous_7']),
            '30' => $this->finishAdWindows($totals['30']),
            'quality' => $this->qualityByAd($platform, $externalCampaignId, $sevenFrom),
        ];
    }

    /**
     * @return array<string, array<string, string>>
     */
    private function qualityByAd(string $platform, string $externalCampaignId, string $since): array
    {
        $latest = [];

        foreach ([0, 1] as $monthsAgo) {
            $table = 'arb_adops_quality_daily_'.Carbon::now()->subMonths($monthsAgo)->format('Ym');

            try {
                if (! Schema::connection('whale')->hasTable($table)) {
                    continue;
                }

                $columns = Schema::connection('whale')->getColumnListing($table);
                $idColumn = in_array('entity_id', $columns, true)
                    ? 'entity_id'
                    : (in_array('ad_id', $columns, true) ? 'ad_id' : null);

                if ($idColumn === null || ! in_array('metric', $columns, true) || ! in_array('value', $columns, true)) {
                    continue;
                }

                $query = DB::connection('whale')->table($table)
                    ->where('platform', $platform)
                    ->where('campaign_id', $externalCampaignId)
                    ->where('stat_date', '>=', $since);

                if (in_array('entity_level', $columns, true)) {
                    $query->where('entity_level', 'ad');
                }

                $rows = $query->get([$idColumn, 'stat_date', 'metric', 'value']);
            } catch (Throwable) {
                continue;
            }

            foreach ($rows as $row) {
                $id = trim((string) ($row->{$idColumn} ?? ''));
                $metric = trim((string) ($row->metric ?? ''));
                $date = substr((string) ($row->stat_date ?? ''), 0, 10);
                $value = trim((string) ($row->value ?? ''));

                if ($id === '' || $metric === '' || $value === '' || $date === '') {
                    continue;
                }

                if (! isset($latest[$id][$metric]) || $date >= $latest[$id][$metric]['date']) {
                    $latest[$id][$metric] = ['date' => $date, 'value' => $value];
                }
            }
        }

        $out = [];

        foreach ($latest as $id => $metrics) {
            foreach ($metrics as $metric => $info) {
                $out[$id][$metric] = $info['value'];
            }
        }

        return $out;
    }

    /**
     * @param  array<string, array<string, mixed>>  $totals
     * @return array<string, array<string, mixed>>
     */
    private function finishAdWindows(array $totals): array
    {
        foreach ($totals as $id => $row) {
            unset($row['frequency_weight'], $row['frequency_impressions']);
            $totals[$id] = $row;
        }

        return $totals;
    }

    /**
     * @return list<string>
     */
    private function textList(mixed $value): array
    {
        if (is_string($value) && str_starts_with(trim($value), '[')) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : [$value];
        }

        if (! is_array($value)) {
            $single = $this->clip(is_string($value) ? $value : null);

            return $single === null ? [] : [$single];
        }

        $lines = [];

        foreach ($value as $item) {
            if (is_array($item)) {
                $item = $item['text'] ?? null;
            }

            $line = $this->clip(is_string($item) ? $item : null);

            if ($line !== null && ! in_array($line, $lines, true)) {
                $lines[] = $line;
            }

            if (count($lines) >= 5) {
                break;
            }
        }

        return $lines;
    }

    private function firstUrl(mixed $value): ?string
    {
        if (is_string($value) && str_starts_with(trim($value), '[')) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : [$value];
        }

        if (is_array($value)) {
            $value = $value[0] ?? null;
        }

        return $this->urlOrNull($value);
    }

    private function urlOrNull(mixed $value): ?string
    {
        $value = trim((string) $value);

        return $value === '' ? null : $value;
    }

    private function firstText(mixed $value): ?string
    {
        if (is_string($value) && str_starts_with(trim($value), '[')) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : $value;
        }

        if (is_array($value)) {
            $first = $value[0] ?? null;

            if (is_array($first)) {
                $first = $first['text'] ?? null;
            }

            return $this->clip(is_string($first) ? $first : null);
        }

        return $this->clip(is_string($value) ? $value : null);
    }

    /**
     * @param  array<string, array<string, mixed>>  $totals
     */
    private function addAdDelivery(
        array &$totals,
        string $id,
        float $spend,
        int $impressions,
        int $clicks,
        ?float $frequency = null,
        ?int $landingPageViews = null,
        ?int $linkClicks = null,
    ): void {
        $current = $totals[$id] ?? [
            'ad_id' => $id,
            'impressions' => 0,
            'clicks' => 0,
            'link_clicks' => null,
            'spend' => 0.0,
            'frequency_weight' => 0.0,
            'frequency_impressions' => 0,
            'landing_page_views' => null,
        ];
        $totalImpressions = (int) $current['impressions'] + $impressions;
        $totalClicks = (int) $current['clicks'] + $clicks;
        $totalLinkClicks = $linkClicks === null
            ? ($current['link_clicks'] ?? null)
            : (int) ($current['link_clicks'] ?? 0) + $linkClicks;
        $totalSpend = round((float) $current['spend'] + $spend, 2);
        $frequencyWeight = (float) ($current['frequency_weight'] ?? 0);
        $frequencyImpressions = (int) ($current['frequency_impressions'] ?? 0);

        if ($frequency !== null && $impressions > 0) {
            $frequencyWeight += $frequency * $impressions;
            $frequencyImpressions += $impressions;
        }

        $ctrClicks = is_int($totalLinkClicks) ? $totalLinkClicks : $totalClicks;
        $row = [
            'ad_id' => $id,
            'impressions' => $totalImpressions,
            'clicks' => $totalClicks,
            'link_clicks' => $totalLinkClicks,
            'spend' => $totalSpend,
            'ctr' => $totalImpressions > 0 && $ctrClicks > 0 ? round($ctrClicks / $totalImpressions, 4) : null,
            'cpc' => $ctrClicks > 0 ? round($totalSpend / $ctrClicks, 4) : null,
            'frequency_weight' => $frequencyWeight,
            'frequency_impressions' => $frequencyImpressions,
            'landing_page_views' => $current['landing_page_views'] ?? null,
        ];

        if ($frequencyImpressions > 0) {
            $row['frequency'] = round($frequencyWeight / $frequencyImpressions, 4);
        }

        if ($landingPageViews !== null) {
            $row['landing_page_views'] = (int) ($row['landing_page_views'] ?? 0) + $landingPageViews;
        }

        $totals[$id] = $row;
    }

    /**
     * @return list<string>
     */
    private function texts(mixed $value): array
    {
        if (is_string($value) && str_starts_with(trim($value), '[')) {
            $decoded = json_decode($value, true);
            $value = is_array($decoded) ? $decoded : $value;
        }

        if (is_string($value)) {
            $text = $this->clip($value);

            return $text === null ? [] : [$text];
        }

        if (! is_array($value)) {
            return [];
        }

        $texts = [];

        foreach ($value as $item) {
            if (is_array($item)) {
                $item = $item['text'] ?? null;
            }

            $text = $this->clip(is_string($item) ? $item : null);

            if ($text !== null) {
                $texts[] = $text;
            }

            if (count($texts) >= 5) {
                break;
            }
        }

        return $texts;
    }

    /**
     * @return array<string, mixed>
     */
    private function landingPageFromBrief(?LandingPageAnalysis $analysis): array
    {
        if ($analysis === null) {
            return [
                'title' => null,
                'description' => null,
                'headings' => [],
                'subheadings' => [],
                'calls_to_action' => [],
                'prices' => [],
                'text' => null,
            ];
        }

        return [
            'title' => $analysis->title !== '' ? $analysis->title : null,
            'description' => $this->clip(
                $analysis->description !== '' ? $analysis->description : $analysis->socialDescription,
                500,
            ),
            'headings' => array_slice(array_values(array_filter(array_map(
                fn (mixed $heading): ?string => $this->clip(is_string($heading) ? $heading : null),
                $analysis->headings,
            ))), 0, 12),
            'subheadings' => array_slice($analysis->subheadings, 0, 12),
            'calls_to_action' => array_slice($analysis->callsToAction, 0, 12),
            'prices' => array_slice($analysis->prices, 0, 8),
            'text' => $this->clip($analysis->reviewText !== '' ? $analysis->reviewText : $analysis->text, 8000),
        ];
    }

    /**
     * A campaign created here can still have its pictures only in Whale.
     *
     * @param  array<string, mixed>  $context
     * @return array<string, mixed>
     */
    private function withWhaleImages(array $context, string $platform, string $externalCampaignId): array
    {
        if (($context['images'] ?? []) !== []) {
            return $context;
        }

        $whale = $this->indexImages($this->fromWhale($platform, $externalCampaignId));

        if (($whale['images'] ?? []) === []) {
            return $context;
        }

        $context['images'] = $whale['images'];

        return $context;
    }

    /**
     * Still images the recommendation model can see. Video files are left out.
     * A video contributes only its poster frame.
     *
     * @return list<array{ad_id: string, creative_id: string, url: string, kind: string}>
     */
    private function remoteImages(mixed $creative, string $adId): array
    {
        if (! is_object($creative)) {
            return [];
        }

        $type = strtolower(trim((string) ($creative->type ?? '')));
        $kind = 'image';
        $urls = $type === 'video' ? [] : $this->urlList($creative->image_urls ?? null);

        if ($urls === []) {
            $thumb = $this->publicImageUrl(is_string($creative->thumbnail_url ?? null) ? $creative->thumbnail_url : null);

            if ($thumb === null) {
                return [];
            }

            $urls = [$thumb];
            $kind = $type === 'video' ? 'poster' : 'image';
        }

        $images = [];

        $creativeId = trim((string) ($creative->creative_id ?? ''));

        foreach (array_slice($urls, 0, 2) as $url) {
            $images[] = [
                'ad_id' => $adId,
                'creative_id' => $creativeId,
                'url' => $url,
                'kind' => $kind,
            ];
        }

        return $images;
    }

    /**
     * @return list<string>
     */
    private function urlList(mixed $value): array
    {
        if (is_string($value)) {
            $trimmed = trim($value);
            $decoded = str_starts_with($trimmed, '[') ? json_decode($trimmed, true) : null;
            $value = is_array($decoded) ? $decoded : ($trimmed === '' ? [] : [$trimmed]);
        }

        if (! is_array($value)) {
            return [];
        }

        $urls = [];

        foreach ($value as $item) {
            if (is_array($item)) {
                $item = $item['url'] ?? $item['image_url'] ?? null;
            }

            $url = $this->publicImageUrl(is_string($item) ? $item : null);

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

            $urls[$url] = $url;

            if (count($urls) >= 2) {
                break;
            }
        }

        return array_values($urls);
    }

    private function publicImageUrl(?string $url): ?string
    {
        $url = trim((string) $url);

        if ($url === '' || preg_match('#^https?://#i', $url) !== 1) {
            return null;
        }

        $path = strtolower((string) parse_url($url, PHP_URL_PATH));

        foreach (['.mp4', '.mov', '.webm', '.m3u8', '.m4v'] as $extension) {
            if (str_ends_with($path, $extension)) {
                return null;
            }
        }

        return mb_substr($url, 0, 2000);
    }

    /**
     * @return list<array{ad_id: string, disk: string, path: string, kind: string}>
     */
    private function storedImages(?Asset $asset, string $adId): array
    {
        if ($asset === null || blank($asset->path) || $asset->kind === 'video' || str_starts_with((string) $asset->mime, 'video/')) {
            return [];
        }

        return [[
            'ad_id' => $adId,
            'disk' => $asset->disk ?: 'local',
            'path' => (string) $asset->path,
            'kind' => 'image',
        ]];
    }

    /**
     * @param  array<string, mixed>  $context
     * @return array<string, mixed>
     */
    private function indexImages(array $context): array
    {
        if (($context['found'] ?? false) !== true) {
            return $context;
        }

        $found = [];

        foreach (['ads', 'creatives'] as $key) {
            $rows = $context[$key] ?? [];

            if (! is_array($rows)) {
                continue;
            }

            foreach ($rows as $row) {
                if (! is_array($row)) {
                    continue;
                }

                foreach ($row['images'] ?? [] as $image) {
                    if (! is_array($image)) {
                        continue;
                    }

                    $id = (string) ($image['url'] ?? (($image['disk'] ?? '').'|'.($image['path'] ?? '')));

                    if ($id === '' || $id === '|' || isset($found[$id])) {
                        continue;
                    }

                    $found[$id] = $image;
                }
            }
        }

        $images = array_values($found);
        usort($images, function (array $left, array $right): int {
            return (($left['kind'] ?? '') === 'poster') <=> (($right['kind'] ?? '') === 'poster');
        });
        $limit = max(0, (int) config('campaign-performance.creative_image_limit', 6));
        $context['images'] = array_slice($images, 0, $limit);

        return $context;
    }

    private function clip(?string $value, int $limit = 240): ?string
    {
        $value = trim((string) $value);

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

        return mb_substr($value, 0, $limit);
    }
}
