<?php

namespace App\Campaigns;

use App\Library\CampaignDecision\CampaignBudgetRecommendation;
use App\Library\CampaignDecision\CampaignDecisionVerdict;
use App\Library\CampaignDecision\CampaignMarketingDiagnosis;
use App\Library\CampaignDecision\CampaignPerformanceBrief;
use App\Library\CampaignDecision\CampaignPerformanceStrategy;
use App\Models\Campaign;
use App\Models\CampaignDecision;
use App\Models\CampaignPerformanceSuggestion;
use App\Models\CampaignPerformanceVerdictLog;
use App\Models\GoogleAdsCampaign;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;

class PerformanceBoard
{
    public function __construct(
        private readonly WhaleAdopsReader $adops,
        private readonly RoiDashboardReader $roi,
        private readonly AdSetOptimizationAssembler $adSetOptimization,
    ) {}

    /**
     * @param  array{q?: string, platform?: string, status?: string, per_page?: int}  $filters
     * @return array{
     *     rows: LengthAwarePaginator,
     *     stats: array<string, int>,
     *     totals: array<string, float|int|null>
     * }
     */
    public function forUser(User $user, array $filters): array
    {
        $q = trim((string) ($filters['q'] ?? ''));
        $platform = strtolower(trim((string) ($filters['platform'] ?? '')));
        $configuredPlatforms = array_map(strtolower(...), (array) config('campaign-performance.adops_platforms', ['meta', 'google', 'linkedin']));
        $scopedPlatform = in_array($platform, $configuredPlatforms, true) ? $platform : null;

        $rows = $this->rowsFor($user, $scopedPlatform)
            ->filter(fn (array $row): bool => CampaignPerformanceStrategy::appearsOnListing($row))
            ->values();

        if ($scopedPlatform !== null) {
            $rows = $rows->where('platform', $scopedPlatform)->values();
        }

        $effectiveVerdict = fn (array $row): ?CampaignDecisionVerdict => CampaignDecisionVerdict::tryFromStored($row['ai_status'] ?? null)
            ?? CampaignDecisionVerdict::tryFromStored($row['verdict'] ?? null)
            ?? CampaignDecisionVerdict::tryFromStored($row['status'] ?? null);

        $stats = [
            'all' => $rows->count(),
            'none' => $rows->filter(fn (array $row): bool => $effectiveVerdict($row) === null)->count(),
        ];

        foreach (CampaignDecisionVerdict::cases() as $verdict) {
            $stats[$verdict->value] = $rows->filter(
                fn (array $row): bool => $effectiveVerdict($row) === $verdict
            )->count();
        }

        foreach (PerformanceVerdict::cases() as $verdict) {
            if (! array_key_exists($verdict->value, $stats)) {
                $target = CampaignDecisionVerdict::tryFromStored($verdict->value);
                $stats[$verdict->value] = $target !== null ? ($stats[$target->value] ?? 0) : 0;
            }
        }

        $totals = [
            'spend_7d' => round((float) $rows->sum('spend_7d'), 2),
            'clicks_7d' => (int) $rows->sum('clicks_7d'),
            'impressions_7d' => (int) $rows->sum('impressions_7d'),
        ];
        $totals['cpc_7d'] = $totals['clicks_7d'] > 0
            ? round($totals['spend_7d'] / $totals['clicks_7d'], 4)
            : null;
        $totals['ctr_7d'] = $totals['impressions_7d'] > 0
            ? round($totals['clicks_7d'] / $totals['impressions_7d'], 4)
            : null;

        $status = strtolower(trim((string) ($filters['status'] ?? '')));

        if ($q !== '') {
            $rows = $rows->filter(fn (array $row): bool => $this->matchesCampaignQuery($row, $q));
        }

        if ($status === 'none') {
            $rows = $rows->filter(fn (array $row): bool => $effectiveVerdict($row) === null);
        } elseif ($status !== '' && $status !== 'all') {
            $targetVerdict = CampaignDecisionVerdict::tryFromStored($status);
            if ($targetVerdict !== null) {
                $rows = $rows->filter(fn (array $row): bool => $effectiveVerdict($row) === $targetVerdict);
            } else {
                $rows = $rows->filter(fn (array $row): bool => ($row['status'] ?? null) === $status || ($row['verdict'] ?? null) === $status);
            }
        }

        $perPage = in_array((int) ($filters['per_page'] ?? 10), [10, 25, 50], true)
            ? (int) ($filters['per_page'] ?? 10)
            : 10;
        $page = max(1, (int) request()->query('page', 1));
        $rows = $rows->values();

        $paginator = new Paginator(
            $rows->forPage($page, $perPage)->map(
                fn (array $row): array => $this->attachAdSetOptimization($row),
            )->values(),
            $rows->count(),
            $perPage,
            $page,
            ['path' => request()->url(), 'query' => request()->query()],
        );

        return [
            'rows' => $paginator,
            'stats' => $stats,
            'totals' => $totals,
        ];
    }

    /**
     * Latest cron decision per campaign on a calendar day.
     * The monitor stores every pass under one user, so this list is shared.
     *
     * @return LengthAwarePaginator<int, array<string, mixed>>
     */
    public function decisionsOnDate(Carbon $date, int $perPage = 10, string $query = '', string $platform = '', string $status = ''): LengthAwarePaginator
    {
        $platform = strtolower(trim($platform));
        $status = strtolower(trim($status));
        $targetVerdict = $status !== '' && $status !== 'all' && $status !== 'none'
            ? CampaignDecisionVerdict::tryFromStored($status)
            : null;

        $configuredPlatforms = array_map(strtolower(...), (array) config('campaign-performance.adops_platforms', ['meta', 'google', 'linkedin']));
        $rows = CampaignDecision::query()
            ->whereDate('evaluated_at', $date->toDateString())
            ->when(
                in_array($platform, $configuredPlatforms, true),
                fn ($q) => $q->where('platform', $platform),
            )
            ->when(
                $status === 'none',
                fn ($q) => $q->where(fn ($sub) => $sub->whereNull('verdict')->orWhere('verdict', '')),
            )
            ->when(
                $targetVerdict !== null,
                fn ($q) => $q->where('verdict', $targetVerdict->value),
            )
            ->when(
                $targetVerdict === null && $status !== '' && $status !== 'all' && $status !== 'none',
                fn ($q) => $q->where('verdict', $status),
            )
            ->orderByDesc('evaluated_at')
            ->orderByDesc('id')
            ->get();

        $latest = [];

        foreach ($rows as $decision) {
            $key = $decision->platform.'|'.$decision->external_campaign_id;

            if (isset($latest[$key])) {
                continue;
            }

            $latest[$key] = $this->decisionCard($decision);
        }

        $query = trim($query);
        $cards = collect(array_values($latest))
            ->when($query !== '', fn (Collection $rows): Collection => $rows->filter(
                fn (array $row): bool => $this->matchesCampaignQuery($row, $query),
            ))
            ->sort(fn (array $left, array $right): int => $this->compareCampaignRows($left, $right, 'updated_at'))
            ->values();
        $perPage = in_array($perPage, [10, 25, 50], true) ? $perPage : 10;
        $page = max(1, (int) request()->query('decision_page', 1));

        return new Paginator(
            $cards->forPage($page, $perPage)->map(
                fn (array $row): array => $this->attachAdSetOptimization($row),
            )->values(),
            $cards->count(),
            $perPage,
            $page,
            [
                'path' => request()->url(),
                'query' => request()->query(),
                'pageName' => 'decision_page',
            ],
        );
    }

