from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path

import polars as pl

from uforia.storage import DatasetName, DatasetStore, RunStatus


def test_compact_reduces_runs_to_single_latest_partition_file(tmp_path) -> None:
    store = DatasetStore(tmp_path)
    ts = datetime(2026, 3, 9, 15, tzinfo=timezone.utc)
    for value, run_id, minute in ((55.0, "run-1", 1), (56.0, "run-2", 2)):
        store.write(
            DatasetName.DVOL_SNAPSHOT,
            pl.DataFrame(
                [
                    {
                        "ts": ts,
                        "date": ts.date(),
                        "venue": "deribit",
                        "underlying": "BTC",
                        "source": "dvol",
                        "dvol_open": value,
                        "dvol_high": value,
                        "dvol_low": value,
                        "dvol_close": value,
                        "quality_flag": "ok",
                    }
                ]
            ),
            run_id=run_id,
            run_ts=ts.replace(minute=minute),
            status=RunStatus.SUCCESS,
        )

    result = store.compact(
        DatasetName.DVOL_SNAPSHOT,
        start_date=ts.date(),
        end_date=ts.date(),
        filters={"underlying": "BTC"},
    )

    latest = store.read(DatasetName.DVOL_SNAPSHOT, filters={"underlying": "BTC"})

    assert result["partitions"] == 1
    assert result["rows"] == 1
    assert result["deleted_files"] == 0
    assert latest.height == 1
    assert latest.item(0, "dvol_close") == 56.0


def test_compact_is_a_memory_only_deduplication_pass(tmp_path) -> None:
    store = DatasetStore(tmp_path)
    ts = datetime(2026, 3, 9, 15, tzinfo=timezone.utc)
    store.write(
        DatasetName.DVOL_SNAPSHOT,
        pl.DataFrame(
            [
                {
                    "ts": ts,
                    "date": ts.date(),
                    "venue": "deribit",
                    "underlying": "BTC",
                    "source": "dvol",
                    "dvol_open": 55.0,
                    "dvol_high": 55.0,
                    "dvol_low": 55.0,
                    "dvol_close": 55.0,
                    "quality_flag": "ok",
                }
            ]
        ),
        run_id="run-1",
        run_ts=ts.replace(minute=1),
        status=RunStatus.SUCCESS,
    )

    result = store.compact(
        DatasetName.DVOL_SNAPSHOT,
        start_date=ts.date(),
        end_date=ts.date(),
        filters={"underlying": "BTC"},
    )

    latest = store.read(DatasetName.DVOL_SNAPSHOT, filters={"underlying": "BTC"})

    assert result["partitions"] == 1
    assert result["rows"] == 1
    assert result["deleted_files"] == 0
    assert latest.height == 1


def test_compact_ignores_malformed_partition_dates(tmp_path) -> None:
    store = DatasetStore(tmp_path)
    ts = datetime(2026, 3, 9, 15, tzinfo=timezone.utc)
    store.write(
        DatasetName.RAZOR_SERIES,
        pl.DataFrame(
            [
                {
                    "ts": ts,
                    "date": ts.date(),
                    "underlying": "BTC",
                    "source": "synthetic_7d_atm",
                    "reference_tenor_days": 7,
                    "razor_pnl": 1.0,
                    "razor_vrp": 1.0,
                    "buyer_increment": 0.1,
                    "seller_increment": -0.1,
                    "option_reval_pnl": 0.05,
                    "hedge_pnl": 0.03,
                    "roll_pnl": 0.02,
                    "razor_pnl_zscore": 0.0,
                    "razor_vrp_zscore": 0.0,
                    "trade_band": "neutral",
                    "long_vol_signal": False,
                    "short_vol_signal": False,
                    "quality_flag": "ok",
                }
            ]
        ),
    )
    malformed = (
        Path(tmp_path)
        / "razor_series"
        / "underlying=None"
        / "source=synthetic_7d_atm"
        / "date=None"
    )
    malformed.mkdir(parents=True, exist_ok=True)
    (malformed / "junk.parquet").write_bytes(b"not-a-real-parquet-file")

    result = store.compact(
        DatasetName.RAZOR_SERIES,
        start_date=ts.date(),
        end_date=ts.date(),
        filters={"underlying": "BTC"},
    )

    assert result["partitions"] == 1
