"""tests/regression/test_done_escalated_coexistence.py — Group 7 (1건).

task-2472 regression: .done + .done.escalated 동시 존재 → DONE reject.

23. test_done_and_done_escalated_coexistence_rejects_done
"""
from __future__ import annotations

import importlib.util
import sys
from pathlib import Path

WORKTREE = Path(__file__).resolve().parents[2]


def _load(mod_name: str, rel: str):
    path = WORKTREE / rel
    spec = importlib.util.spec_from_file_location(mod_name, str(path))
    assert spec is not None and spec.loader is not None, f"spec load 실패: {path}"
    mod = importlib.util.module_from_spec(spec)
    sys.modules[mod_name] = mod
    spec.loader.exec_module(mod)
    return mod


scg = _load("silent_corruption_guard_g7", "utils/silent_corruption_guard.py")


# ---------------------------------------------------------------------------
# Test 23: .done + .done.escalated 동시 존재 → check_done_escalated_coexistence ok=False
# ---------------------------------------------------------------------------

def test_done_and_done_escalated_coexistence_rejects_done(tmp_path):
    """.done + .done.escalated 둘 다 존재하면 check_done_escalated_coexistence → ok=False."""
    task_id = "task-coexist-23"

    # events 디렉토리 생성
    events_dir = tmp_path / "memory" / "events"
    events_dir.mkdir(parents=True, exist_ok=True)

    # .done 파일 생성 (정상 완료 마커)
    done_path = events_dir / f"{task_id}.done"
    done_path.write_text("done", encoding="utf-8")

    # .done.escalated 파일 동시 생성 (silent corruption 상태)
    escalated_path = events_dir / f"{task_id}.done.escalated"
    escalated_path.write_text(
        '{"reason":"test","ts":"2026-05-07T00:00:00Z","task_id":"task-coexist-23",'
        '"source":"test","blocking_condition":"test","evidence_path":"/dev/null"}',
        encoding="utf-8",
    )

    # 동시 존재 → ok=False
    result = scg.check_done_escalated_coexistence(task_id, workspace=tmp_path)

    assert result["ok"] is False, (
        ".done + .done.escalated 동시 존재 시 DONE 인정 불가 — ok=False 필수"
    )
    assert result["detail"]["done_exists"] is True
    assert result["detail"]["escalated_exists"] is True
    assert "동시 존재" in result["reason"] or "coexist" in result["reason"].lower()

    # .done만 있을 때는 OK
    escalated_path.unlink()
    result_ok = scg.check_done_escalated_coexistence(task_id, workspace=tmp_path)
    assert result_ok["ok"] is True, ".done만 있으면 PASS 필수"

    # .done.escalated만 있을 때도 OK (done은 없음)
    done_path.unlink()
    escalated_path.write_text("x", encoding="utf-8")
    result_escalated_only = scg.check_done_escalated_coexistence(task_id, workspace=tmp_path)
    assert result_escalated_only["ok"] is True, ".done.escalated만 있으면 PASS 필수"
