"""Pure engine tests: no database, no clock."""
from datetime import datetime, timedelta, timezone
from decimal import Decimal as D

import pytest

from app.engines import exposure
from app.engines.fefo import Stock, fefo_allocate
from app.engines.shelf_life import LIFE_CAP_MULTIPLE, recalculate_estimated

UTC = timezone.utc
NOW = datetime(2026, 9, 19, 2, 0, tzinfo=UTC)
DAY = timedelta(days=1)


def stock(batch_id, qty, *, removal_days, received_days=0, reserved=0, status="ACTIVE",
          expiry_days=None, crate=None):
    return Stock(
        batch_id=batch_id, location_id=1, qty=D(str(qty)), reserved_qty=D(str(reserved)),
        crate_id=crate or batch_id, status=status, received_at=NOW - received_days * DAY,
        removal_date=NOW + removal_days * DAY,
        effective_expiry=NOW + (expiry_days if expiry_days is not None else removal_days + 1) * DAY)


# ------------------------------------------------------------------ FEFO
def test_fefo_picks_earliest_removal_first_not_oldest_received():
    hot = stock(1, 10, removal_days=2, received_days=0)      # heat cut its life short
    old = stock(2, 10, removal_days=5, received_days=3)      # received earlier but lasts longer
    res = fefo_allocate([old, hot], D(10), strategy="FEFO", whole_crates=False, now=NOW)
    assert [a.batch_id for a in res.allocations] == [1]


def test_fifo_ignores_removal_date():
    hot = stock(1, 10, removal_days=2, received_days=0)
    old = stock(2, 10, removal_days=5, received_days=3)
    res = fefo_allocate([hot, old], D(10), strategy="FIFO", whole_crates=False, now=NOW)
    assert [a.batch_id for a in res.allocations] == [2]


def test_expired_batches_are_never_offered():
    expired_status = stock(1, 10, removal_days=-3, status="EXPIRED")
    past_expiry = stock(2, 10, removal_days=-3, expiry_days=-1)
    written_off = stock(3, 10, removal_days=1, status="WRITTEN_OFF")
    good = stock(4, 10, removal_days=4)
    res = fefo_allocate([expired_status, past_expiry, written_off, good], D(30),
                        strategy="FEFO", whole_crates=False, now=NOW)
    assert [a.batch_id for a in res.allocations] == [4]
    assert res.is_short and res.short == D(20)


def test_reserved_stock_is_not_available():
    a = stock(1, 10, removal_days=1, reserved=10)
    b = stock(2, 10, removal_days=2, reserved=4)
    res = fefo_allocate([a, b], D(8), strategy="FEFO", whole_crates=False, now=NOW)
    assert [(x.batch_id, x.qty) for x in res.allocations] == [(2, D(6))]
    assert res.short == D(2)


def test_packaged_takes_partial_batches_in_order():
    res = fefo_allocate([stock(1, 12, removal_days=1), stock(2, 12, removal_days=2)], D(15),
                        strategy="FEFO", whole_crates=False, now=NOW)
    assert [(a.batch_id, a.qty) for a in res.allocations] == [(1, D(12)), (2, D(3))]
    assert not res.is_short


def test_loose_whole_crates_round_down_and_never_exceed_request():
    crates = [stock(1, "12.5", removal_days=1), stock(2, 15, removal_days=2),
              stock(3, "12.5", removal_days=3)]
    res = fefo_allocate(crates, D(25), strategy="FEFO", whole_crates=True, now=NOW)
    # 12.5 fits, 15 would overshoot and is skipped, the next 12.5 fits
    assert [a.batch_id for a in res.allocations] == [1, 3]
    assert res.allocated == D(25) and not res.is_short

    small = fefo_allocate(crates, D(10), strategy="FEFO", whole_crates=True, now=NOW)
    assert small.allocations == [] and small.short == D(10)  # no crate fits: flagged, not faked


def test_loose_partially_reserved_crate_is_skipped():
    res = fefo_allocate([stock(1, 10, removal_days=1, reserved=2)], D(10),
                        strategy="FEFO", whole_crates=True, now=NOW)
    assert res.allocations == [] and res.is_short


def test_unknown_strategy_is_an_error():
    with pytest.raises(ValueError):
        fefo_allocate([stock(1, 1, removal_days=1)], D(1), strategy="LIFO", whole_crates=False,
                      now=NOW)


# ------------------------------------------------------------------ exposure
def hours(start, values):
    return {start + timedelta(hours=i): v for i, v in enumerate(values)}


def test_window_average_weights_partial_hours():
    start = datetime(2026, 9, 19, 0, 30, tzinfo=UTC)
    temps = hours(datetime(2026, 9, 19, 0, tzinfo=UTC), [20.0, 30.0])
    avg, flag = exposure.window_average(temps, start, start + timedelta(hours=1))
    assert avg == pytest.approx(25.0) and flag is None  # half an hour in each


