<?php

namespace App\Library\CampaignDecision;

/**
 * Facebook vs Instagram cost per optimization result, rolled up from placement rows.
 */
class PlacementPublisherCosts
{
    private const MIN_SPEND = 1.0;

    private const MIN_RESULTS = 5.0;

    private const MIN_SAVINGS = 0.05;

    private const MIN_RATIO = 1.15;

    /**
     * @param  array<string, mixed>  $snapshot
     * @return array{
     *     publishers: list<array{publisher: string, label: string, spend: float, results: float, clicks: int, cost_per_result: ?float}>,
     *     gap: ?array{cheaper_label: string, expensive_label: string, cheaper_cpr: float, expensive_cpr: float, savings: float, metric: string},
     *     results_on_file: bool,
     *     metric: string
     * }
     */
    public static function fromSnapshot(array $snapshot, string $kind): array
    {
        $traffic = in_array($kind, ['traffic', 'awareness'], true);
        $metric = $traffic ? 'landing page view' : 'result';
        $publishers = [];

        foreach (self::adSets($snapshot) as $adSet) {
            foreach (self::fromAdSet($adSet, $traffic)['publishers'] as $row) {
                $key = $row['publisher'];
                $current = $publishers[$key] ?? [
                    'publisher' => $key,
                    'label' => $row['label'],
                    'spend' => 0.0,
                    'results' => 0.0,
                    'clicks' => 0,
                    'cost_per_result' => null,
                ];
                $current['spend'] = round($current['spend'] + $row['spend'], 2);
                $current['results'] += $row['results'];
                $current['clicks'] += $row['clicks'];
                $current['cost_per_result'] = $current['results'] > 0
                    ? round($current['spend'] / $current['results'], 2)
                    : null;
                $publishers[$key] = $current;
            }
        }

        $rows = array_values($publishers);
        usort($rows, fn (array $left, array $right): int => $right['spend'] <=> $left['spend']);

        $adSetResults = self::adSetResultTotal($snapshot, $traffic);
        $placementResults = array_sum(array_column($rows, 'results'));
        $resultsOnFile = $placementResults > 0;
        if ($adSetResults > 0 && $placementResults <= 0) {
            $resultsOnFile = false;
        }

        return [
            'publishers' => $rows,
            'gap' => $resultsOnFile ? self::gap($rows, $metric) : null,
            'results_on_file' => $resultsOnFile,
            'metric' => $metric,
        ];
    }

    /**
     * @param  array<string, mixed>  $adSet
     * @return array{publishers: list<array{publisher: string, label: string, spend: float, results: float, clicks: int, cost_per_result: ?float}>}
     */
    public static function fromAdSet(array $adSet, bool $trafficGoal): array
    {
        $totals = [];
        $platforms = data_get($adSet, 'breakdowns.publisher_platforms');
        $rows = is_array($platforms) && $platforms !== []
            ? $platforms
            : data_get($adSet, 'breakdowns.placements');

        if (! is_array($rows)) {
            return ['publishers' => []];
        }

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

            $publisher = self::publisher($row);

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

            $spend = is_numeric($row['spend'] ?? null) ? (float) $row['spend'] : 0.0;
            $clicks = is_numeric($row['clicks'] ?? null)
                ? (int) $row['clicks']
                : (is_numeric($row['link_clicks'] ?? null) ? (int) $row['link_clicks'] : 0);
            $results = self::results($row, $trafficGoal);
            $current = $totals[$publisher] ?? [
                'publisher' => $publisher,
                'label' => self::label($publisher),
                'spend' => 0.0,
                'results' => 0.0,
                'clicks' => 0,
                'cost_per_result' => null,
            ];
            $current['spend'] = round($current['spend'] + $spend, 2);
            $current['results'] += $results;
            $current['clicks'] += $clicks;
            $stated = is_numeric($row['cost_per_result'] ?? null) ? round((float) $row['cost_per_result'], 2) : null;
            $current['cost_per_result'] = $stated
                ?? ($current['results'] > 0 ? round($current['spend'] / $current['results'], 2) : null);
            $totals[$publisher] = $current;
        }

