from __future__ import annotations

import json
from pathlib import Path

from apps.web.experiment_baked_sleeves import read_effective_baked_sleeves


def test_read_effective_baked_sleeves_inherits_from_base_config(tmp_path: Path):
    project_root = tmp_path
    backtest_dir = project_root / "configs" / "backtest"
    experiment_dir = project_root / "configs" / "experiments"
    backtest_dir.mkdir(parents=True)
    experiment_dir.mkdir(parents=True)

    base_config = {
        "risk": {"cash_parking_preset": "parking_base"},
        "idle_alpha_sleeve_preset": "idle_base",
        "form4_capture_sleeve_preset": "form4_base",
        "ownership_capture_sleeve_preset": "ownership_base",
        "risk_off_alpha_sleeve_preset": "riskoff_base",
    }
    (backtest_dir / "base.json").write_text(json.dumps(base_config))

    manifest = {
        "experiment_name": "exp_a",
        "dataset_snapshot_id": "snapshot",
        "base_config": "configs/backtest/base.json",
        "overrides": {
            "risk": {"cash_parking_preset": "parking_override"},
            "idle_alpha_sleeve_preset": "idle_override",
        },
        "strategy_engines": [],
        "splits": [],
        "tags": [],
    }
    config_path = experiment_dir / "exp_a.json"
    config_path.write_text(json.dumps(manifest))

    assert read_effective_baked_sleeves(config_path, project_root) == {
        "parking": "parking_override",
        "idle_alpha": "idle_override",
        "form4_sleeve": "form4_base",
        "ownership_sleeve": "ownership_base",
        "risk_off_sleeve": "riskoff_base",
    }


def test_read_effective_baked_sleeves_respects_explicit_null_override(tmp_path: Path):
    project_root = tmp_path
    runs_dir = project_root / "runs" / "example_run"
    experiment_dir = project_root / "configs" / "experiments"
    runs_dir.mkdir(parents=True)
    experiment_dir.mkdir(parents=True)

    resolved_config = {
        "risk": {"cash_parking_preset": "parking_base"},
        "idle_alpha_sleeve_preset": "idle_base",
        "form4_capture_sleeve_preset": "form4_base",
        "ownership_capture_sleeve_preset": "ownership_base",
        "risk_off_alpha_sleeve_preset": "riskoff_base",
    }
    (runs_dir / "resolved_config.json").write_text(json.dumps(resolved_config))

    manifest = {
        "experiment_name": "exp_b",
        "dataset_snapshot_id": "snapshot",
        "base_config": "runs/example_run/resolved_config.json",
        "overrides": {
            "form4_capture_sleeve_preset": None,
        },
        "strategy_engines": [],
        "splits": [],
        "tags": [],
    }
    config_path = experiment_dir / "exp_b.json"
    config_path.write_text(json.dumps(manifest))

    assert read_effective_baked_sleeves(config_path, project_root) == {
        "parking": "parking_base",
        "idle_alpha": "idle_base",
        "form4_sleeve": None,
        "ownership_sleeve": "ownership_base",
        "risk_off_sleeve": "riskoff_base",
    }