    /**
     * @param  array{
     *     per_page?: int,
     *     log_run_type?: string,
     *     log_verdict?: string,
     *     log_days?: int,
     *     log_per_page?: int
     * }  $filters
     * @return array<string, mixed>|null
     */
    public function detailFor(User $user, string $platform, string $externalId, array $filters = []): ?array
    {
        $platform = strtolower($platform);
        $row = $this->rowsFor($user)->first(
            fn (array $candidate): bool => $candidate['platform'] === $platform
                && $candidate['external_campaign_id'] === $externalId,
        );

        if ($row === null) {
            return null;
        }

        $chartDays = collect();
        $hours = collect();

        if ($this->adops->isAvailable() && in_array($platform, ['meta', 'google', 'linkedin'], true)) {
            $chartDays = $this->adops->dailyStats(
                $platform,
                $externalId,
                now()->subDays(89)->toDateString(),
                now()->toDateString(),
            );
            $oldest = $chartDays->min('stat_date');
            $hourSince = $oldest instanceof Carbon
                ? $oldest->copy()->startOfDay()
                : now()->subDays(7)->startOfHour();
            $hours = $this->adops->hourlyStats($platform, $externalId, $hourSince);
        }

        $perPage = in_array((int) ($filters['per_page'] ?? 10), [10, 25, 50], true)
            ? (int) ($filters['per_page'] ?? 10)
            : 10;
        $page = max(1, (int) request()->query('page', 1));
        $sortedHistory = $chartDays
            ->sortByDesc(fn (PerformanceDay $day): int => $day->stat_date->timestamp)
            ->values();
        $history = new Paginator(
            $sortedHistory->forPage($page, $perPage)->values(),
            $sortedHistory->count(),
            $perPage,
            $page,
            ['path' => request()->url(), 'query' => request()->query()],
        );
        $hourlyByDate = $hours->groupBy(fn (PerformanceHour $hour): string => $hour->stat_hour->toDateString());
        $latestHour = $hours->sortByDesc(fn (PerformanceHour $hour): int => $hour->stat_hour->timestamp)->first();

        $lifetimeSpend = round((float) $chartDays->sum('spend'), 2);
        $lifetimeClicks = (int) $chartDays->sum('clicks');
        $lifetimeImpressions = (int) $chartDays->sum('impressions');

        $suggestion = $this->restrictToUser(CampaignPerformanceSuggestion::query(), $user)
            ->where('platform', $platform)
            ->where('external_campaign_id', $externalId)
            ->first();

        if ($suggestion === null && $this->adops->isAvailable() && in_array($platform, ['meta', 'google', 'linkedin'], true)
            && config('campaign-performance.adops_list_all')) {
            $suggestion = CampaignPerformanceSuggestion::query()
                ->where('platform', $platform)
                ->where('external_campaign_id', $externalId)
                ->first();
        }

        $decisionLogs = $this->decisionLogsFor($user, $platform, $externalId, $filters);
        $verdictLogs = $this->verdictLogsFor($user, $platform, $externalId, $filters);

        $latestVerdict = $this->restrictToUser(CampaignPerformanceVerdictLog::query(), $user)
            ->where('platform', $platform)
            ->where('external_campaign_id', $externalId)
            ->orderByDesc('evaluated_at')
            ->orderByDesc('id')
            ->first();

        $snapshotProfile = data_get($suggestion?->snapshot, 'campaign_profile');
        $whaleProfile = $this->adops->isAvailable()
            ? $this->adops->profileFacts($platform, $externalId)
            : ['objective' => null, 'region_label' => null];
        $liveProfile = array_filter([
            'name' => $row['name'],
            'objective' => $whaleProfile['objective'],
            'platform_status' => $row['platform_status'],
            'delivery_status' => $row['delivery_status'],
            'region_label' => $whaleProfile['region_label'] ?: $row['region_label'],
            'platform_learning_label' => $row['platform_learning_label'],
            'daily_budget' => $row['daily_budget'] ?? data_get($suggestion?->snapshot, 'daily_budget'),
            'account_id' => $row['account_id'] ?? null,
            'started_at' => $row['started_at'] ?? null,
        ], fn (mixed $value): bool => $value !== null && $value !== '');
        $profile = PerformanceProfileView::fromSnapshot(array_merge(
            is_array($snapshotProfile) ? $snapshotProfile : [],
            $liveProfile,
        ));

        $suggestionWindows = $this->resolveSuggestionWindows($suggestion, $chartDays);
        $suggestionHourlyVerdict = data_get($suggestion?->snapshot, 'verdicts.hourly_verdict');
        $suggestionRunType = (string) data_get($suggestion?->snapshot, 'verdicts.run_type', '');
        if ($suggestionRunType === '' && data_get($suggestion?->snapshot, 'decision_engine') === 'v2') {
            $suggestionRunType = (string) data_get($suggestion?->snapshot, 'trigger', 'hourly');
        }

        $affiliate = data_get($suggestion?->snapshot, 'affiliate');
        $affiliate = is_array($affiliate) && ($affiliate['matched'] ?? false) ? $affiliate : null;
        $whale = app(CampaignPerformanceWhaleEnrichment::class);
        if ($affiliate === null && $whale->isEnabled()) {
            $liveAffiliate = data_get($whale->enrichSnapshot([], $externalId), 'affiliate');
            $affiliate = is_array($liveAffiliate) && ($liveAffiliate['matched'] ?? false)
                ? $liveAffiliate
                : null;
        }
        $affiliateDaily = $whale->isEnabled() ? $whale->dailyRows($externalId) : [];
        $affiliateDailyByDate = collect($affiliateDaily)->keyBy('date');
        $roiDetail = $this->roiForDetail($platform, $externalId);
        $outcomeDaily = $whale->isEnabled()
            ? $whale->outcomeDaily($platform, $externalId, 90)
            : [];
        $dailyHistoryByDate = $this->mergeDailyHistory(
            $chartDays,
            $outcomeDaily,
            is_array($roiDetail) && is_array($roiDetail['daily'] ?? null) ? $roiDetail['daily'] : [],
            $affiliateDaily,
        );

        $platformMetrics7d = PerformanceWindowRollup::fromDays('7d', 7, $chartDays);
        $snapshot = is_array($suggestion?->snapshot) ? $suggestion->snapshot : [];
        $row = $this->refreshDecisionFromLiveDays($row, $snapshot, $chartDays);
        $decisionFacts = $this->decisionFacts($snapshot, $chartDays);

        if (is_array($decisionFacts) && is_array($row['marketing_plan'] ?? null) && $row['marketing_plan'] !== []) {
            $row['marketing_plan'][0] = $decisionFacts['lookup_line'];
        }

        $storedCreative = is_array($snapshot['creative_context'] ?? null) ? $snapshot['creative_context'] : [];
        $freshCreative = app(CampaignCreativeContext::class)->forExternal($platform, $externalId);
        if (($freshCreative['found'] ?? false) === true) {
            $snapshot['creative_context'] = app(CampaignLandingPageText::class)->keepStoredPage($freshCreative, $storedCreative);
        }

        $storedLlmActions = data_get($snapshot, 'brief.next_actions_source') === 'llm'
            && is_array(data_get($snapshot, 'brief.next_actions'))
            ? data_get($snapshot, 'brief.next_actions')
            : null;

        if ($chartDays->isNotEmpty()) {
            $windows = is_array($snapshot['windows'] ?? null) ? $snapshot['windows'] : [];

            foreach ([3 => 3, 7 => 7, 14 => 14, 15 => 15, 30 => PerformanceWindows::AI_CONTEXT_DAYS] as $label => $length) {
                $windows[$label.'d'] = PerformanceWindowRollup::fromDays($label.'d', $length, $chartDays);
            }

            $snapshot['windows'] = $windows;
            unset($snapshot['brief'], $row['brief']);
        }

        if ($this->adops->isAvailable()) {
            $snapshot['audience'] = $this->adops->audienceFacts($platform, $externalId);
            unset($snapshot['brief'], $row['brief']);
        }

        $row['snapshot'] = $snapshot;
        $row['objective'] = $profile->objective ?? data_get($snapshot, 'campaign_profile.objective');
        $brief = CampaignPerformanceBrief::forDisplay($row, $snapshot);

        if (is_array($storedLlmActions)) {
            $brief = CampaignPerformanceBrief::applyModelSteps($brief, $storedLlmActions, $snapshot);
        }

        $row['brief'] = $brief;
        $decisionFacts = $this->alignDecisionFactsToWindow($decisionFacts, $suggestionWindows, $snapshot);
        $row['windows'] = $suggestionWindows;
        $row['ad_set_optimization'] = $this->adSetOptimizationFor($platform, $externalId, $row['ad_set_optimization'] ?? null);

        return [
            'row' => $row,
            'history' => $history,
            'hourly_by_date' => $hourlyByDate,
            'chart' => PerformanceChart::fromDays($chartDays),
            'suggestion' => $suggestion,
            'suggestion_windows' => $suggestionWindows,
            'suggestion_hourly_verdict' => is_array($suggestionHourlyVerdict) ? $suggestionHourlyVerdict : null,
            'suggestion_run_type' => $suggestionRunType,
            'latest_hour' => $latestHour,
            'profile' => $profile,
            'decision_logs' => $decisionLogs,
            'verdict_logs' => $verdictLogs,
            'latest_verdict' => $latestVerdict,
            'log_filters' => [
                'run_type' => trim((string) ($filters['log_run_type'] ?? '')),
                'verdict' => trim((string) ($filters['log_verdict'] ?? '')),
                'days' => (int) ($filters['log_days'] ?? 0),
                'per_page' => $verdictLogs->perPage(),
            ],
            'local' => null,
            'lifetime' => [
                'spend' => $lifetimeSpend,
                'clicks' => $lifetimeClicks,
                'impressions' => $lifetimeImpressions,
                'cpc' => $lifetimeClicks > 0 ? round($lifetimeSpend / $lifetimeClicks, 4) : null,
            ],
            'daily_budget' => $profile->daily_budget ?? $row['daily_budget'] ?? data_get($suggestion?->snapshot, 'daily_budget'),
            'local_status' => $profile->platform_status,

            'affiliate' => $affiliate,
            'affiliate_daily' => $affiliateDaily,
            'affiliate_daily_by_date' => $affiliateDailyByDate,
            'daily_history_by_date' => $dailyHistoryByDate,
            'roi' => $roiDetail,
            'platform_metrics_7d' => [
                'spend' => $platformMetrics7d['spend'],
                'clicks' => $platformMetrics7d['clicks'],
                'cpc' => $platformMetrics7d['cpc'],
                'conversions' => $platformMetrics7d['conversions'],
                'conversion_value' => $platformMetrics7d['conversion_value'],
            ],
            'decision_facts' => $decisionFacts,
        ];
    }