        return ['publishers' => array_values($totals)];
    }

    /**
     * @param  array{
     *     publishers: list<array{publisher: string, label: string, spend: float, results: float, clicks: int, cost_per_result: ?float}>,
     *     gap: ?array{cheaper_label: string, expensive_label: string, cheaper_cpr: float, expensive_cpr: float, savings: float, metric: string},
     *     results_on_file: bool,
     *     metric: string
     * }  $costs
     */
    public static function mustSay(array $costs): ?string
    {
        $gap = $costs['gap'] ?? null;

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

        return $gap['cheaper_label'].' cost per '.$gap['metric'].' is $'.number_format((float) $gap['cheaper_cpr'], 2)
            .' and '.$gap['expensive_label'].' is $'.number_format((float) $gap['expensive_cpr'], 2)
            .'. Shift spend toward '.$gap['cheaper_label'].' (about $'.number_format((float) $gap['savings'], 2)
            .' cheaper per '.$gap['metric'].'). Do not keep Advantage+ placements unchanged.';
    }

    /**
     * @param  list<array{publisher: string, label: string, spend: float, results: float, clicks: int, cost_per_result: ?float}>  $rows
     * @return array{cheaper_label: string, expensive_label: string, cheaper_cpr: float, expensive_cpr: float, savings: float, metric: string}|null
     */
    private static function gap(array $rows, string $metric): ?array
    {
        $ranked = [];

        foreach ($rows as $row) {
            $cpr = $row['cost_per_result'];

            if ($cpr === null || $row['spend'] < self::MIN_SPEND || $row['results'] < self::MIN_RESULTS) {
                continue;
            }

            $ranked[] = $row;
        }

        if (count($ranked) < 2) {
            return null;
        }

        usort($ranked, fn (array $left, array $right): int => ($left['cost_per_result'] ?? 0) <=> ($right['cost_per_result'] ?? 0));
        $cheaper = $ranked[0];
        $expensive = $ranked[count($ranked) - 1];
        $cheapCpr = (float) $cheaper['cost_per_result'];
        $dearCpr = (float) $expensive['cost_per_result'];
        $savings = round($dearCpr - $cheapCpr, 2);

        if ($savings < self::MIN_SAVINGS || $cheapCpr <= 0 || ($dearCpr / $cheapCpr) < self::MIN_RATIO) {
            return null;
        }

        return [
            'cheaper_label' => $cheaper['label'],
            'expensive_label' => $expensive['label'],
            'cheaper_cpr' => $cheapCpr,
            'expensive_cpr' => $dearCpr,
            'savings' => $savings,
            'metric' => $metric,
        ];
    }

    /**
     * @param  array<string, mixed>  $row
     */
    private static function results(array $row, bool $trafficGoal): float
    {
        $lpv = is_numeric($row['landing_page_views'] ?? null) ? (float) $row['landing_page_views'] : null;
        $conversions = is_numeric($row['conversions'] ?? null) ? (float) $row['conversions'] : null;

        if ($trafficGoal) {
            if ($lpv !== null && $lpv > 0) {
                return $lpv;
            }

            if ($conversions !== null && $conversions > 0) {
                return $conversions;
            }

            return 0.0;
        }

        return (float) ($conversions ?? 0);
    }

    /**
     * @param  array<string, mixed>  $row
     */
    private static function publisher(array $row): ?string
    {
        $raw = strtolower(trim((string) ($row['publisher'] ?? '')));

        if (in_array($raw, ['facebook', 'instagram', 'audience_network', 'messenger', 'threads'], true)) {
            return $raw;
        }

        $label = strtolower(trim((string) ($row['label'] ?? $row['placement'] ?? '')));

        return match (true) {
            str_contains($label, 'instagram') => 'instagram',
            str_contains($label, 'facebook') => 'facebook',
            str_contains($label, 'audience network') => 'audience_network',
            str_contains($label, 'messenger') => 'messenger',
            str_contains($label, 'threads') => 'threads',
            default => null,
        };
    }

    private static function label(string $publisher): string
    {
        return match ($publisher) {
            'facebook' => 'Facebook',
            'instagram' => 'Instagram',
            'audience_network' => 'Audience Network',
            'messenger' => 'Messenger',
            'threads' => 'Threads',
            default => ucfirst($publisher),
        };
    }

    /**
     * @param  array<string, mixed>  $snapshot
     * @return list<array<string, mixed>>
     */
    private static function adSets(array $snapshot): array
    {
        $sets = data_get($snapshot, 'ad_set_optimization.ad_sets');

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

        return array_values(array_filter($sets, fn (mixed $set): bool => is_array($set)));
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private static function adSetResultTotal(array $snapshot, bool $traffic): float
    {
        $total = 0.0;

        foreach (self::adSets($snapshot) as $adSet) {
            $delivery = is_array($adSet['delivery'] ?? null) ? $adSet['delivery'] : [];
            $total += $traffic
                ? (float) ($delivery['landing_page_views'] ?? $delivery['outbound_clicks'] ?? 0)
                : (float) ($delivery['conversions'] ?? 0);
        }

        if ($total > 0) {
            return $total;
        }

        $window = is_array(data_get($snapshot, 'windows.7d')) ? data_get($snapshot, 'windows.7d') : [];

        return $traffic
            ? (float) ($window['landing_page_views'] ?? $window['outbound_clicks'] ?? 0)
            : (float) ($window['conversions'] ?? 0);
    }
}