def test_short_gap_is_interpolated():
    t0 = datetime(2026, 9, 19, 0, tzinfo=UTC)
    temps = {t0: 20.0, t0 + timedelta(hours=3): 32.0}  # 2 hours missing between
    avg, flag = exposure.window_average(temps, t0, t0 + timedelta(hours=4))
    assert flag == "INTERPOLATED"
    assert avg == pytest.approx((20 + 24 + 28 + 32) / 4)


def test_long_gap_falls_back_to_monthly_mean():
    t0 = datetime(2026, 9, 19, 0, tzinfo=UTC)
    temps = {t0: 20.0, t0 + timedelta(hours=5): 20.0}  # 4 missing hours: too long
    avg, flag = exposure.window_average(temps, t0, t0 + timedelta(hours=6))
    assert flag == "FALLBACK"
    fallback = exposure.monthly_mean(t0)
    assert avg == pytest.approx((20 + 4 * fallback + 20) / 6)


def test_no_weather_at_all_is_fallback():
    t0 = datetime(2026, 9, 19, 0, tzinfo=UTC)
    avg, flag = exposure.window_average({}, t0, t0 + timedelta(hours=6))
    assert (avg, flag) == (exposure.monthly_mean(t0), "FALLBACK")


def test_open_truck_adds_solar_offset_and_other_vehicles_do_not():
    assert exposure.vehicle_temp(30.0, "OPEN") == (38.0, "OPEN_VEHICLE_V1")
    temp, model = exposure.vehicle_temp(30.0, "REFRIGERATED")
    assert temp == 30.0 and model != "OPEN_VEHICLE_V1"


def test_clamp_marks_out_of_range_temperatures():
    assert exposure.clamp(45.0, 5.0, 40.0) == (40.0, "CLAMPED")
    assert exposure.clamp(1.0, 5.0, 40.0) == (5.0, "CLAMPED")
    assert exposure.clamp(25.0, 5.0, 40.0) == (25.0, None)


def test_rate_follows_q10_and_has_a_floor():
    assert exposure.rate(2.5, 20, 20) == pytest.approx(1.0)
    assert exposure.rate(2.5, 30, 20) == pytest.approx(2.5)  # +10C = Q10 times faster
    assert exposure.rate(2.5, -100, 20) == exposure.RATE_FLOOR


def test_life_consumed_is_proportional_to_time():
    start = NOW
    six = exposure.life_consumed_days(2.5, 20, 30, start, start + timedelta(hours=6))
    twelve = exposure.life_consumed_days(2.5, 20, 30, start, start + timedelta(hours=12))
    assert six == pytest.approx(2.5 * 6 / 24) and twelve == pytest.approx(2 * six)


def test_worst_flag_priority():
    assert exposure.worst_flag(None, "INTERPOLATED", "FALLBACK") == "FALLBACK"
    assert exposure.worst_flag("FALLBACK", "CLAMPED") == "CLAMPED"
    assert exposure.worst_flag(None, None) is None


# ------------------------------------------------------------------ shelf life (Q10)
def recalc(segments, storage_temp=20.0, now=NOW, baseline=7.0):
    return recalculate_estimated(received_at=NOW - 2 * DAY, baseline_life_days=baseline,
                                 segment_days=segments, q10=2.5, ref_temp_c=20.0,
                                 storage_temp_c=storage_temp, now=now)


def test_segments_are_added_so_order_does_not_matter():
    """Golden: hot truck then cold storage == cold storage then hot truck == the sum."""
    hot, cold = 1.2, 0.3
    a = recalc([hot, cold], storage_temp=20)
    b = recalc([cold, hot], storage_temp=20)
    c = recalc([cold], storage_temp=20)
    c_plus_hot = recalc([*[cold], hot], storage_temp=20)  # hot segment added later
    assert a.adjusted_expiry == b.adjusted_expiry == c_plus_hot.adjusted_expiry
    assert a.consumed_days == pytest.approx(1.5)
    assert c.adjusted_expiry > a.adjusted_expiry  # the hot leg cost real life


def test_adjusted_expiry_is_now_plus_remaining_over_storage_rate():
    r = recalc([2.0], storage_temp=30.0)  # rate 2.5, remaining 5 days -> 2 days from now
    assert r.remaining_ref_days == pytest.approx(5.0)
    assert r.adjusted_expiry - NOW == timedelta(days=2)


def test_life_used_up_expires_now():
    r = recalc([9.0])
    assert r.adjusted_expiry == NOW and r.remaining_ref_days < 0


def test_cold_storage_life_is_capped_at_twice_baseline():
    r = recalc([0.1], storage_temp=4.0)  # chilled: rate ~0.23 would give ~30 days
    assert r.cap_applied
    assert r.adjusted_expiry == NOW - 2 * DAY + timedelta(days=7 * LIFE_CAP_MULTIPLE)


def test_trace_steps_show_the_working():
    r = recalc([1.0, 0.5], storage_temp=25.0)
    labels = [s["label"] for s in r.steps]
    assert labels == ["Baseline life", "Life consumed so far", "Remaining at reference temp",
                      "Storage ageing rate", "Adjusted expiry"]
    assert r.steps[1]["value"] == pytest.approx(1.5)
