<?php

namespace App\Library\CampaignDecision;

/**
 * PHP keep / pause / too-early labels per ad. The model may explain them, not relabel them.
 */
class CampaignAdRoster
{
    /**
     * @param  array<string, mixed>  $snapshot
     * @param  array<string, mixed>  $strategy
     * @return array{
     *     frozen: bool,
     *     ads: list<array<string, mixed>>
     * }
     */
    public static function fromSnapshot(array $snapshot, array $strategy): array
    {
        $frozen = ($strategy['broken_step'] ?? '') === 'tracking';
        $audience = (string) ($strategy['audience_mode'] ?? 'prospecting');
        $campaignSpend = (float) data_get($strategy, 'delivery.spend_7d', data_get($snapshot, 'windows.7d.spend', 0));
        $ads = self::sourceAds($snapshot);
        $drafts = [];

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

            $drafts[] = self::draft($ad, $audience, $campaignSpend);
        }

        $labeled = self::assignRelativeLabels($drafts);

        if ($frozen) {
            foreach ($labeled as $index => $row) {
                $labeled[$index]['llm_action'] = 'keep';
            }
        }

        return [
            'frozen' => $frozen,
            'ads' => $labeled,
        ];
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    public static function creativeAdviceFrozen(array $snapshot): bool
    {
        return (bool) data_get($snapshot, 'performance_strategy.ad_roster.frozen', false)
            || (string) data_get($snapshot, 'performance_strategy.broken_step') === 'tracking';
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>|null
     */
    public static function rowForAd(array $snapshot, string $adId): ?array
    {
        if ($adId === '') {
            return null;
        }

        $ads = data_get($snapshot, 'performance_strategy.ad_roster.ads');

        if (! is_array($ads)) {
            return null;
        }

        foreach ($ads as $row) {
            if (is_array($row) && trim((string) ($row['ad_id'] ?? '')) === $adId) {
                return $row;
            }
        }

        return null;
    }

    /**
     * Board/detail payload. Rebuilds labels from the stored snapshot when hourly
     * has not written ad_roster yet.
     *
     * @param  array<string, mixed>  $row
     * @return array{
     *     frozen: bool,
     *     event: string,
     *     spend: ?string,
     *     results: ?string,
     *     landing_page_views: ?string,
     *     cost_per_lpv: ?string,
     *     empty: ?string,
     *     fatigue: string,
     *     ads: list<array<string, mixed>>
     * }
     */
    public static function forDisplay(array $row): array
    {
        $snapshot = is_array($row['snapshot'] ?? null) ? $row['snapshot'] : $row;
        $strategy = is_array(data_get($snapshot, 'performance_strategy'))
            ? data_get($snapshot, 'performance_strategy')
            : (is_array($row['performance_strategy'] ?? null) ? $row['performance_strategy'] : []);
        $roster = is_array($strategy['ad_roster'] ?? null) ? $strategy['ad_roster'] : null;

        if ($strategy === [] && is_array($snapshot) && $snapshot !== []) {
            $strategy = CampaignPerformanceStrategy::fromSnapshot($snapshot);
        }

        if (self::sourceAds($snapshot) !== []) {
            $roster = self::fromSnapshot($snapshot, $strategy !== [] ? $strategy : []);
        } elseif (! is_array($roster) || ! is_array($roster['ads'] ?? null)) {
            $roster = $strategy !== []
                ? self::fromSnapshot($snapshot, $strategy)
                : ['frozen' => false, 'ads' => []];
        }

        $ads = [];

        foreach (is_array($roster['ads'] ?? null) ? $roster['ads'] : [] as $ad) {
            if (! is_array($ad)) {
                continue;
            }

            $ads[] = self::displayAd($ad);
        }

        $delivery = is_array($strategy['delivery'] ?? null) ? $strategy['delivery'] : [];
        $lpv = $delivery['landing_page_views'] ?? null;
        $spend = $delivery['spend_7d'] ?? data_get($snapshot, 'windows.7d.spend');
        $results = $strategy['platform_results'] ?? null;
        $frozen = (bool) ($roster['frozen'] ?? false) || (string) ($strategy['broken_step'] ?? '') === 'tracking';

        return [
            'frozen' => $frozen,
            'event' => (string) ($strategy['primary_result_label'] ?? $strategy['primary_result_event'] ?? ''),
            'spend' => is_numeric($spend) ? '$'.number_format((float) $spend, 2) : null,
            'results' => is_numeric($results) ? (string) (0 + $results) : null,
            'landing_page_views' => is_numeric($lpv) ? (string) (int) $lpv : null,
            'cost_per_lpv' => isset($delivery['cost_per_lpv']) && is_numeric($delivery['cost_per_lpv'])
                ? '$'.number_format((float) $delivery['cost_per_lpv'], 2)
                : null,
            'empty' => $ads === [] ? 'No ad-level windows this hour.' : null,
            'fatigue' => self::fatigueLine(
                is_array($roster['ads'] ?? null) ? $roster['ads'] : [],
                $delivery,
                $frozen,
                $strategy,
            ),
            'ads' => $ads,
        ];
    }

    /**
     * @param  array<string, mixed>  $ad
     * @return array<string, mixed>
     */
    private static function displayAd(array $ad): array
    {
        $label = (string) ($ad['label'] ?? 'watch');

        return [
            'ad_id' => (string) ($ad['ad_id'] ?? ''),
            'name' => (string) (($ad['name'] ?? '') !== '' ? $ad['name'] : ($ad['headline'] ?? 'Ad')),
            'headline' => (string) ($ad['headline'] ?? ''),
            'status' => (string) ($ad['status'] ?? ''),
            'format' => (string) ($ad['format'] ?? ''),
            'live' => self::isLive($ad),
            'spend' => '$'.number_format((float) ($ad['spend'] ?? 0), 2),
            'impressions' => number_format((int) ($ad['impressions'] ?? 0)),
            'clicks' => number_format((int) ($ad['clicks'] ?? 0)),
            'ctr' => isset($ad['ctr_percent']) && is_numeric($ad['ctr_percent'])
                ? number_format((float) $ad['ctr_percent'], 2).'%'
                : '—',
            'cpc' => isset($ad['cpc']) && is_numeric($ad['cpc']) ? '$'.number_format((float) $ad['cpc'], 2) : '—',
            'lpv' => isset($ad['landing_page_views']) && is_numeric($ad['landing_page_views'])
                ? number_format((int) $ad['landing_page_views'])
                : '—',
            'cost_per_lpv' => isset($ad['cost_per_lpv']) && is_numeric($ad['cost_per_lpv'])
                ? '$'.number_format((float) $ad['cost_per_lpv'], 2)
                : '—',
            'frequency' => isset($ad['frequency']) && is_numeric($ad['frequency'])
                ? number_format((float) $ad['frequency'], 2)
                : 'not on file',
            'ranking' => self::rankingText($ad),
            'label' => $label,
            'label_text' => self::labelText($label),
            'duplicate_copy' => (bool) ($ad['duplicate_copy'] ?? false),
            'ctr_drop' => isset($ad['ctr_drop']) && is_numeric($ad['ctr_drop']) ? (float) $ad['ctr_drop'] : null,
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $ads
     * @param  array<string, mixed>  $delivery
     */
    /**
     * @param  array<string, mixed>  $strategy
     */
    private static function fatigueLine(array $ads, array $delivery, bool $frozen, array $strategy = []): string
    {
        if ($ads === []) {
            return 'No ad-level windows this hour.';
        }

        $maxFrequency = null;
        $duplicates = 0;
        $drops = 0;

        $live = [];
        $paused = 0;

        foreach ($ads as $ad) {
            if (! self::isLive($ad)) {
                $paused++;

                continue;
            }

            $live[] = $ad;
        }

        $parts = [];

        if ($paused > 0) {
            $parts[] = $live === []
                ? 'All '.$paused.' ads on file are paused.'
                : count($live).' ads are live. '.$paused.' paused ads are listed but not used for fatigue.';
        }

        foreach ($live as $ad) {
            if (isset($ad['frequency']) && is_numeric($ad['frequency'])) {
                $maxFrequency = $maxFrequency === null
                    ? (float) $ad['frequency']
                    : max($maxFrequency, (float) $ad['frequency']);
            }

            if (($ad['duplicate_copy'] ?? false) === true) {
                $duplicates++;
            }

            if (($ad['ctr_drop'] ?? null) !== null && (float) $ad['ctr_drop'] >= 0.3) {
                $drops++;
            }
        }

        if ($live !== []) {
            if ($maxFrequency !== null) {
                $parts[] = 'Highest frequency on live ads is '.number_format($maxFrequency, 2).'.';
            } else {
                $parts[] = 'Per-ad frequency is not on file.';
            }
        }

        if ($duplicates > 0) {
            $parts[] = $duplicates.' ads share the same headline and primary text.';
        }

        if ($drops > 0) {
            $parts[] = $drops.' ad'.($drops === 1 ? ' has' : 's have').' CTR down 30% or more versus the 30-day window.';
        }

        if ($frozen) {
            $parts[] = 'Fix tracking before replacing creatives.';
        }

        if (($strategy['audience_saturated'] ?? false) === true) {
            $parts[] = 'CPM is rising while reach is flat, so the pool is saturating.';
        }

        if (($strategy['small_retargeting_pool'] ?? false) === true) {
            $parts[] = 'Retargeting reach is under about 5,000 — recheck frequency weekly.';
        }

        if (($strategy['cta_mismatch'] ?? false) === true) {
            $parts[] = 'A retargeting ad still uses See details or Learn more.';
        }

        return implode(' ', $parts);
    }

    public static function labelText(string $label): string
    {
        return match ($label) {
            'winner' => 'Winner',
            'pause' => 'Pause',
            'paused' => 'Paused',
            'too_early' => 'Too early',
            'dead' => 'Dead',
            'fatigued' => 'Fatigued, replace',
            default => 'Watch',
        };
    }

    /**
     * Ordered must-do list. The model may rephrase, not drop, skip, or reorder.
     *
     * @param  array{frozen?: bool, ads?: list<array<string, mixed>>}  $roster
     * @return list<array{action: string, ad_id: ?string, text: string}>
     */
    public static function proposedChanges(array $roster): array
    {
        $frozen = (bool) ($roster['frozen'] ?? false);
        $items = [];

        if ($frozen) {
            $items[] = [
                'action' => 'fix_tracking',
                'ad_id' => null,
                'text' => 'Check Events Manager and a test conversion for the optimization event before changing ads or the page.',
            ];
        }

        foreach (is_array($roster['ads'] ?? null) ? $roster['ads'] : [] as $ad) {
            if (! is_array($ad)) {
                continue;
            }

            $id = trim((string) ($ad['ad_id'] ?? ''));
            $name = trim((string) (($ad['name'] ?? '') !== '' ? $ad['name'] : ($ad['headline'] ?? 'Ad')));
            $label = (string) ($ad['label'] ?? 'watch');

            if (! self::isLive($ad)) {
                continue;
            }
            $named = $name.($id !== '' ? ' ('.$id.')' : '');

            $duplicate = (bool) ($ad['duplicate_copy'] ?? false);
            $ctaMismatch = (bool) ($ad['cta_mismatch'] ?? false);

            $items[] = match ($label) {
                'pause', 'dead' => [
                    'action' => 'pause_ad',
                    'ad_id' => $id !== '' ? $id : null,
                    'text' => $duplicate
                        ? 'Pause '.$named.'. It duplicates another ad\'s headline and primary text.'
                        : ((bool) ($ad['quality_pause'] ?? false)
                            ? 'Pause '.$named.'. Quality ranking is below average.'
                            : 'Pause '.$named.'.'),
                ],
                'winner' => [
                    'action' => 'keep_ad',
                    'ad_id' => $id !== '' ? $id : null,
                    'text' => 'Keep '.$named.' (winner).',
                ],
                'too_early' => [
                    'action' => 'wait_ad',
                    'ad_id' => $id !== '' ? $id : null,
                    'text' => 'Do not judge '.$named.' yet (too early).',
                ],
                'fatigued' => [
                    'action' => $frozen ? 'keep_ad' : 'replace_ad',
                    'ad_id' => $id !== '' ? $id : null,
                    'text' => $frozen
                        ? 'Keep '.$named.' until tracking is fixed (fatigued).'
                        : 'Replace '.$named.' (fatigued).',
                ],
                default => [
                    'action' => 'watch_ad',
                    'ad_id' => $id !== '' ? $id : null,
                    'text' => 'Watch '.$named.'.',
                ],
            };

            if (! $frozen && $ctaMismatch && ! in_array($label, ['pause', 'dead'], true)) {
                $items[] = [
                    'action' => 'change_cta',
                    'ad_id' => $id !== '' ? $id : null,
                    'text' => 'Change the CTA on '.$named.' from See details / Learn more to Sign up, Subscribe, or Get offer.',
                ];
            }
        }

        return $items;
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    public static function isVagueCta(array $ad): bool
    {
        $raw = strtolower(trim((string) (
            $ad['cta']
            ?? $ad['call_to_action_type']
            ?? $ad['call_to_action']
            ?? ''
        )));
        $normalized = str_replace(['-', ' '], '_', $raw);

        return in_array($normalized, ['learn_more', 'see_details', 'see_more', 'learnmore', 'see_detail'], true)
            || str_contains($raw, 'see details')
            || str_contains($raw, 'learn more');
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<array<string, mixed>>
     */
    private static function sourceAds(array $snapshot): array
    {
        $ads = data_get($snapshot, 'creative_context.ads');

        if (! is_array($ads) || $ads === []) {
            $ads = data_get($snapshot, 'creative_context.creatives');
        }

        return is_array($ads) ? array_values($ads) : [];
    }

    /**
     * @param  array<string, mixed>  $ad
     * @return array<string, mixed>
     */
    private static function draft(array $ad, string $audience, float $campaignSpend): array
    {
        $seven = is_array($ad['last_7_days'] ?? null) ? $ad['last_7_days'] : [];
        $previousSeven = is_array($ad['previous_7_days'] ?? null) ? $ad['previous_7_days'] : [];
        $thirty = is_array($ad['last_30_days'] ?? null) ? $ad['last_30_days'] : [];
        $spend = (float) ($seven['spend'] ?? $ad['spend'] ?? 0);
        $impressions = (int) ($seven['impressions'] ?? $ad['impressions'] ?? 0);
        $linkClicks = isset($seven['link_clicks']) && is_numeric($seven['link_clicks'])
            ? (int) $seven['link_clicks']
            : (isset($ad['link_clicks']) && is_numeric($ad['link_clicks']) ? (int) $ad['link_clicks'] : null);
        $clicks = $linkClicks ?? (int) ($seven['clicks'] ?? $ad['clicks'] ?? 0);
        $ctr = self::ctrPercent($seven['ctr'] ?? $ad['ctr'] ?? null, $impressions, $clicks);
        $cpc = isset($seven['cpc']) && is_numeric($seven['cpc'])
            ? round((float) $seven['cpc'], 2)
            : ($clicks > 0 && $spend > 0 ? round($spend / $clicks, 2) : null);
        $lpv = isset($seven['landing_page_views']) && is_numeric($seven['landing_page_views'])
            ? (int) $seven['landing_page_views']
            : (isset($ad['landing_page_views']) && is_numeric($ad['landing_page_views']) ? (int) $ad['landing_page_views'] : null);
        $costPerLpv = ($lpv !== null && $lpv > 0 && $spend > 0) ? round($spend / $lpv, 2) : null;
        $frequency = isset($seven['frequency']) && is_numeric($seven['frequency'])
            ? (float) $seven['frequency']
            : (isset($ad['frequency']) && is_numeric($ad['frequency']) ? (float) $ad['frequency'] : null);
        $priorWindow = $previousSeven !== [] ? $previousSeven : $thirty;
        $priorCtr = self::ctrPercent(
            $priorWindow['ctr'] ?? null,
            (int) ($priorWindow['impressions'] ?? 0),
            (int) ($priorWindow['clicks'] ?? 0),
        );
        $ctrDrop = ($ctr !== null && $priorCtr !== null && $priorCtr > 0)
            ? round(($priorCtr - $ctr) / $priorCtr, 4)
            : null;
        $tooEarlySpend = (float) config('campaign-decisions.defaults.ad_too_early_spend', 20);
        $tooEarlyImpressions = (int) config('campaign-decisions.defaults.ad_too_early_impressions', 1000);
        $fatigueFrequency = $audience === 'retargeting'
            ? (float) config('campaign-decisions.defaults.ad_fatigue_frequency_retargeting', 3)
            : (float) config('campaign-decisions.defaults.ad_fatigue_frequency_prospecting', 2);
        $fatigueDrop = (float) config('campaign-decisions.defaults.ad_fatigue_ctr_drop', 0.30);
        $copy = self::copyFingerprint($ad);
        $live = self::isLive($ad);
        $spendThirty = (float) ($thirty['spend'] ?? 0);
        $impressionsThirty = (int) ($thirty['impressions'] ?? 0);
        $thinSeven = $spend < $tooEarlySpend || $impressions < $tooEarlyImpressions;
        $matureThirty = $spendThirty >= $tooEarlySpend && $impressionsThirty >= $tooEarlyImpressions;
        if ($live && $thinSeven && $matureThirty) {
            $spend = $spendThirty;
            $impressions = $impressionsThirty;
            $linkClicks = isset($thirty['link_clicks']) && is_numeric($thirty['link_clicks'])
                ? (int) $thirty['link_clicks']
                : $linkClicks;
            $clicks = $linkClicks ?? (int) ($thirty['clicks'] ?? $clicks);
            $ctr = self::ctrPercent($thirty['ctr'] ?? $ctr, $impressions, $clicks);
            $cpc = isset($thirty['cpc']) && is_numeric($thirty['cpc'])
                ? round((float) $thirty['cpc'], 2)
                : ($clicks > 0 && $spend > 0 ? round($spend / $clicks, 2) : $cpc);
            $lpv = isset($thirty['landing_page_views']) && is_numeric($thirty['landing_page_views'])
                ? (int) $thirty['landing_page_views']
                : $lpv;
            $costPerLpv = ($lpv !== null && $lpv > 0 && $spend > 0) ? round($spend / $lpv, 2) : null;
            $frequency = isset($thirty['frequency']) && is_numeric($thirty['frequency'])
                ? (float) $thirty['frequency']
                : $frequency;
        }
        $dead = $live && $campaignSpend > 0 && $spend <= 0 && $impressions <= 0;
        $tooEarly = $live && ! $dead && ($spend < $tooEarlySpend || $impressions < $tooEarlyImpressions);
        $fatigued = $live && ! $dead && ! $tooEarly
            && $frequency !== null
            && $frequency >= $fatigueFrequency
            && $ctrDrop !== null
            && $ctrDrop >= $fatigueDrop;
        $label = match (true) {
            ! $live => 'paused',
            $dead => 'dead',
            $tooEarly => 'too_early',
            $fatigued => 'fatigued',
            default => 'watch',
        };

        return [
            'ad_id' => trim((string) ($ad['ad_id'] ?? '')),
            'creative_id' => trim((string) ($ad['creative_id'] ?? '')),
            'name' => trim((string) ($ad['name'] ?? '')),
            'headline' => trim((string) ($ad['headline'] ?? '')),
            'cta' => trim((string) ($ad['cta'] ?? '')),
            'cta_mismatch' => $audience === 'retargeting' && self::isVagueCta($ad),
            'copy_fingerprint' => $copy,
            'spend' => round($spend, 2),
            'impressions' => $impressions,
            'clicks' => $clicks,
            'ctr_percent' => $ctr,
            'prior_ctr_percent' => $priorCtr,
            'ctr_drop' => $ctrDrop,
            'cpc' => $cpc,
            'landing_page_views' => $lpv,
            'cost_per_lpv' => $costPerLpv,
            'frequency' => $frequency !== null ? round($frequency, 2) : null,
            'quality_ranking' => self::qualityRankingValue($ad),
            'engagement_rate_ranking' => self::stringOrNull($ad['engagement_rate_ranking'] ?? $seven['engagement_rate_ranking'] ?? null),
            'conversion_rate_ranking' => self::stringOrNull($ad['conversion_rate_ranking'] ?? $seven['conversion_rate_ranking'] ?? null),
            'quality_pause' => false,
            'duplicate_copy' => false,
            'status' => strtoupper(trim((string) ($ad['status'] ?? ''))),
            'format' => self::creativeFormat($ad),
            'label' => $label,
            'llm_action' => in_array($label, ['fatigued'], true) ? 'change' : 'keep',
        ];
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    public static function isLive(array $ad): bool
    {
        $status = strtoupper(trim((string) ($ad['status'] ?? '')));

        return $status === '' || in_array($status, ['ACTIVE', 'CAMPAIGN_ACTIVE'], true);
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    private static function creativeFormat(array $ad): string
    {
        $type = strtolower(trim((string) ($ad['type'] ?? $ad['creative_type'] ?? '')));

        if ($type === 'video' || str_contains($type, 'video')) {
            return 'video';
        }

        foreach (is_array($ad['images'] ?? null) ? $ad['images'] : [] as $image) {
            if (is_array($image) && strtolower((string) ($image['kind'] ?? '')) === 'video') {
                return 'video';
            }
        }

        if ($type === 'image' || (is_array($ad['images'] ?? null) && $ad['images'] !== [])) {
            return 'image';
        }

        return $type !== '' ? $type : '';
    }

    /**
     * @param  list<array<string, mixed>>  $drafts
     * @return list<array<string, mixed>>
     */
    private static function assignRelativeLabels(array $drafts): array
    {
        $fingerprints = [];

        foreach ($drafts as $row) {
            if (! self::isLive($row)) {
                continue;
            }

            $print = (string) ($row['copy_fingerprint'] ?? '');
            if ($print === '') {
                continue;
            }
            $fingerprints[$print] = ($fingerprints[$print] ?? 0) + 1;
        }

        foreach ($drafts as $index => $row) {
            $print = (string) ($row['copy_fingerprint'] ?? '');
            $drafts[$index]['duplicate_copy'] = $print !== '' && ($fingerprints[$print] ?? 0) > 1;
        }

        $judgedIndexes = [];

        foreach ($drafts as $index => $row) {
            if (in_array($row['label'], ['watch'], true) && self::isLive($row)) {
                $judgedIndexes[] = $index;
            }
        }

        if ($judgedIndexes !== []) {
            $bestIndex = $judgedIndexes[0];
            $worstIndex = $judgedIndexes[0];

            foreach ($judgedIndexes as $index) {
                if (self::betterThan($drafts[$index], $drafts[$bestIndex])) {
                    $bestIndex = $index;
                }
                if (self::worseThan($drafts[$index], $drafts[$worstIndex])) {
                    $worstIndex = $index;
                }
            }

            $drafts[$bestIndex]['label'] = 'winner';
            $drafts[$bestIndex]['llm_action'] = 'keep';

            if (count($judgedIndexes) >= 2 && $worstIndex !== $bestIndex) {
                $drafts[$worstIndex]['label'] = 'pause';
                $drafts[$worstIndex]['llm_action'] = 'keep';
            }
        }

        foreach ($drafts as $index => $row) {
            if ($row['label'] === 'dead' && $row['duplicate_copy'] === true) {
                $drafts[$index]['llm_action'] = 'keep';
            }

            if (self::isBelowAverageQuality($row) && ! in_array($row['label'], ['too_early', 'dead'], true)) {
                $drafts[$index]['label'] = 'pause';
                $drafts[$index]['llm_action'] = 'keep';
                $drafts[$index]['quality_pause'] = true;
            }
        }

        return $drafts;
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    private static function rankingText(array $ad): string
    {
        $value = self::qualityRankingValue($ad);

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

        return str_replace('_', ' ', strtolower($value));
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    private static function qualityRankingValue(array $ad): ?string
    {
        return self::stringOrNull($ad['quality_ranking'] ?? data_get($ad, 'last_7_days.quality_ranking'));
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    private static function isBelowAverageQuality(array $ad): bool
    {
        $value = strtolower((string) ($ad['quality_ranking'] ?? ''));

        return $value !== '' && str_contains($value, 'below');
    }

    private static function stringOrNull(mixed $value): ?string
    {
        if (! is_string($value)) {
            return null;
        }

        $trimmed = trim($value);

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

    /**
     * @param  array<string, mixed>  $left
     * @param  array<string, mixed>  $right
     */
    private static function betterThan(array $left, array $right): bool
    {
        $leftCost = $left['cost_per_lpv'] ?? $left['cpc'];
        $rightCost = $right['cost_per_lpv'] ?? $right['cpc'];

        if (is_numeric($leftCost) && is_numeric($rightCost) && (float) $leftCost !== (float) $rightCost) {
            return (float) $leftCost < (float) $rightCost;
        }

        return (float) ($left['ctr_percent'] ?? 0) > (float) ($right['ctr_percent'] ?? 0);
    }

    /**
     * @param  array<string, mixed>  $left
     * @param  array<string, mixed>  $right
     */
    private static function worseThan(array $left, array $right): bool
    {
        return self::betterThan($right, $left);
    }

    /**
     * @param  array<string, mixed>  $ad
     */
    private static function copyFingerprint(array $ad): string
    {
        $text = strtolower(trim(preg_replace('/\s+/', ' ', implode(' ', array_filter([
            (string) ($ad['headline'] ?? ''),
            (string) ($ad['primary_text'] ?? ''),
        ]))) ?? ''));

        return $text;
    }

    private static function ctrPercent(mixed $ctr, int $impressions, int $clicks): ?float
    {
        if (is_numeric($ctr)) {
            $value = (float) $ctr;

            return $value > 1 ? round($value, 2) : round($value * 100, 2);
        }

        if ($impressions > 0 && $clicks > 0) {
            return round(($clicks / $impressions) * 100, 2);
        }

        return null;
    }
}
