<?php

use App\Enums\FuelType;
use App\Models\Station;
use App\Models\StationPrice;
use App\Models\StationPriceCurrent;
use App\Services\NationalFuelPredictionService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('returns no_signal when there is insufficient price history', function () {
    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['predicted_direction'])->toBe('stable')
        ->and($result['signals']['trend']['enabled'])->toBeFalse()
        ->and($result['action'])->toBe('no_signal');
});

it('detects rising trend from consistently increasing daily averages', function () {
    $station = Station::factory()->create();

    // 7 days of prices rising at ~100 pence/day
    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 14000 + ((6 - $daysAgo) * 100),
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['signals']['trend']['direction'])->toBe('up')
        ->and($result['signals']['trend']['enabled'])->toBeTrue()
        ->and($result['predicted_direction'])->toBe('up')
        ->and($result['action'])->toBe('fill_now');
});

it('detects falling trend from consistently decreasing daily averages', function () {
    $station = Station::factory()->create();

    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 16000 - ((6 - $daysAgo) * 100),
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['signals']['trend']['direction'])->toBe('down')
        ->and($result['predicted_direction'])->toBe('down')
        ->and($result['action'])->toBe('wait');
});

it('returns current_avg from station_prices_current', function () {
    $station = Station::factory()->create();
    StationPriceCurrent::factory()->create([
        'station_id' => $station->node_id,
        'fuel_type' => FuelType::E10,
        'price_pence' => 14750,
    ]);

    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['current_avg'])->toBe(147.5);
});

it('includes all required keys in response', function () {
    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result)
        ->toHaveKeys([
            'fuel_type', 'current_avg', 'predicted_direction', 'predicted_change_pence',
            'confidence_score', 'confidence_label', 'action', 'reasoning',
            'prediction_horizon_days', 'region_key', 'methodology',
            'weekly_summary', 'signals',
        ])
        ->and($result['signals'])->toHaveKeys([
            'trend', 'day_of_week', 'brand_behaviour',
            'national_momentum', 'regional_momentum', 'price_stickiness', 'oil',
        ])
        ->and($result['weekly_summary'])->toHaveKeys([
            'yesterday_avg', 'today_avg', 'tomorrow_estimated_avg',
            'yesterday_today_delta_pence', 'last_7_days_series',
            'last_7_days_change_pence', 'cheapest_day', 'priciest_day', 'is_regional',
        ]);
});

it('weekly_summary returns null prices and empty series when there is no data', function () {
    $result = app(NationalFuelPredictionService::class)->predict();
    $weekly = $result['weekly_summary'];

    expect($weekly['yesterday_avg'])->toBeNull()
        ->and($weekly['yesterday_today_delta_pence'])->toBeNull()
        ->and($weekly['last_7_days_series'])->toBe([])
        ->and($weekly['cheapest_day'])->toBeNull()
        ->and($weekly['priciest_day'])->toBeNull()
        ->and($weekly['is_regional'])->toBeFalse();
});

it('weekly_summary populates yesterday avg, today avg and 7-day series from station_prices', function () {
    $station = Station::factory()->create();
    StationPriceCurrent::factory()->create([
        'station_id' => $station->node_id,
        'fuel_type' => FuelType::E10,
        'price_pence' => 14000,
    ]);

    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 14000 + ($daysAgo * 50),
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict();
    $weekly = $result['weekly_summary'];

    expect($weekly['yesterday_avg'])->toBe(140.5)
        ->and($weekly['today_avg'])->toBe(140.0)
        ->and($weekly['yesterday_today_delta_pence'])->toBe(-0.5)
        ->and(count($weekly['last_7_days_series']))->toBe(7)
        ->and($weekly['cheapest_day']['avg'])->toBe(140.0)
        ->and($weekly['priciest_day']['avg'])->toBe(143.0);
});

it('weekly_summary falls back from regional to national when regional data is empty', function () {
    $station = Station::factory()->create(['lat' => 51.5, 'lng' => -0.1]);

    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 14000,
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    // Coordinates 600+ km away from any station — no regional data available.
    $result = app(NationalFuelPredictionService::class)->predict(58.0, -3.0);
    $weekly = $result['weekly_summary'];

    expect($weekly['is_regional'])->toBeFalse()
        ->and(count($weekly['last_7_days_series']))->toBe(7);
});

it('weekly_summary marks is_regional true when stations exist within 50km of coordinates', function () {
    $station = Station::factory()->create(['lat' => 51.5, 'lng' => -0.1]);

    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 14000,
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict(51.5074, -0.1278);

    expect($result['weekly_summary']['is_regional'])->toBeTrue();
});

it('always returns e10 as fuel_type', function () {
    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['fuel_type'])->toBe('e10');
});

it('returns national region_key without coordinates', function () {
    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['region_key'])->toBe('national');
});

it('returns regional region_key when coordinates are provided', function () {
    $result = app(NationalFuelPredictionService::class)->predict(51.5074, -0.1278);

    expect($result['region_key'])->toBe('regional');
});

it('enables regional_momentum signal when coordinates are provided', function () {
    $station = Station::factory()->create(['lat' => 51.5, 'lng' => -0.1]);

    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 14000 + ((6 - $daysAgo) * 100),
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict(51.5074, -0.1278);

    expect($result['signals']['regional_momentum']['enabled'])->toBeTrue();
});