    /**
     * Merge Meta daily delivery with internal (ROI + affiliate) outcome rows for the history table.
     *
     * @param  Collection<int, PerformanceDay>  $metaDays
     * @param  list<array<string, float|string>>  $outcomeDaily
     * @param  list<array<string, float|string>>  $roiDaily
     * @param  list<array<string, float|int|string>>  $affiliateDaily
     * @return array<string, array<string, mixed>>
     */
    private function mergeDailyHistory(
        Collection $metaDays,
        array $outcomeDaily,
        array $roiDaily,
        array $affiliateDaily,
    ): array {
        $outcomeByDate = collect($outcomeDaily)->keyBy('date');
        $roiByDate = collect($roiDaily)->keyBy('date');
        $affiliateByDate = collect($affiliateDaily)->keyBy('date');
        $dates = collect()
            ->merge($metaDays->map(fn (PerformanceDay $day): string => $day->stat_date->toDateString()))
            ->merge($outcomeByDate->keys())
            ->merge($roiByDate->keys())
            ->merge($affiliateByDate->keys())
            ->unique()
            ->sort()
            ->values();

        $merged = [];

        foreach ($dates as $date) {
            /** @var PerformanceDay|null $meta */
            $meta = $metaDays->first(
                fn (PerformanceDay $day): bool => $day->stat_date->toDateString() === $date,
            );
            $outcome = $outcomeByDate->get($date);
            $roi = $roiByDate->get($date);
            $affiliate = $affiliateByDate->get($date);

            $spend = $meta !== null ? (float) $meta->spend : (float) ($roi['spent'] ?? $roi['spend'] ?? 0);
            $reach = $meta?->reach;
            $outbound = $meta?->outbound_clicks;
            $linkClicks = $meta?->link_clicks;
            $visitors = ($reach !== null && $reach > 0) ? $reach : null;
            $landingPageViews = ($meta !== null && isset($meta->landing_page_views) && $meta->landing_page_views !== null)
                ? (int) $meta->landing_page_views
                : (($outbound !== null && $linkClicks !== null && $linkClicks > 0 && $outbound < (int) round($linkClicks * 0.9))
                    ? $outbound
                    : null);

            $revenue = (float) ($affiliate['net_revenue'] ?? $outcome['revenue'] ?? $roi['sales'] ?? $roi['revenue'] ?? 0);
            $orders = (float) ($affiliate['orders'] ?? $outcome['orders'] ?? $roi['orders'] ?? 0);
            $conversions = (float) ($roi['conversions'] ?? $outcome['roi_conversions'] ?? $meta?->conversions ?? 0);
            $subscriptions = (float) ($roi['subscriptions'] ?? $outcome['subscriptions'] ?? 0);
            $installs = (float) ($roi['installs'] ?? $outcome['installs'] ?? 0);
            $leads = (float) ($roi['leads'] ?? $outcome['leads'] ?? 0);
            $profit = round($revenue - $spend, 2);
            $profitPct = $spend > 0 ? round(($profit / $spend) * 100, 2) : null;

            $merged[$date] = [
                'date' => $date,
                'buying_source' => 'Meta',
                'internal_source' => 'Internal',
                'spend' => round($spend, 2),
                'impressions' => $meta?->impressions,
                'clicks' => $meta?->clicks,
                'cpc' => $meta?->cpc,
                'ctr' => $meta?->ctr,
                'reach' => $reach,
                'link_clicks' => $linkClicks,
                'outbound_clicks' => $outbound,
                'platform_conversions' => $meta?->conversions,
                'platform_conversion_value' => $meta?->conversion_value,
                'visitors' => $visitors,
                'landing_page_views' => $landingPageViews,
                'conversions' => $conversions,
                'subscriptions' => $subscriptions,
                'installs' => $installs,
                'leads' => $leads,
                'orders' => $orders,
                'revenue' => round($revenue, 2),
                'profit' => $profit,
                'profit_pct' => $profitPct,
                'has_meta' => $meta !== null,
                'has_internal' => $affiliate !== null || $roi !== null || $outcome !== null,
            ];
        }

        return $merged;
    }

    /**
     * @param  array<string, mixed>  $row
     * @return array<string, mixed>
     */
    private function attachAdSetOptimization(array $row): array
    {
        $platform = strtolower(trim((string) ($row['platform'] ?? '')));
        $campaignId = trim((string) ($row['external_campaign_id'] ?? ''));

        if ($platform === '' || $campaignId === '') {
            return $row;
        }

        $row['ad_set_optimization'] = $this->adSetOptimizationFor($platform, $campaignId, $row['ad_set_optimization'] ?? null);

        return $row;
    }

    /**
     * Stored ad set diagnosis when the snapshot already has it. Otherwise the last 30 days from Whale.
     *
     * @return array<string, mixed>
     */
    private function adSetOptimizationFor(string $platform, string $campaignId, mixed $stored): array
    {
        if (is_array($stored) && is_array($stored['ad_sets'] ?? null) && $stored['ad_sets'] !== []) {
            return $stored;
        }

        return $this->adSetOptimization->forCampaign(
            $platform,
            $campaignId,
            now()->subDays(29)->toDateString(),
            now()->toDateString(),
        );
    }

    /**
     * ROI dashboard rows for this campaign id. Null when the table has no rows.
     * Kept off the verdict and the delivery chart.
     *
     * @return array{
     *     totals: array<string, float>,
     *     daily: list<array<string, float|string>>,
     *     from: string,
     *     to: string,
     *     range_min: string,
     *     range_max: string
     * }|null
     */
    private function roiForDetail(string $platform, string $campaignId): ?array
    {
        $campaignId = trim($campaignId);

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

        try {
            if (! Schema::connection('whale')->hasTable('roi_dashboard_campaign_stats')) {
                return null;
            }

            $to = now()->toDateString();
            $from = now()->subDays(89)->toDateString();

            $rows = $this->roiDetailRows($campaignId, strtolower(trim($platform)), $from, $to);

            if ($rows->isEmpty()) {
                $rows = $this->roiDetailRows($campaignId, null, $from, $to);
            }
        } catch (Throwable) {
            return null;
        }

        if ($rows->isEmpty()) {
            return null;
        }

        $byDate = [];

        foreach ($rows as $row) {
            $date = Carbon::parse($row->date)->toDateString();
            $current = $byDate[$date] ?? $this->emptyRoiDay($date);
            $current['spent'] = round($current['spent'] + (float) $row->spent, 4);
            $current['conversions'] = round($current['conversions'] + (float) $row->conversions, 4);
            $current['subscriptions'] = round($current['subscriptions'] + (float) $row->subscriptions, 4);
            $current['cancellations'] = round($current['cancellations'] + (float) $row->cancellations, 4);
            $current['installs'] = round($current['installs'] + (float) $row->installs, 4);
            $current['bookings'] = round($current['bookings'] + (float) $row->bookings, 4);
            $current['leads'] = round($current['leads'] + (float) $row->leads, 4);
            $current['estimated_revenue'] = round($current['estimated_revenue'] + (float) $row->estimated_revenue, 4);
            $current['orders'] = round($current['orders'] + (float) $row->arb_orders, 4);
            $current['sales'] = round($current['sales'] + (float) $row->arb_sales_amount, 4);
            $byDate[$date] = $current;
        }

        ksort($byDate);
        $daily = array_values($byDate);
        $windowFrom = now()->subDays(6)->toDateString();

        return [
            'daily' => $daily,
            'totals' => $this->roiTotalsBetween($daily, $windowFrom, $to),
            'from' => $windowFrom,
            'to' => $to,
            'range_min' => $from,
            'range_max' => $to,
        ];
    }

