from __future__ import annotations

import datetime as dt
import json
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq

from apps.paper_trader.backtest_sim import _snapshot_has_required_coverage, _snapshot_needs_refresh


def _write_split(path: Path, event_dates: list[str]) -> None:
    table = pa.table({"event_date": pa.array(event_dates)})
    pq.write_table(table, str(path))


def test_snapshot_refresh_uses_actual_coverage_not_manifest_age(tmp_path: Path) -> None:
    snapshot_id = "snapshot-a"
    snap_dir = tmp_path / snapshot_id
    snap_dir.mkdir(parents=True)
    (snap_dir / "manifest.json").write_text(json.dumps({
        "snapshot_id": snapshot_id,
        "created_at_utc": "2020-01-01T00:00:00+00:00",
    }))
    _write_split(snap_dir / "train.parquet", ["2025-01-03", "2025-06-30"])
    _write_split(snap_dir / "valid.parquet", ["2025-07-01", "2025-09-30"])
    _write_split(snap_dir / "test.parquet", ["2025-10-01", "2025-12-31"])

    end_date = dt.date(2025, 12, 31)

    assert _snapshot_has_required_coverage(snapshot_id, end_date, snapshot_dir=str(tmp_path)) is True
    assert _snapshot_needs_refresh(snapshot_id, end_date, snapshot_dir=str(tmp_path)) is False


def test_snapshot_refresh_triggers_when_coverage_is_missing(tmp_path: Path) -> None:
    snapshot_id = "snapshot-b"
    snap_dir = tmp_path / snapshot_id
    snap_dir.mkdir(parents=True)
    _write_split(snap_dir / "test.parquet", ["2025-10-01", "2025-12-01"])

    end_date = dt.date(2025, 12, 31)

    assert _snapshot_has_required_coverage(snapshot_id, end_date, snapshot_dir=str(tmp_path)) is False
    assert _snapshot_needs_refresh(snapshot_id, end_date, snapshot_dir=str(tmp_path)) is True