it('disables regional_momentum signal without coordinates', function () {
    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['signals']['regional_momentum']['enabled'])->toBeFalse();
});

it('disables trend signal when r_squared is below 0.5', function () {
    $station = Station::factory()->create();

    // Highly erratic prices (zigzag pattern) — low R²
    $prices = [14000, 16000, 13000, 17000, 12000, 18000, 14500];
    foreach ($prices as $daysAgo => $price) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => $price,
            'price_effective_at' => now()->subDays(count($prices) - 1 - $daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict();

    // Trend signal may be disabled if both 5-day and 14-day lookbacks fail R² threshold
    expect($result['signals']['trend']['data_points'])->toBeInt();
});

it('oil signal is disabled when no price_predictions row covers today or later', function () {
    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['signals']['oil']['enabled'])->toBeFalse();
});

it('oil signal picks up an llm prediction over an ewma one for the same date', function () {
    DB::table('price_predictions')->insert([
        [
            'predicted_for' => now()->toDateString(),
            'source' => 'ewma',
            'direction' => 'flat',
            'confidence' => 60,
            'reasoning' => null,
            'generated_at' => now()->subHour(),
        ],
        [
            'predicted_for' => now()->toDateString(),
            'source' => 'llm',
            'direction' => 'rising',
            'confidence' => 75,
            'reasoning' => 'OPEC cut',
            'generated_at' => now(),
        ],
    ]);

    $oil = app(NationalFuelPredictionService::class)->predict()['signals']['oil'];

    expect($oil['enabled'])->toBeTrue()
        ->and($oil['direction'])->toBe('up')
        ->and($oil['score'])->toBe(1.0)
        ->and($oil['confidence'])->toBe(0.75);
});

it('oil signal prefers llm_with_context over plain llm', function () {
    DB::table('price_predictions')->insert([
        [
            'predicted_for' => now()->toDateString(),
            'source' => 'llm',
            'direction' => 'falling',
            'confidence' => 70,
            'reasoning' => 'baseline',
            'generated_at' => now(),
        ],
        [
            'predicted_for' => now()->toDateString(),
            'source' => 'llm_with_context',
            'direction' => 'rising',
            'confidence' => 82,
            'reasoning' => 'with context',
            'generated_at' => now(),
        ],
    ]);

    $oil = app(NationalFuelPredictionService::class)->predict()['signals']['oil'];

    expect($oil['direction'])->toBe('up')
        ->and($oil['confidence'])->toBe(0.82);
});

it('confidence reaches "high" when trend and oil agree strongly', function () {
    $station = Station::factory()->create();

    // Strong falling trend over 7 days, ~1p/day
    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 15000 - ((6 - $daysAgo) * 100),
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    DB::table('price_predictions')->insert([
        'predicted_for' => now()->toDateString(),
        'source' => 'llm',
        'direction' => 'falling',
        'confidence' => 80,
        'reasoning' => 'agree',
        'generated_at' => now(),
    ]);

    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['predicted_direction'])->toBe('down')
        ->and($result['confidence_score'])->toBeGreaterThanOrEqual(70)
        ->and($result['confidence_label'])->toBe('high');
});

it('confidence drops when trend and oil disagree', function () {
    $station = Station::factory()->create();

    // Strong falling trend
    for ($daysAgo = 6; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 15000 - ((6 - $daysAgo) * 100),
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    // Oil disagrees: rising
    DB::table('price_predictions')->insert([
        'predicted_for' => now()->toDateString(),
        'source' => 'llm',
        'direction' => 'rising',
        'confidence' => 80,
        'reasoning' => 'opec',
        'generated_at' => now(),
    ]);

    $agree = app(NationalFuelPredictionService::class)->predict();

    // Replace oil with one that agrees instead — confidence should be higher
    DB::table('price_predictions')->update([
        'direction' => 'falling',
    ]);

    $disagreeReplaced = app(NationalFuelPredictionService::class)->predict();

    expect($agree['confidence_score'])->toBeLessThan($disagreeReplaced['confidence_score']);
});

it('day-of-week signal activates at 21 days of history (no longer 56)', function () {
    $station = Station::factory()->create();

    for ($daysAgo = 25; $daysAgo >= 0; $daysAgo--) {
        StationPrice::factory()->create([
            'station_id' => $station->node_id,
            'fuel_type' => FuelType::E10,
            'price_pence' => 14000 + ($daysAgo % 7) * 50,
            'price_effective_at' => now()->subDays($daysAgo)->setTime(12, 0),
        ]);
    }

    $result = app(NationalFuelPredictionService::class)->predict();

    expect($result['signals']['day_of_week']['enabled'])->toBeTrue();
});

it('reasoning fallback for the wait action does not say "fill up"', function () {
    // No data → trend disabled, brand disabled, oil disabled.
    // Force a "down" direction by injecting an oil prediction that points down with low confidence.
    DB::table('price_predictions')->insert([
        'predicted_for' => now()->toDateString(),
        'source' => 'ewma',
        'direction' => 'falling',
        'confidence' => 50,
        'reasoning' => null,
        'generated_at' => now(),
    ]);

    $result = app(NationalFuelPredictionService::class)->predict();

    if ($result['action'] === 'wait') {
        expect($result['reasoning'])->not->toContain('fill up at the cheapest');
    } else {
        // If thresholds keep this at no_signal, still verify action-aware fallback exists
        expect($result['reasoning'])->toBeString();
    }
});
