<?php

namespace App\Campaigns;

use App\Models\CampaignPerformanceHourStat;
use App\Models\CampaignPerformanceStat;
use Illuminate\Support\Collection;

class CampaignPerformanceVerdictEvaluator
{
    public function __construct(
        private readonly PerformanceWindowVerdict $windowVerdict,
        private readonly PerformanceVerdictCombiner $combiner,
    ) {}

    /**
     * @param  array<string, mixed>  $context
     * @param  Collection<int, CampaignPerformanceStat>  $days
     * @param  Collection<int, CampaignPerformanceHourStat>  $hours
     * @param  'hourly'|'daily'|'manual'  $runType
     * @return array{
     *     windows: array<string, array<string, mixed>>,
     *     hourly_verdict: ?array{verdict: string, reason: string},
     *     final_verdict: PerformanceVerdict,
     *     final_reason: string
     * }
     */
    public function evaluate(array $context, Collection $days, Collection $hours, string $runType = 'daily'): array
    {
        $windowKeys = $runType === 'hourly'
            ? PerformanceWindows::hourWindowKeys()
            : array_keys(PerformanceWindows::analysis());

        $windows = [];

        foreach ($windowKeys as $windowKey) {
            $definition = PerformanceWindows::analysis()[$windowKey];
            $rollup = $definition['type'] === 'hours'
                ? PerformanceWindowRollup::fromHours($windowKey, $definition['length'], $hours)
                : PerformanceWindowRollup::fromDays($windowKey, $definition['length'], $days);

            $windows[$windowKey] = $this->windowVerdict->forWindow($rollup, $context);
        }

        $hourly = $runType === 'hourly'
            ? $this->combiner->hourly($windows)
            : null;

        $final = $runType === 'hourly' && $hourly !== null
            ? $hourly
            : $this->combiner->final($windows);

        return [
            'windows' => $windows,
            'hourly_verdict' => $hourly === null
                ? null
                : [
                    'verdict' => $hourly['verdict']->value,
                    'reason' => $hourly['reason'],
                ],
            'final_verdict' => $final['verdict'],
            'final_reason' => $final['reason'],
        ];
    }
}
