"""ExecutionStore raises ExecutionStoreCorruptError on corrupt JSON files."""
from __future__ import annotations

import json
import pytest
from pathlib import Path

from recoil.core.exceptions import ExecutionStoreCorruptError
from recoil.execution.execution_store import ExecutionStore


class TestCorruptShotRaises:
    def test_read_shot_file_raises_on_corrupt_json(self, tmp_path: Path):
        shots_dir = tmp_path / "shots"
        shots_dir.mkdir(parents=True, exist_ok=True)
        store = ExecutionStore(db_path=shots_dir)
        bad = shots_dir / "BAD_SH01.json"
        bad.write_text("this is not json {{{", encoding="utf-8")
        with pytest.raises(ExecutionStoreCorruptError) as ei:
            store._read_shot_file("BAD_SH01")
        assert "BAD_SH01" in str(ei.value)

    def test_load_all_raises_on_corrupt_json(self, tmp_path: Path):
        shots_dir = tmp_path / "shots"
        shots_dir.mkdir(parents=True, exist_ok=True)
        store = ExecutionStore(db_path=shots_dir)
        good = {"shot_id": "GOOD_SH01", "schema_version": 1}
        (shots_dir / "GOOD_SH01.json").write_text(json.dumps(good), encoding="utf-8")
        (shots_dir / "BAD_SH02.json").write_text("not json", encoding="utf-8")
        with pytest.raises(ExecutionStoreCorruptError):
            store._load_all()

    def test_missing_file_returns_none(self, tmp_path: Path):
        """Missing file (not corrupt) is still None — only decode errors raise."""
        shots_dir = tmp_path / "shots"
        shots_dir.mkdir(parents=True, exist_ok=True)
        store = ExecutionStore(db_path=shots_dir)
        assert store._read_shot_file("MISSING_SH99") is None
