from __future__ import annotations

import pytest

from recoil.pipeline._lib import dispatch_payload as dp
from recoil.pipeline._lib.plan_loader import CanonicalShot


@pytest.fixture(autouse=True)
def _clear_project_config_cache(monkeypatch: pytest.MonkeyPatch) -> None:
    dp._project_config_cache.clear()
    monkeypatch.delenv("RECOIL_USE_COMPOSITE_SHEETS", raising=False)
    yield
    dp._project_config_cache.clear()


def _shot() -> CanonicalShot:
    raw = {
        "shot_id": "EP001_SH01",
        "scene_index": 1,
        "duration_s": 3.0,
        "asset_data": {"location_id": "int_lower_decks_corridor", "characters": []},
        "prompt_data": {"shot_type": "WS"},
    }
    return CanonicalShot(
        shot_id="EP001_SH01",
        scene_index=1,
        sequence_id=None,
        pipeline="video",
        previs_model="gemini-3-pro-image-preview",
        video_model="seeddance-2.0",
        location_id="int_lower_decks_corridor",
        characters=[],
        shot_type="WS",
        duration_s=3.0,
        is_env_only=True,
        has_dialogue=False,
        aspect_ratio="9:16",
        raw=raw,
    )


def test_composite_sheets_load_failure_does_not_poison_cache(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def _raise(_project: str) -> dict:
        raise RuntimeError("binding validation failed")

    monkeypatch.setattr(dp, "load_project_config", _raise)

    assert dp._composite_sheets_enabled("tartarus") is False
    assert "tartarus" not in dp._project_config_cache


def test_composite_sheets_success_after_failure_populates_cache_and_honors_flag(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def _raise(_project: str) -> dict:
        raise RuntimeError("binding validation failed")

    monkeypatch.setattr(dp, "load_project_config", _raise)
    assert dp._composite_sheets_enabled("tartarus") is False
    assert "tartarus" not in dp._project_config_cache

    real_config = {"use_composite_sheets": True}
    monkeypatch.setattr(dp, "load_project_config", lambda _project: real_config)

    assert dp._composite_sheets_enabled("tartarus") is True
    assert dp._project_config_cache["tartarus"] == real_config


def test_author_bootstrap_config_load_failure_raises_without_caching_empty_config(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    def _raise(_project: str) -> dict:
        raise RuntimeError("binding validation failed")

    monkeypatch.setattr(dp, "load_project_config", _raise)

    with pytest.raises(RuntimeError, match="binding validation failed"):
        dp.build_dispatch_payload(
            shot=_shot(),
            project="tartarus",
            modality="r2v_multi",
            model_override="seeddance-2.0",
            dry_run=True,
            force_no_refs=True,
        )

    assert "tartarus" not in dp._project_config_cache
