<?php

namespace App\Services\Forecasting;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

/**
 * Trailing-13-week hit rate for a model_version. Read from
 * `forecast_outcomes`. Returns null when fewer than 4 outcomes are
 * available (a single bad week would otherwise dominate the ratio).
 */
final class AccuracyHistory
{
    private const int WEEKS = 13;

    private const int MIN_OUTCOMES = 4;

    public function trailingHitRate(string $modelVersion): ?float
    {
        $cutoff = Carbon::now()->subWeeks(self::WEEKS)->toDateString();

        $row = DB::table('forecast_outcomes')
            ->where('model_version', $modelVersion)
            ->where('forecast_for', '>=', $cutoff)
            ->selectRaw('COUNT(*) as total, SUM(CASE WHEN correct THEN 1 ELSE 0 END) as correct')
            ->first();

        $total = (int) ($row->total ?? 0);
        if ($total < self::MIN_OUTCOMES) {
            return null;
        }

        return (int) ($row->correct ?? 0) / $total;
    }
}
