"""Tests for the REC-181 SPATIAL_COHERENCE critic fix (reads sibling spatial_data + cut_relation)."""
from __future__ import annotations

from recoil.pipeline._lib.critics import FailureMode
from recoil.pipeline._lib.critics.plan_pass_critic import PlanPassCritic

_SKEL = {"subject_line": "a", "environment_line": "b", "action_line": "c",
         "motion_line": "d e", "emotion_line": "f"}


def _shot(shot_id, scene_index, side, seg, cut_relation, *, sibling=True):
    sd = {"camera_side": side, "axis_segment_id": seg, "cut_relation": cut_relation}
    shot = {"shot_id": shot_id, "scene_index": scene_index,
            "prompt_data": {"prompt_skeleton": dict(_SKEL)}}
    if sibling:
        shot["spatial_data"] = sd
    else:
        # OLD dead path only — sibling spatial_data absent
        shot["prompt_data"]["spatial_data"] = sd
    return shot


def _spatial_dim(prev, cur):
    critic = PlanPassCritic(bible={}, all_shots=[prev, cur], shot_id=cur["shot_id"])
    dims = critic.evaluate(cur, {})
    return next(d for d in dims if d.name == "SPATIAL_COHERENCE")


def test_unlicensed_crossing_fails():
    prev = _shot("EP001_SH01", 1, "A", 0, "scene_open")
    cur = _shot("EP001_SH02", 1, "B", 0, "consistent")  # flip within same segment, no license
    dim = _spatial_dim(prev, cur)
    assert dim.passed is False
    assert dim.failure_mode == FailureMode.COVERAGE_GEOMETRY_BROKEN


def test_licensed_jump_passes():
    prev = _shot("EP001_SH01", 1, "A", 0, "scene_open")
    cur = _shot("EP001_SH02", 1, "B", 0, "intentional_jump")  # flip IS licensed
    assert _spatial_dim(prev, cur).passed is True


def test_reestablish_new_segment_passes():
    prev = _shot("EP001_SH01", 1, "A", 0, "scene_open")
    cur = _shot("EP001_SH02", 1, "A", 1, "re_establish")  # new segment
    assert _spatial_dim(prev, cur).passed is True


def test_dead_path_not_consulted():
    # sibling spatial_data ABSENT (only the old prompt_data.spatial_data set) -> no crossing reported
    prev = _shot("EP001_SH01", 1, "A", 0, "scene_open", sibling=False)
    cur = _shot("EP001_SH02", 1, "B", 0, "consistent", sibling=False)
    assert _spatial_dim(prev, cur).passed is True
