"""REC-232: generate_previs must fail loud on a corrupt-but-present global
bible instead of silently dropping all location enrichment.

The `_load_bible` helper encapsulates the exact load logic the previs entry
point uses. These tests pin its three-way contract:
  - bible absent   -> None (previs degrades gracefully — unchanged behavior)
  - bible valid    -> parsed dict
  - bible corrupt  -> WorkspaceStateCorruptError (the REC-232 fix)
"""

import json

import pytest

from recoil.core.exceptions import WorkspaceStateCorruptError
from recoil.core.paths import ProjectPaths
from recoil.pipeline.tools import generate_previs


def _bible_path(project_root):
    return ProjectPaths.from_root(project_root).global_bible_path


@pytest.fixture
def project(tmp_path, monkeypatch):
    """A synthetic project whose global_bible_path lives under tmp_path."""
    monkeypatch.setattr(
        ProjectPaths, "for_project", classmethod(lambda cls, p: cls.from_root(tmp_path))
    )
    bp = _bible_path(tmp_path)
    bp.parent.mkdir(parents=True, exist_ok=True)
    return tmp_path


def test_missing_bible_returns_none(project):
    assert generate_previs._load_bible("tartarus") is None


def test_valid_bible_returns_dict(project):
    _bible_path(project).write_text(json.dumps({"locations": {"a": 1}}))
    bible = generate_previs._load_bible("tartarus")
    assert bible == {"locations": {"a": 1}}


def test_corrupt_bible_raises(project):
    # Present but malformed JSON — the case that previously parsed to None
    # silently and dropped enrichment.
    _bible_path(project).write_text("{not valid json,,,")
    with pytest.raises(WorkspaceStateCorruptError):
        generate_previs._load_bible("tartarus")
