from __future__ import annotations

import json
from pathlib import Path

import pytest

from libs.backtest.snapshots import (
    UnknownSnapshotError,
    canonical_snapshot_dir,
    get_requested_aliases,
    resolve_snapshot,
    resolve_snapshot_path,
)


def test_resolve_snapshot_alias_to_main_canonical() -> None:
    resolution = resolve_snapshot("midlarge-liquid-long-v1_bucketfix_full_audit_tier3")
    assert resolution.requested_snapshot_id == "midlarge-liquid-long-v1_bucketfix_full_audit_tier3"
    assert resolution.canonical_snapshot_id == "midlarge-liquid-long-v1_bucketfix_full_audit_canonical"
    assert resolution.is_alias is True
    assert resolution.is_registry_managed is True


def test_resolve_snapshot_canonical_passthrough() -> None:
    resolution = resolve_snapshot("midlarge-liquid-long-v1_bucketfix_full_audit_canonical")
    assert resolution.requested_snapshot_id == resolution.canonical_snapshot_id
    assert resolution.is_alias is False
    assert resolution.is_registry_managed is True


def test_resolve_snapshot_unknown_raises() -> None:
    with pytest.raises(UnknownSnapshotError, match="Unknown snapshot id"):
        resolve_snapshot("totally_unknown_snapshot_for_unit_test")


def test_resolve_snapshot_path_prefers_canonical_then_requested_fallback(tmp_path: Path, monkeypatch) -> None:
    parquet_root = tmp_path / "parquet"
    canonical_dir = parquet_root / "midlarge-liquid-long-v1_bucketfix_full_audit_canonical"
    requested_dir = parquet_root / "midlarge-liquid-long-v1_bucketfix_full_audit_tier3"
    requested_dir.mkdir(parents=True)
    (requested_dir / "manifest.json").write_text(json.dumps({"snapshot_id": requested_dir.name}))

    path = resolve_snapshot_path(
        "midlarge-liquid-long-v1_bucketfix_full_audit_tier3",
        snapshot_dir=parquet_root,
    )
    assert path == requested_dir.resolve()

    canonical_dir.mkdir(parents=True)
    (canonical_dir / "manifest.json").write_text(json.dumps({"snapshot_id": canonical_dir.name}))
    path = resolve_snapshot_path(
        "midlarge-liquid-long-v1_bucketfix_full_audit_tier3",
        snapshot_dir=parquet_root,
    )
    assert path == canonical_dir.resolve()


def test_get_requested_aliases_lists_main_family() -> None:
    aliases = get_requested_aliases("midlarge-liquid-long-v1_bucketfix_full_audit_canonical")
    assert "midlarge-liquid-long-v1_bucketfix_full_audit_tier3" in aliases
    assert "midlarge-liquid-long-v1_bucketfix_full_audit_tier3tech" in aliases


def test_canonical_snapshot_dir_uses_parquet_root(tmp_path: Path, monkeypatch) -> None:
    from libs.backtest import snapshots

    monkeypatch.setattr(
        snapshots,
        "get_settings",
        lambda: type("S", (), {"parquet_dir": str(tmp_path / "parquet")})(),
    )
    assert canonical_snapshot_dir("abc").as_posix().endswith("/parquet/abc")
