from __future__ import annotations

from datetime import datetime, timedelta, timezone

import polars as pl

from uforia.config import AppConfig, ModelingConfig
from uforia.signals import compute_qvvix
from uforia.storage import DatasetName, DatasetStore


def test_compute_qvvix_from_history(tmp_path) -> None:
    store = DatasetStore(tmp_path)
    start = datetime(2025, 9, 1, tzinfo=timezone.utc)
    feature_rows = []
    vol_rows = []
    for hour in range(24 * 10):
        ts = start + timedelta(hours=hour)
        feature_rows.append(
            {
                "ts": ts,
                "date": ts.date(),
                "underlying": "BTC",
                "source": "ssvi",
                "atm_iv_7d": 0.5 + 0.001 * (hour % 12),
                "atm_iv_14d": 0.52 + 0.001 * (hour % 10),
                "atm_iv_30d": 0.55 + 0.001 * (hour % 8),
                "atm_iv_60d": 0.58 + 0.001 * (hour % 6),
                "rr_25_7d": -0.05 + 0.0001 * hour,
                "rr_25_30d": -0.03 + 0.0001 * hour,
                "bf_25_7d": 0.02 + 0.00005 * hour,
                "bf_25_30d": 0.03 + 0.00004 * hour,
                "term_slope_7_30": -0.05,
                "term_slope_30_60": -0.03,
                "fit_quality": 0.001,
                "coverage_ratio": 0.8,
                "maturity_violations": 0,
                "fit_validity_flag": "ok",
                "quality_flag": "ok",
            }
        )
        vol_rows.append(
            {
                "ts": ts,
                "date": ts.date(),
                "underlying": "BTC",
                "source": "dvol",
                "value": 55.0 + 0.01 * hour,
                "quality_flag": "ok",
            }
        )
    store.write(DatasetName.SURFACE_FEATURES, pl.DataFrame(feature_rows))
    store.write(DatasetName.VOL_INDEX_SERIES, pl.DataFrame(vol_rows))
    config = AppConfig(modeling=ModelingConfig(qvvix_paths=32))
    value = compute_qvvix(
        store,
        start + timedelta(hours=(24 * 10) - 1),
        underlying="BTC",
        config=config,
    )
    assert value >= 0