    /**
     * @return array<string, float|string>
     */
    private function emptyRoiDay(string $date): array
    {
        return [
            'date' => $date,
            'spent' => 0.0,
            'conversions' => 0.0,
            'subscriptions' => 0.0,
            'cancellations' => 0.0,
            'installs' => 0.0,
            'bookings' => 0.0,
            'leads' => 0.0,
            'estimated_revenue' => 0.0,
            'orders' => 0.0,
            'sales' => 0.0,
        ];
    }

    /**
     * @param  list<array<string, float|string>>  $daily
     * @return array<string, float>
     */
    private function roiTotalsBetween(array $daily, string $from, string $to): array
    {
        $totals = $this->emptyRoiDay($from);
        unset($totals['date']);

        foreach ($daily as $day) {
            if ($day['date'] < $from || $day['date'] > $to) {
                continue;
            }

            foreach (array_keys($totals) as $key) {
                $totals[$key] = round($totals[$key] + (float) $day[$key], 4);
            }
        }

        return $totals;
    }

    /**
     * @return Collection<int, object>
     */
    private function roiDetailRows(string $campaignId, ?string $platform, string $from, string $to): Collection
    {
        $query = DB::connection('whale')
            ->table('roi_dashboard_campaign_stats')
            ->where('campaign_id', $campaignId)
            ->whereBetween('date', [$from, $to])
            ->orderBy('date');

        if ($platform !== null && $platform !== '') {
            $query->whereRaw('LOWER(platform) = ?', [$platform]);
        }

        return $query->get([
            'date',
            'spent',
            'conversions',
            'subscriptions',
            'cancellations',
            'installs',
            'bookings',
            'leads',
            'estimated_revenue',
            'arb_orders',
            'arb_sales_amount',
        ]);
    }

    /**
     * Replace a saved suggestion when the live 7-day delivery no longer matches it.
     *
     * @param  array<string, mixed>  $row
     * @param  array<string, mixed>  $snapshot
     * @param  Collection<int, PerformanceDay>  $chartDays
     * @return array<string, mixed>
     */
    private function refreshDecisionFromLiveDays(array $row, array $snapshot, Collection $chartDays): array
    {
        if ($chartDays->isEmpty()) {
            return $row;
        }

        $live7 = PerformanceWindowRollup::fromDays('7d', 7, $chartDays);
        $storedClicks = data_get($snapshot, 'windows.7d.clicks', data_get($snapshot, 'last_7_days.clicks'));
        $storedImpressions = data_get($snapshot, 'windows.7d.impressions', data_get($snapshot, 'last_7_days.impressions'));
        $storedSpend = data_get($snapshot, 'windows.7d.spend', data_get($snapshot, 'last_7_days.spend'));
        $hasStored = is_numeric($storedClicks) || is_numeric($storedImpressions) || is_numeric($storedSpend);
        $unchanged = $hasStored
            && (int) $storedClicks === (int) $live7['clicks']
            && (int) $storedImpressions === (int) $live7['impressions']
            && abs((float) $storedSpend - (float) $live7['spend']) < 0.01;

        $age = $this->campaignAgeDays(
            is_string($row['started_at'] ?? null) ? $row['started_at'] : null,
            $chartDays,
            (int) data_get($snapshot, 'days_live', 0),
        );
        $row['learning'] = $this->learningLabel(
            $age,
            (int) config('campaign-performance.learning_window_days', 3),
            (float) $live7['spend'],
            (float) config('campaign-performance.max_test_spend', 40),
        );

        if ($unchanged) {
            return $row;
        }

        $diagnosisSnapshot = $snapshot;
        $diagnosisSnapshot['windows'] = is_array($diagnosisSnapshot['windows'] ?? null) ? $diagnosisSnapshot['windows'] : [];
        $diagnosisSnapshot['windows']['7d'] = $live7;
        $diagnosisSnapshot['windows']['15d'] = PerformanceWindowRollup::fromDays('15d', 15, $chartDays);
        $diagnosisSnapshot['windows']['30d'] = PerformanceWindowRollup::fromDays('30d', PerformanceWindows::AI_CONTEXT_DAYS, $chartDays);
        $diagnosisSnapshot['daily_history'] = PerformanceDailyHistory::fromDays($chartDays);
        $diagnosis = app(CampaignMarketingDiagnosis::class)->fromSnapshot($diagnosisSnapshot);
        $row['marketing_plan'] = $diagnosis['plan'];
        $row['marketing_lever'] = $diagnosis['primary_lever'];
        $row['marketing_summary'] = $diagnosis['summary'];

        return $row;
    }

    /**
     * Totals and the sentence for the window the detail page should show next to the decision.
     *
     * @param  array<string, mixed>  $snapshot
     * @param  Collection<int, PerformanceDay>  $chartDays
     * @return array<string, mixed>|null
     */
    private function decisionFacts(array $snapshot, Collection $chartDays): ?array
    {
        $stored = data_get($snapshot, 'daily_history');
        $storedRows = is_array($stored) && is_array($stored['rows'] ?? null) ? $stored['rows'] : [];
        $useStored = is_array($stored) && (int) ($stored['days_on_file'] ?? 0) > 0 && $storedRows !== [];

        if ($useStored) {
            $history = $stored;
            $metrics = $this->metricsFromHistoryRows($storedRows);
        } else {
            $rollup = PerformanceWindowRollup::fromDays('30d', PerformanceWindows::AI_CONTEXT_DAYS, $chartDays);

            if ((int) $rollup['buckets'] < 1 || ! is_string($rollup['from']) || $rollup['from'] === '') {
                return null;
            }

            $history = [
                'from' => Carbon::parse($rollup['from'])->toDateString(),
                'to' => Carbon::parse((string) $rollup['to'])->toDateString(),
                'expected_days' => PerformanceWindows::AI_CONTEXT_DAYS,
                'days_on_file' => (int) $rollup['buckets'],
            ];
            $metrics = [
                'spend' => $rollup['spend'],
                'clicks' => $rollup['clicks'],
                'cpc' => $rollup['cpc'],
                'conversions' => $rollup['conversions'],
                'conversion_value' => $rollup['conversion_value'],
                'orders' => null,
                'revenue' => null,
            ];
        }

        $basis = (string) data_get($snapshot, 'marketing_diagnosis.lookup_basis', '');

        if ($basis === '') {
            $basis = data_get($snapshot, 'marketing_diagnosis.window_used') === '15d' ? '15d' : '7d';
        }

        $line = CampaignMarketingDiagnosis::lookupLine($history, $basis);

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

        $onFile = (int) $history['days_on_file'];
        $expected = (int) $history['expected_days'];

        return array_merge($metrics, [
            'label' => $onFile >= $expected ? 'last '.$expected.' days' : $onFile.' of '.$expected.' days',
            'lookup_line' => $line,
        ]);
    }

    /**
     * @param  list<array<string, mixed>>  $rows
     * @return array{
     *     spend: float,
     *     clicks: int,
     *     cpc: ?float,
     *     conversions: int,
     *     conversion_value: float,
     *     orders: ?float,
     *     revenue: ?float
     * }
     */
    private function metricsFromHistoryRows(array $rows): array
    {
        $spend = 0.0;
        $clicks = 0;
        $conversions = 0;
        $value = 0.0;
        $orders = null;
        $revenue = null;

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

            if (($row['platform_row'] ?? false) === true) {
                $spend += (float) ($row['spend'] ?? 0);
                $clicks += (int) ($row['clicks'] ?? 0);
                $conversions += (int) ($row['conversions'] ?? 0);
                $value += (float) ($row['conversion_value'] ?? 0);
            }

            if (is_numeric($row['orders'] ?? null)) {
                $orders = round(($orders ?? 0) + (float) $row['orders'], 4);
            }

            if (is_numeric($row['revenue'] ?? null)) {
                $revenue = round(($revenue ?? 0) + (float) $row['revenue'], 4);
            }
        }

