<?php

namespace App\Services\Prediction\Signals;

use Illuminate\Support\Facades\DB;

final class OilSignal extends AbstractSignal
{
    /**
     * Reads the most recent Brent crude prediction (LLM preferred, EWMA
     * fallback) covering today or later. Sourced from price_predictions,
     * which OilPriceService populates daily.
     */
    public function compute(SignalContext $context): array
    {
        $prediction = null;

        foreach (['llm_with_context', 'llm', 'ewma'] as $source) {
            $prediction = DB::table('price_predictions')
                ->where('source', $source)
                ->where('predicted_for', '>=', now()->toDateString())
                ->orderByDesc('predicted_for')
                ->orderByDesc('generated_at')
                ->first();

            if ($prediction !== null) {
                break;
            }
        }

        if ($prediction === null) {
            return $this->disabledSignal('No oil price prediction available');
        }

        $direction = match ($prediction->direction) {
            'rising' => 'up',
            'falling' => 'down',
            default => 'stable',
        };

        $score = match ($direction) {
            'up' => 1.0,
            'down' => -1.0,
            default => 0.0,
        };

        $confidence = round(((float) $prediction->confidence) / 100, 2);

        return [
            'score' => $score,
            'confidence' => $confidence,
            'direction' => $direction,
            'detail' => sprintf(
                'Brent crude %s (%s, %d%% confidence)',
                $prediction->direction,
                $prediction->source,
                (int) $prediction->confidence,
            ),
            'data_points' => 1,
            'enabled' => true,
        ];
    }
}
