"""tests/lifecycle_guards/test_self_application.py — Group 8 (1건, §8.A-14).

task-2472 regression: drink-your-own-champagne 메타 테스트.
task-2473에서 task-2471+1 hardening이 raw shell bypass에 우회된 사실 박제
+ 동일 우회 차단 확인.

24. test_drink_your_own_champagne_meta_regression
"""
from __future__ import annotations

import importlib.util
import json
import re
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


em = _load("escalation_marker_g8", "scripts/escalation_marker.py")


# ---------------------------------------------------------------------------
# Test 24: drink-your-own-champagne 메타 regression
# ---------------------------------------------------------------------------

def test_drink_your_own_champagne_meta_regression(tmp_path, monkeypatch):
    """task-2472 hardening이 자기 자신에게 적용되는지 검증.

    시나리오:
    1. raw `: > /tmp/task-X.done.escalated` 시도 → escalation_marker.py가 거부
    2. finish-task.sh에 escalation_marker.py 호출이 있는지 grep 검증
    3. done-watcher.sh에 raw `: >` 패턴 0건 검증
    """
    # --- 시나리오 1: raw bypass 시도 → escalation_marker.py가 올바르게 거부 ---
    # escalation_marker.py의 EVENTS_DIR/AUDIT_DIR을 tmp_path로 override
    monkeypatch.setattr(em, "EVENTS_DIR", tmp_path / "events")
    monkeypatch.setattr(em, "AUDIT_DIR", tmp_path / "audit")
    monkeypatch.setattr(em, "ESCALATION_AUDIT_PATH", tmp_path / "audit" / "state-recovery.jsonl")

    (tmp_path / "events").mkdir(parents=True, exist_ok=True)
    (tmp_path / "audit").mkdir(parents=True, exist_ok=True)

    # 정상 emit: 필수 필드 모두 있음 → ok=True (raw bypass가 아닌 Python 경로)
    result_ok = em.emit_escalation(
        task_id="task-2472-heimdall-meta",
        kind="escalated",
        reason="L1 meta regression smoke",
        source="test",
        blocking_condition="meta_test_validation",
        evidence_path="/dev/null",
    )
    assert result_ok["ok"] is True, f"정상 emit 실패: {result_ok}"

    # 생성된 마커 파일 검증: JSON payload, 필수 필드 존재
    marker_path = tmp_path / "events" / "task-2472-heimdall-meta.done.escalated"
    assert marker_path.exists(), "정상 emit 후 마커 파일이 없음"
    content = json.loads(marker_path.read_bytes())
    for field in ("reason", "ts", "task_id", "source", "blocking_condition", "evidence_path"):
        assert field in content, f"마커 파일에 필수 필드 '{field}' 없음"
    assert marker_path.stat().st_size > 0, "마커 파일이 0-byte (raw emit 의심)"

    # raw bypass 시도 시뮬레이션: reason="" → 거부 확인
    result_raw_bypass = em.emit_escalation(
        task_id="task-2472-raw-bypass-attempt",
        kind="escalated",
        reason="",   # 빈 문자열 → raw bypass 패턴
        source="shell_bypass",
        blocking_condition="",
        evidence_path="",
    )
    assert result_raw_bypass["ok"] is False, (
        "raw bypass 시도 (빈 payload) → escalation_marker.py가 거부해야 함"
    )
    # raw bypass 마커가 생성되지 않아야 함
    bypass_marker = tmp_path / "events" / "task-2472-raw-bypass-attempt.done.escalated"
    assert not bypass_marker.exists(), "raw bypass 거부 후 마커 파일이 생성되면 안 됨"

    # --- 시나리오 2: finish-task.sh에 escalation_marker.py 호출 확인 ---
    finish_task_sh = WORKTREE / "scripts" / "finish-task.sh"
    assert finish_task_sh.exists(), "finish-task.sh 없음"
    ft_content = finish_task_sh.read_text(encoding="utf-8")

    # BLOCKED/ESCALATED case에 escalation_marker.py 호출이 있어야 함
    assert "escalation_marker.py" in ft_content, (
        "finish-task.sh에 escalation_marker.py 호출 없음 — task-2472 구현 누락"
    )

    # raw `: > ` 패턴이 없어야 함 (task-2473 우회 패턴 차단 확인)
    raw_emit_pattern = re.compile(
        r"^\s*:\s*>\s*.*\.done\.(escalated|blocked)",
        re.MULTILINE,
    )
    raw_matches = raw_emit_pattern.findall(ft_content)
    assert len(raw_matches) == 0, (
        f"finish-task.sh에 raw emit 패턴 {len(raw_matches)}건 잔존 — "
        "task-2473에서 발생한 동일 우회가 차단되지 않음"
    )

    # --- 시나리오 3: done-watcher.sh에 raw `: >` 패턴 0건 검증 ---
    done_watcher_sh = WORKTREE / "scripts" / "done-watcher.sh"
    assert done_watcher_sh.exists(), "done-watcher.sh 없음"
    dw_content = done_watcher_sh.read_text(encoding="utf-8")

    # done-watcher.sh에도 raw emit 0건
    dw_raw_matches = raw_emit_pattern.findall(dw_content)
    assert len(dw_raw_matches) == 0, (
        f"done-watcher.sh에 raw emit 패턴 {len(dw_raw_matches)}건 잔존 — task-2472 위반"
    )

    # task-2473 증거 박제: sanity check 기록이 있는지 (done-watcher.sh)
    assert "escalation_marker.py" in dw_content or "task-2472" in dw_content, (
        "done-watcher.sh에 task-2472 hardening 적용 흔적 없음 "
        "(escalation_marker.py 또는 task-2472 주석 없음)"
    )