        return [
            'spend' => round($spend, 2),
            'clicks' => $clicks,
            'cpc' => $clicks > 0 ? round($spend / $clicks, 4) : null,
            'conversions' => $conversions,
            'conversion_value' => round($value, 2),
            'orders' => $orders,
            'revenue' => $revenue,
        ];
    }

    /**
     * @param  Collection<int, PerformanceDay>  $days
     * @return array<string, array<string, mixed>>
     */
    private function resolveSuggestionWindows(?CampaignPerformanceSuggestion $suggestion, Collection $days): array
    {
        $snapshot = is_array($suggestion?->snapshot) ? $suggestion->snapshot : [];

        if (data_get($snapshot, 'decision_engine') === 'v2') {
            $raw = data_get($snapshot, 'windows', []);
            $raw = is_array($raw) ? $raw : [];
            $windows = [];

            foreach (PerformanceWindows::comparisonDayWindowKeys() as $windowKey) {
                if (! isset($raw[$windowKey]) || ! is_array($raw[$windowKey])) {
                    continue;
                }

                $windows[$windowKey] = $this->normalizeSnapshotWindowRow($raw[$windowKey], $windowKey);
            }

            return $this->mergePlatformMetricsIntoWindows($windows, $days);
        }

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

        return $this->mergePlatformMetricsIntoWindows($windows, $days);
    }

    /**
     * @param  array<string, mixed>  $row
     * @return array<string, mixed>
     */
    private function normalizeSnapshotWindowRow(array $row, string $windowKey): array
    {
        $buckets = isset($row['buckets']) ? (int) $row['buckets'] : null;
        $expected = isset($row['expected_buckets']) ? (int) $row['expected_buckets'] : null;

        return array_merge($row, [
            'window' => (string) ($row['window'] ?? $windowKey),
            'verdict' => (string) ($row['verdict'] ?? 'no_action'),
            'reason' => (string) ($row['reason'] ?? $this->windowCoverageReason($buckets, $expected)),
            'impressions' => (int) ($row['impressions'] ?? 0),
            'ctr' => isset($row['ctr']) ? (float) $row['ctr'] : null,
            'conversions' => (int) ($row['conversions'] ?? 0),
            'conversion_value' => (float) ($row['conversion_value'] ?? 0),
            'buckets' => $buckets,
            'expected_buckets' => $expected,
        ]);
    }

    private function windowCoverageReason(?int $buckets, ?int $expected): string
    {
        if ($buckets === null || $expected === null || $expected <= 0) {
            return '—';
        }

        if ($buckets >= $expected) {
            return $expected.' of '.$expected.' days on file.';
        }

        return $buckets.' of '.$expected.' days on file.';
    }

    /**
     * @param  array<string, array<string, mixed>>  $windows
     * @param  Collection<int, PerformanceDay>  $days
     * @return array<string, array<string, mixed>>
     */
    private function mergePlatformMetricsIntoWindows(array $windows, Collection $days): array
    {
        if ($days->isEmpty()) {
            return $windows;
        }

        foreach (['3d' => 3, '7d' => 7, '15d' => 15, '30d' => 30] as $windowKey => $length) {
            $rollup = PerformanceWindowRollup::fromDays($windowKey, $length, $days);
            $stored = is_array($windows[$windowKey] ?? null) ? $windows[$windowKey] : [];
            $windows[$windowKey] = array_merge($stored, [
                'window' => $windowKey,
                'from' => $rollup['from'],
                'to' => $rollup['to'],
                'spend' => $rollup['spend'],
                'impressions' => $rollup['impressions'],
                'clicks' => $rollup['clicks'],
                'cpc' => $rollup['cpc'],
                'ctr' => $rollup['ctr'],
                'conversions' => $rollup['conversions'],
                'conversion_value' => $rollup['conversion_value'],
                'buckets' => $rollup['buckets'],
                'expected_buckets' => $rollup['expected_buckets'],
                'verdict' => (string) ($stored['verdict'] ?? 'no_action'),
                'reason' => (string) ($stored['reason'] ?? $this->windowCoverageReason($rollup['buckets'], $rollup['expected_buckets'])),
            ]);
        }

        return $windows;
    }

    /**
     * @param  array<string, mixed>|null  $facts
     * @param  array<string, array<string, mixed>>  $windows
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>|null
     */
    private function alignDecisionFactsToWindow(?array $facts, array $windows, array $snapshot): ?array
    {
        if ($facts === null || $windows === []) {
            return $facts;
        }

        $basis = (string) data_get($snapshot, 'marketing_diagnosis.lookup_basis', '');

        if ($basis === '') {
            $basis = data_get($snapshot, 'marketing_diagnosis.window_used') === '15d' ? '15d' : '7d';
        }

        $window = $windows[$basis] ?? $windows['7d'] ?? null;

        if (! is_array($window)) {
            return $facts;
        }

        $facts['spend'] = (float) ($window['spend'] ?? 0);
        $facts['clicks'] = (int) ($window['clicks'] ?? 0);
        $facts['cpc'] = $window['cpc'] ?? null;
        $facts['conversions'] = (int) ($window['conversions'] ?? 0);
        $facts['conversion_value'] = (float) ($window['conversion_value'] ?? 0);
        $facts['label'] = match ($basis) {
            '15d' => '15 days',
            '30d' => '30 days',
            '3d' => '3 days',
            default => '7 days',
        };

        return $facts;
    }

    /**
     * @return Collection<int, array<string, mixed>>
     */
    private function rowsFor(User $user, ?string $platform = null): Collection
    {
        $since = now()->subDays(6)->toDateString();
        $identities = $this->identities($user, $platform);
        $platforms = array_map(strtolower(...), (array) config('campaign-performance.adops_platforms', ['meta', 'google', 'linkedin']));
        $platformsToQuery = $platform !== null ? [$platform] : $platforms;
        $whaleTotals = [];
        $widerTotals = [];

        if ($this->adops->isAvailable()) {
            foreach ($platformsToQuery as $platformKey) {
                $whaleTotals[$platformKey] = $this->adops->sevenDayTotals($platformKey, $since);
                $widerTotals[$platformKey] = $this->adops->sevenDayTotals($platformKey, now()->subDays(89)->toDateString());
            }
        }
        $suggestions = $this->restrictToUser(CampaignPerformanceSuggestion::query(), $user)
            ->get()
            ->keyBy(fn (CampaignPerformanceSuggestion $row): string => $row->platform.'|'.$row->external_campaign_id);

        if ($this->adops->isAvailable()) {
            CampaignPerformanceSuggestion::query()
                ->whereIn('platform', $platformsToQuery)
                ->get()
                ->each(function (CampaignPerformanceSuggestion $row) use ($suggestions): void {
                    if (data_get($row->snapshot, 'data_source') !== 'whale_adops') {
                        return;
                    }

                    $suggestions->put($row->platform.'|'.$row->external_campaign_id, $row);
                });
        }

        $learningWindow = (int) config('campaign-performance.learning_window_days', 3);
        $maxTest = (float) config('campaign-performance.max_test_spend', 40);
        $ingestErrors = [];
        $roiTotals = $this->roiTotals($identities);

        return $identities->map(function (array $identity) use ($suggestions, $learningWindow, $maxTest, $whaleTotals, $widerTotals, $roiTotals, &$ingestErrors): array {
            $key = $identity['platform'].'|'.$identity['external_campaign_id'];
            $suggestion = $suggestions->get($key);
            $daysLive = $this->campaignAgeDays(
                is_string($identity['started_at'] ?? null) ? $identity['started_at'] : null,
                null,
                (int) data_get($suggestion?->snapshot, 'days_live', 0),
            );
            $spend = (float) data_get($suggestion?->snapshot, 'windows.7d.spend', data_get($suggestion?->snapshot, 'last_7_days.spend', 0));
            $clicks = (int) data_get($suggestion?->snapshot, 'windows.7d.clicks', data_get($suggestion?->snapshot, 'last_7_days.clicks', 0));
            $impressions = (int) data_get($suggestion?->snapshot, 'windows.7d.impressions', data_get($suggestion?->snapshot, 'last_7_days.impressions', 0));
            $platformConversions = (int) data_get($suggestion?->snapshot, 'windows.7d.conversions', data_get($suggestion?->snapshot, 'last_7_days.conversions', 0));
            $platformConversionValue = (float) data_get($suggestion?->snapshot, 'windows.7d.conversion_value', data_get($suggestion?->snapshot, 'last_7_days.conversion_value', 0));

            $plat = $identity['platform'];
            if (isset($whaleTotals[$plat][$identity['external_campaign_id']])) {
                $whale = $whaleTotals[$plat][$identity['external_campaign_id']];
                $spend = round((float) $whale['spend'], 2);
                $clicks = (int) $whale['clicks'];
                $impressions = (int) $whale['impressions'];
                if (array_key_exists('conversions', $whale)) {
                    $platformConversions = (int) $whale['conversions'];
                }
            } else {
                $spend = round($spend, 2);
            }

            $name = $this->resolveCampaignName(
                $identity['external_campaign_id'],
                (string) $identity['name'],
                $suggestion,
            );
            $ctr = $impressions > 0 ? round($clicks / $impressions, 4) : null;
            $snapshot = is_array($suggestion?->snapshot) ? $suggestion->snapshot : [];
            $wider = $widerTotals[$identity['platform']][$identity['external_campaign_id']]
                ?? $widerTotals[$identity['external_campaign_id']]
                ?? null;
            $widerConversions = $identity['platform'] === 'meta' && is_array($wider)
                ? (int) ($wider['conversions'] ?? data_get($snapshot, 'windows.30d.conversions', 0))
                : $platformConversions;
            $headline = PerformanceHeadline::choose(
                ['spend' => $spend, 'clicks' => $clicks, 'impressions' => $impressions, 'conversions' => $platformConversions],
                is_array($wider)
                    ? [
                        'spend' => (float) $wider['spend'],
                        'clicks' => (int) $wider['clicks'],
                        'impressions' => (int) $wider['impressions'],
                        'conversions' => $widerConversions,
                    ]
                    : ['spend' => $spend, 'clicks' => $clicks, 'impressions' => $impressions, 'conversions' => $platformConversions],
            );
            $platformConversions = (int) ($headline['conversions'] ?? $platformConversions);
            $aiStatus = CampaignDecisionVerdict::tryFrom((string) data_get($suggestion?->snapshot, 'ai_status'));
            $budgetSummary = $this->budgetSummary(
                $suggestion?->status,
                $snapshot !== [] ? $snapshot : null,
                $identity['daily_budget'] ?? null,
            );
            $row = [
                'name' => $name,
                'platform' => $identity['platform'],
                'external_campaign_id' => $identity['external_campaign_id'],
                'account_id' => $identity['account_id'] ?? null,
                'daily_budget' => $identity['daily_budget'] ?? data_get($snapshot, 'daily_budget'),
                'started_at' => $identity['started_at'] ?? data_get($snapshot, 'campaign_profile.started_at'),
                'objective' => $identity['objective'] ?? data_get($snapshot, 'campaign_profile.objective'),
                'platform_status' => $identity['platform_status'] ?? data_get($snapshot, 'platform_status'),
                'delivery_status' => $identity['learning_status'] ?? data_get($snapshot, 'delivery_status'),
                'region_label' => data_get($snapshot, 'campaign_profile.region_label'),
                'platform_learning_label' => $identity['learning_status']
                    ?? data_get($snapshot, 'campaign_profile.platform_learning_label'),
                'status' => $suggestion?->status,
                'verdict' => $this->resolvedVerdict($suggestion?->status)?->value ?? $suggestion?->status,
                'verdict_label' => $this->resolvedVerdict($suggestion?->status)?->label() ?? 'No verdict yet',
                'action_summary' => $budgetSummary ?? $this->resolvedVerdictActionSummary($suggestion?->status),
                'budget_summary' => $budgetSummary,
                'learning' => $this->learningLabel($daysLive, $learningWindow, $spend, $maxTest),
                'headline' => $headline,
                'spend_7d' => $spend,
                'clicks_7d' => $clicks,
                'impressions_7d' => $impressions,
                'cpc_7d' => $clicks > 0 ? round($spend / $clicks, 4) : null,
                'ctr_7d' => $ctr,
                'platform_conversions_7d' => $platformConversions,
                'platform_conversion_value_7d' => $platformConversionValue,
                'affiliate_clicks_7d' => data_get($snapshot, 'affiliate.7d.clicks'),
                'affiliate_sum_cpc_7d' => data_get($snapshot, 'affiliate.7d.sum_cpc'),
                'affiliate_orders_7d' => data_get($snapshot, 'affiliate.7d.orders'),
                'affiliate_matched' => (bool) data_get($snapshot, 'affiliate.matched', false),
                'trend' => data_get($snapshot, 'trend'),
                'trend_summary' => data_get($snapshot, 'trend_summary'),
                'roi_performance' => ($identity['metrics_source'] ?? null) === 'roi_dashboard'
                    ? ($roiTotals[$identity['platform'].'|'.$identity['external_campaign_id']] ?? null)
                    : null,
                'reason' => $suggestion?->reason,
                'marketing_summary' => data_get($suggestion?->snapshot, 'marketing_diagnosis.summary'),
                'marketing_plan' => data_get($suggestion?->snapshot, 'marketing_diagnosis.plan'),
                'budget_summary' => $budgetSummary,
                'marketing_lever' => data_get($suggestion?->snapshot, 'marketing_diagnosis.primary_lever'),
                'landing_suggestion' => data_get($suggestion?->snapshot, 'landing_suggestion'),
                'review' => data_get($suggestion?->snapshot, 'review'),
                'ad_set_optimization' => data_get($suggestion?->snapshot, 'ad_set_optimization'),
                'creative_context' => data_get($suggestion?->snapshot, 'creative_context'),
                'ai_status' => $aiStatus?->value,
                'ai_status_label' => $aiStatus?->label(),
                'verdict_reason' => $this->engineVerdictReason($suggestion),
                'verdict_reasons' => $this->engineVerdictReasons($suggestion),
                'affiliate_net_revenue_7d' => data_get($snapshot, 'affiliate.7d.net_revenue'),
                'updated_at' => $suggestion?->suggested_at,
                'last_error' => $this->ingestErrorFor($identity, $ingestErrors),
                'snapshot' => $snapshot,
            ];
            $row['brief'] = CampaignPerformanceBrief::forDisplay($row, $snapshot);

            return $row;
        })->sort(fn (array $left, array $right): int => $this->compareCampaignRows($left, $right, 'spend_7d'))
            ->values();
    }

    /**
     * @return Collection<int, array{platform: string, external_campaign_id: string, name: string, account_id: ?string}>
     */
    private function identities(User $user, ?string $platform = null): Collection
    {
        $rows = collect();
        $configuredPlatforms = array_map(strtolower(...), (array) config('campaign-performance.adops_platforms', ['meta', 'google', 'linkedin']));
        $platformsToLoad = $platform !== null ? [$platform] : $configuredPlatforms;

        if ($this->adops->isAvailable() && config('campaign-performance.adops_list_all')) {
            foreach ($platformsToLoad as $platformKey) {
                foreach ($this->adops->campaignsWithRecentStats($platformKey) as $campaign) {
                    $this->putIdentity(
                        $rows,
                        $campaign['platform'] !== '' ? $campaign['platform'] : $platformKey,
                        $campaign['campaign_id'],
                        $campaign['name'] !== '' ? $campaign['name'] : 'Campaign '.$campaign['campaign_id'],
                        [
                            'account_id' => $campaign['account_id'],
                            'platform_status' => $campaign['effective_status'] ?? $campaign['status'],
                            'daily_budget' => $campaign['daily_budget'],
                            'learning_status' => $campaign['learning_status'],
                            'started_at' => $campaign['started_at'],
                            'objective' => $campaign['objective'] ?? null,
                            'metrics_source' => $campaign['metrics_source'] ?? null,
                        ],
                    );
                }
            }
        } else {
            $query = CampaignPerformanceSuggestion::query();
            if ($platform !== null) {
                $query->where('platform', $platform);
            }
            $this->restrictToUser($query, $user)
                ->get()
                ->each(function (CampaignPerformanceSuggestion $suggestion) use ($rows): void {
                    $this->putIdentity(
                        $rows,
                        (string) $suggestion->platform,
                        (string) $suggestion->external_campaign_id,
                        'Campaign '.$suggestion->external_campaign_id,
                        [
                            'account_id' => data_get($suggestion->snapshot, 'campaign_profile.account_id'),
                            'platform_status' => data_get($suggestion->snapshot, 'platform_status'),
                            'daily_budget' => data_get($suggestion->snapshot, 'daily_budget'),
                            'learning_status' => data_get($suggestion->snapshot, 'campaign_profile.platform_learning_label'),
                            'started_at' => data_get($suggestion->snapshot, 'campaign_profile.started_at'),
                            'objective' => data_get($suggestion->snapshot, 'campaign_profile.objective'),
                        ],
                    );
                });
        }

        $this->collectLocalCampaignIdentities($rows, $user, $platform);

        return $rows->values();
    }

    private function collectLocalCampaignIdentities(Collection $rows, User $user, ?string $platform = null): void
    {
        $configuredPlatforms = array_map(strtolower(...), (array) config('campaign-performance.adops_platforms', ['meta', 'google', 'linkedin']));
        $targetPlatforms = $platform !== null ? [$platform] : $configuredPlatforms;

        $campaignPlatforms = array_values(array_intersect($targetPlatforms, ['meta', 'google', 'linkedin']));
        if ($campaignPlatforms !== []) {
            $campaignQuery = Campaign::query()
                ->select(['id', 'user_id', 'platform', 'external_campaign_id', 'name', 'ad_account_id', 'status', 'budget', 'created_at'])
                ->whereIn('platform', $campaignPlatforms)
                ->whereNotNull('external_campaign_id')
                ->where('external_campaign_id', '!=', '');

            if (! config('campaign-performance.skip_user_scope')) {
                $campaignQuery->where('user_id', $user->id);
            }

            $campaignQuery->get()->each(function (Campaign $campaign) use ($rows): void {
                $this->putIdentity(
                    $rows,
                    (string) $campaign->platform,
                    (string) $campaign->external_campaign_id,
                    (string) $campaign->name,
                    [
                        'account_id' => $campaign->ad_account_id,
                        'platform_status' => $campaign->status,
                        'daily_budget' => $campaign->budget,
                        'started_at' => $campaign->created_at?->toIso8601String(),
                    ],
                );
            });
        }

        if (in_array('google', $targetPlatforms, true)) {
            $googleAdsQuery = GoogleAdsCampaign::query()
                ->select(['id', 'user_id', 'google_campaign_id', 'name', 'status', 'daily_budget', 'created_at'])
                ->whereNotNull('google_campaign_id')
                ->where('google_campaign_id', '!=', '');

            if (! config('campaign-performance.skip_user_scope')) {
                $googleAdsQuery->where('user_id', $user->id);
            }

            $googleAdsQuery->get()->each(function (GoogleAdsCampaign $campaign) use ($rows): void {
                $this->putIdentity(
                    $rows,
                    'google',
                    (string) $campaign->google_campaign_id,
                    (string) ($campaign->name ?? 'Campaign '.$campaign->google_campaign_id),
                    [
                        'account_id' => null,
                        'platform_status' => $campaign->status,
                        'daily_budget' => $campaign->daily_budget,
                        'started_at' => $campaign->created_at?->toIso8601String(),
                    ],
                );
            });
        }
    }

    /**
     * @param  Collection<string, array<string, mixed>>  $rows
     * @param  array<string, mixed>  $meta
     */
    private function putIdentity(Collection $rows, string $platform, string $externalId, string $name, array $meta = []): void
    {
        $key = $platform.'|'.$externalId;

        if ($rows->has($key)) {
            return;
        }

        $accountId = $meta['account_id'] ?? null;

        $rows->put($key, [
            'platform' => $platform,
            'external_campaign_id' => $externalId,
            'name' => $name,
            'account_id' => is_string($accountId) && $accountId !== '' ? $accountId : null,
            'platform_status' => is_string($meta['platform_status'] ?? null) ? $meta['platform_status'] : null,
            'daily_budget' => isset($meta['daily_budget']) ? (is_numeric($meta['daily_budget']) ? (float) $meta['daily_budget'] : null) : null,
            'learning_status' => is_string($meta['learning_status'] ?? null) ? $meta['learning_status'] : null,
            'started_at' => is_string($meta['started_at'] ?? null) ? $meta['started_at'] : null,
            'objective' => is_string($meta['objective'] ?? null) && $meta['objective'] !== '' ? $meta['objective'] : null,
            'metrics_source' => ($meta['metrics_source'] ?? null) === 'roi_dashboard' ? 'roi_dashboard' : null,
        ]);
    }

    /**
     * @param  Collection<int, array<string, mixed>>  $identities
     * @return array<string, array<string, mixed>>
     */
    private function roiTotals(Collection $identities): array
    {
        $totals = [];

        foreach ($identities->groupBy('platform') as $platform => $group) {
            $ids = $group
                ->filter(fn (array $identity): bool => ($identity['metrics_source'] ?? null) === 'roi_dashboard')
                ->pluck('external_campaign_id')
                ->all();

            if ($ids !== []) {
                $platformTotals = $this->roi->totalsForCampaigns((string) $platform, $ids);
                foreach ($platformTotals as $campaignId => $data) {
                    $key = ((string) $platform).'|'.((string) $campaignId);
                    $totals[$key] = $data;
                }
            }
        }

        return $totals;
    }

    /**
     * @param  array{platform: string, account_id?: ?string}  $identity
     * @param  array<string, ?string>  $cache
     */
    private function ingestErrorFor(array $identity, array &$cache): ?string
    {
        $accountId = is_string($identity['account_id'] ?? null) ? $identity['account_id'] : null;
        $key = $identity['platform'].'|'.($accountId ?? '');

        if (! array_key_exists($key, $cache)) {
            $cache[$key] = $this->adops->ingestError($identity['platform'], $accountId, 'hourly');
        }

        return $cache[$key];
    }

    private function resolveCampaignName(
        string $externalId,
        string $identityName,
        ?CampaignPerformanceSuggestion $suggestion,
    ): string {
        $candidates = [
            data_get($suggestion?->snapshot, 'campaign'),
            data_get($suggestion?->snapshot, 'campaign_profile.name'),
            $identityName,
        ];

        foreach ($candidates as $candidate) {
            $name = trim((string) ($candidate ?? ''));

            if ($name !== '' && ! $this->isPlaceholderCampaignName($name, $externalId)) {
                return $name;
            }
        }

        return 'Campaign '.$externalId;
    }

    private function isPlaceholderCampaignName(string $name, string $externalId): bool
    {
        return $name === 'Campaign '.$externalId;
    }

    private function learningLabel(int $daysLive, int $window, float $spend, float $maxTest): string
    {
        $spendText = '$'.number_format($spend, 2);
        $capText = '$'.number_format($maxTest, 2);
        $insideLearning = $daysLive > 0 && $daysLive < $window && $spend < $maxTest;

        if ($insideLearning) {
            return sprintf('Learning day %d of %d · %s of %s test spend', $daysLive, $window, $spendText, $capText);
        }

        if ($daysLive > 0) {
            return sprintf('%d days live · %s spend vs %s test cap', $daysLive, $spendText, $capText);
        }

        return sprintf('%s spend vs %s test cap', $spendText, $capText);
    }

    /**
     * Days since the campaign started, or since the earliest day on file.
     *
     * @param  Collection<int, PerformanceDay>|null  $days
     */
    private function campaignAgeDays(?string $startedAt, ?Collection $days, int $stored): int
    {
        $starts = [];

        if (is_string($startedAt) && $startedAt !== '') {
            $starts[] = Carbon::parse($startedAt)->startOfDay();
        }

        if ($days !== null && $days->isNotEmpty()) {
            $first = $days->min('stat_date');

            if ($first instanceof Carbon) {
                $starts[] = $first->copy()->startOfDay();
            }
        }

        if ($starts === []) {
            return max(0, $stored);
        }

        $start = collect($starts)->sortBy(fn (Carbon $day): int => $day->timestamp)->first();

        return max(1, (int) $start->diffInDays(now()->startOfDay()) + 1);
    }

    /**
     * @param  array{
     *     log_run_type?: string,
     *     log_verdict?: string,
     *     log_days?: int,
     *     log_per_page?: int
     * }  $filters
     */
    private function decisionLogsFor(User $user, string $platform, string $externalId, array $filters): LengthAwarePaginator
    {
        $query = $this->restrictToUser(CampaignDecision::query(), $user)
            ->where('platform', $platform)
            ->where('external_campaign_id', $externalId);

        $runType = trim((string) ($filters['log_run_type'] ?? ''));

        if ($runType === 'hourly') {
            $query->where('trigger', 'scheduled_hourly');
        } elseif ($runType === 'daily') {
            $query->where('trigger', 'scheduled_affiliate_refresh');
        } elseif ($runType === 'manual') {
            $query->where('trigger', 'manual');
        }

        $verdict = trim((string) ($filters['log_verdict'] ?? ''));

        if (CampaignDecisionVerdict::tryFrom($verdict) !== null) {
            $query->where('verdict', $verdict);
        }

        $days = (int) ($filters['log_days'] ?? 0);

        if (in_array($days, [7, 30, 90], true)) {
            $query->where('evaluated_at', '>=', now()->subDays($days));
        }

        $perPage = in_array((int) ($filters['log_per_page'] ?? 10), [10, 25, 50], true)
            ? (int) ($filters['log_per_page'] ?? 10)
            : 10;

        return $query
            ->orderByDesc('evaluated_at')
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'log_page')
            ->withQueryString();
    }

    /**
     * @param  array{
     *     log_run_type?: string,
     *     log_verdict?: string,
     *     log_days?: int,
     *     log_per_page?: int
     * }  $filters
     */
    private function verdictLogsFor(User $user, string $platform, string $externalId, array $filters): LengthAwarePaginator
    {
        $query = $this->restrictToUser(CampaignPerformanceVerdictLog::query(), $user)
            ->where('platform', $platform)
            ->where('external_campaign_id', $externalId);

        $runType = trim((string) ($filters['log_run_type'] ?? ''));

        if (in_array($runType, ['hourly', 'daily', 'manual'], true)) {
            $query->where('run_type', $runType);
        }

        $verdict = trim((string) ($filters['log_verdict'] ?? ''));

        if (PerformanceVerdict::tryFromStored($verdict) !== null) {
            $query->where('final_verdict', $verdict);
        }

        $days = (int) ($filters['log_days'] ?? 0);

        if (in_array($days, [7, 30, 90], true)) {
            $query->where('evaluated_at', '>=', now()->subDays($days));
        }

        $perPage = in_array((int) ($filters['log_per_page'] ?? 10), [10, 25, 50], true)
            ? (int) ($filters['log_per_page'] ?? 10)
            : 10;

        return $query
            ->orderByDesc('evaluated_at')
            ->orderByDesc('id')
            ->paginate($perPage, ['*'], 'log_page')
            ->withQueryString();
    }

    /**
     * @param  array<string, mixed>  $row
     */
    private function matchesCampaignQuery(array $row, string $query): bool
    {
        $needle = strtolower(trim($query));

        return str_contains(strtolower((string) ($row['name'] ?? '')), $needle)
            || str_contains(strtolower((string) ($row['external_campaign_id'] ?? '')), $needle);
    }

    /**
     * Data-issue rows stay at the bottom. Everything else keeps the previous order key.
     *
     * @param  array<string, mixed>  $left
     * @param  array<string, mixed>  $right
     * @param  'spend_7d'|'updated_at'  $thenBy
     */
    private function compareCampaignRows(array $left, array $right, string $thenBy): int
    {
        $issue = $this->dataIssueRank($left) <=> $this->dataIssueRank($right);

        if ($issue !== 0) {
            return $issue;
        }

        if ($thenBy === 'spend_7d') {
            $spend = ($right['spend_7d'] ?? 0) <=> ($left['spend_7d'] ?? 0);

            if ($spend !== 0) {
                return $spend;
            }
        } else {
            $time = ($right['updated_at'] ?? null) <=> ($left['updated_at'] ?? null);

            if ($time !== 0) {
                return $time;
            }
        }

        return strcasecmp((string) ($left['name'] ?? ''), (string) ($right['name'] ?? ''));
    }

    /**
     * @param  array<string, mixed>  $row
     */
    private function dataIssueRank(array $row): int
    {
        return ($row['status'] ?? null) === CampaignDecisionVerdict::DataIssue->value ? 1 : 0;
    }

    private function resolvedVerdict(?string $status): CampaignDecisionVerdict|PerformanceVerdict|null
    {
        return CampaignDecisionVerdict::tryFromStored($status)
            ?? PerformanceVerdict::tryFromStored($status);
    }

    /**
     * @param  array<string, mixed>|null  $snapshot
     */
    private function budgetSummary(?string $status, ?array $snapshot, mixed $dailyBudget, ?int $changePercent = null): ?string
    {
        $budget = is_numeric($dailyBudget) ? (float) $dailyBudget : null;

        return CampaignBudgetRecommendation::fromStored($status, $snapshot, $budget, $changePercent)['summary'] ?? null;
    }

    private function resolvedVerdictActionSummary(?string $status): string
    {
        $verdict = $this->resolvedVerdict($status);

        if ($verdict instanceof CampaignDecisionVerdict) {
            return $verdict->actionSummary();
        }

        if ($verdict instanceof PerformanceVerdict) {
            return $verdict->actionSummary();
        }

        return 'Run campaigns:monitor-adops --hourly to generate a suggestion.';
    }

    private function engineVerdictReason(?CampaignPerformanceSuggestion $suggestion): ?string
    {
        if ($suggestion === null) {
            return null;
        }

        $snapshot = is_array($suggestion->snapshot) ? $suggestion->snapshot : [];

        if (data_get($snapshot, 'decision_engine') === 'v2') {
            $reason = data_get($snapshot, 'reason');

            return is_string($reason) && $reason !== '' ? $reason : null;
        }

        $reason = data_get($snapshot, 'final_reason')
            ?: data_get($snapshot, 'verdicts.final_reason');

        return is_string($reason) && $reason !== '' ? $reason : null;
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function engineVerdictReasons(?CampaignPerformanceSuggestion $suggestion): array
    {
        if ($suggestion === null) {
            return [];
        }

        $reasons = data_get($suggestion->snapshot, 'reasons', []);

        return is_array($reasons) ? array_values(array_filter($reasons, is_array(...))) : [];
    }

    /**
     * @return array<string, mixed>
     */
    private function decisionCard(CampaignDecision $decision): array
    {
        $snapshot = is_array($decision->snapshot_json) ? $decision->snapshot_json : [];
        $metrics = is_array($decision->metrics_json) ? $decision->metrics_json : [];
        $window = data_get($metrics, 'windows.7d', data_get($snapshot, 'windows.7d', []));
        $window = is_array($window) ? $window : [];
        $spend = round((float) ($window['spend'] ?? 0), 2);
        $clicks = (int) ($window['clicks'] ?? 0);
        $impressions = (int) ($window['impressions'] ?? 0);
        $verdict = CampaignDecisionVerdict::tryFrom((string) $decision->verdict);
        $reasons = is_array($decision->reasons_json) ? $decision->reasons_json : [];
        $aiReason = data_get($snapshot, 'ai_reason');
        $engineReason = data_get($snapshot, 'reason');
        $change = (int) $decision->recommended_budget_change_percent;
        $budgetSummary = $this->budgetSummary(
            (string) $decision->verdict,
            $snapshot,
            data_get($snapshot, 'daily_budget'),
            $change,
        );
        $summary = $budgetSummary ?? ($verdict?->actionSummary() ?? 'Review this campaign before changing it.');

        $trigger = match ((string) $decision->trigger) {
            'scheduled_hourly' => 'Hourly',
            'scheduled_affiliate_refresh' => 'Daily',
            default => ucfirst(str_replace('_', ' ', (string) $decision->trigger)),
        };

        $row = [
            'name' => $decision->campaign_name !== '' ? $decision->campaign_name : 'Campaign '.$decision->external_campaign_id,
            'platform' => (string) $decision->platform,
            'external_campaign_id' => (string) $decision->external_campaign_id,
            'account_id' => $decision->account_id,
            'daily_budget' => data_get($snapshot, 'daily_budget'),
            'region_label' => data_get($snapshot, 'campaign_profile.region_label'),
            'platform_status' => data_get($snapshot, 'platform_status'),
            'status' => $decision->verdict,
            'action_summary' => $summary,
            'trend' => data_get($snapshot, 'trend'),
            'trend_summary' => data_get($snapshot, 'trend_summary'),
            'spend_7d' => $spend,
            'impressions_7d' => $impressions,
            'clicks_7d' => $clicks,
            'cpc_7d' => $clicks > 0 ? round($spend / $clicks, 4) : ($window['cpc'] ?? null),
            'ctr_7d' => $impressions > 0 ? round($clicks / $impressions, 4) : ($window['ctr'] ?? null),
            'platform_conversions_7d' => (int) ($window['conversions'] ?? 0),
            'roi_performance' => null,
            'affiliate_matched' => (bool) data_get($snapshot, 'affiliate.matched', false),
            'affiliate_orders_7d' => data_get($snapshot, 'affiliate.7d.orders'),
            'affiliate_clicks_7d' => data_get($snapshot, 'affiliate.7d.clicks'),
            'affiliate_sum_cpc_7d' => data_get($snapshot, 'affiliate.7d.sum_cpc'),
            'affiliate_net_revenue_7d' => data_get($snapshot, 'affiliate.7d.net_revenue'),
            'verdict_reason' => is_string($engineReason) && $engineReason !== '' ? $engineReason : $decision->reason,
            'verdict_reasons' => array_values(array_filter($reasons, is_array(...))),
            'marketing_summary' => data_get($snapshot, 'marketing_diagnosis.summary'),
            'marketing_plan' => data_get($snapshot, 'marketing_diagnosis.plan'),
            'budget_summary' => $budgetSummary,
            'marketing_lever' => data_get($snapshot, 'marketing_diagnosis.primary_lever'),
            'landing_suggestion' => data_get($snapshot, 'landing_suggestion'),
            'review' => data_get($snapshot, 'review'),
            'ad_set_optimization' => data_get($snapshot, 'ad_set_optimization'),
            'creative_context' => data_get($snapshot, 'creative_context'),
            'reason' => is_string($aiReason) && $aiReason !== '' ? $aiReason : $decision->reason,
            'learning' => $trigger.' · confidence '.number_format((float) $decision->confidence, 2),
            'platform_learning_label' => data_get($snapshot, 'campaign_profile.platform_learning_label'),
            'last_error' => null,
            'updated_at' => $decision->evaluated_at,
            'snapshot' => $snapshot,
        ];
        $row['brief'] = CampaignPerformanceBrief::forDisplay($row, $snapshot);

        return $row;
    }

    /**
     * @param  Builder<Model>  $query
     * @return Builder<Model>
     */
    private function restrictToUser(Builder $query, User $user): Builder
    {
        if (config('campaign-performance.skip_user_scope')) {
            return $query;
        }

        return $query->where('user_id', $user->id);
    }
}
