# -*- coding: utf-8 -*-
"""task-2644 regression: callback_adjudicator × 8 fixture."""
from __future__ import annotations

import sys
from pathlib import Path

import pytest

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from _fx_loader import load_fixture  # noqa: E402

from utils import callback_adjudicator  # noqa: E402


def test_fixture_collected_count(all_fixtures):
    assert len(all_fixtures) == 8, "8 fixture 모두 로드되어야 한다"


def test_adjudicate_terminal_state(fx):
    """envelope 가 있을 때 adjudicator 가 expected terminal_state 와 일치한다."""
    env = fx["envelope"]
    if env is None:
        pytest.skip("no envelope (ledger-only fixture)")
    adj = callback_adjudicator.adjudicate(env)
    expected = fx["expected"]
    if "terminal_state" in (expected or {}):
        assert adj["terminal_state"] == expected["terminal_state"], (
            f"{fx['name']}: terminal_state mismatch — adj={adj['terminal_state']} "
            f"expected={expected['terminal_state']}"
        )


def test_adjudicate_policy_class(fx):
    env = fx["envelope"]
    expected = fx["expected"]
    if env is None or "policy_class" not in (expected or {}):
        pytest.skip("no policy_class assertion for this fixture")
    adj = callback_adjudicator.adjudicate(env)
    assert adj["policy_class"] == expected["policy_class"], (
        f"{fx['name']}: policy mismatch — adj={adj['policy_class']} "
        f"expected={expected['policy_class']}"
    )


def test_critical7_detection_for_critical7_fixture():
    fx = load_fixture("critical7")
    env = fx["envelope"]
    assert callback_adjudicator.detect_critical7(env) is True
    assert callback_adjudicator.detect_chair_report_required(env) is not None


def test_merge_ready_policy_lock():
    fx = load_fixture("merge_ready")
    adj = callback_adjudicator.adjudicate(fx["envelope"])
    # 보강-3 hardcoded: MERGE_READY → MERGE_POLICY_LOCK
    assert adj["terminal_state"] == "MERGE_READY"
    assert adj["policy_class"] == "MERGE_POLICY_LOCK"
    assert adj["merge_ready"] is True


def test_fallback_1c0f6f52_not_control_plane_compliant():
    fx = load_fixture(
        "fallback_safety_net_log_recovery_without_control_plane_adjudication"
    )
    env = fx["envelope"]
    adj = callback_adjudicator.adjudicate(env)
    assert adj["terminal_state"] == "NOT_CONTROL_PLANE_COMPLIANT", (
        "1C0F6F52 fixture 는 envelope 회수 + status=ok chain 만 본 경우 "
        "NOT_CONTROL_PLANE_COMPLIANT 분류되어야 한다"
    )


def test_validate_adjudication_passes_for_well_formed_fixtures(all_fixtures):
    for fx in all_fixtures:
        if fx["envelope"] is None:
            continue
        adj = callback_adjudicator.adjudicate(fx["envelope"])
        failures = callback_adjudicator.validate_adjudication(adj)
        # MERGE_READY 는 반드시 MERGE_POLICY_LOCK 정합 → 위반 없음
        if adj["terminal_state"] == "MERGE_READY":
            assert "MERGE_READY_WITHOUT_POLICY_LOCK" not in failures
