"""
test_task_md_preservation_2569.py
MT-T1: RC-4 + AD-4 검증
  - protection-list.json에 task 관련 경로 포함
  - cleanup-workspace.py is_protected() 정상 동작
  - file_cleanup.py SafetyChecker.is_protected() 정상 동작
  - dispatch/__init__.py에 intent-to-add 호출 4회 이상 존재 (정적 검증)
"""
import importlib.util
import json
import sys
from pathlib import Path

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


# ── 헬퍼: cleanup-workspace.py 로드 (파일명에 하이픈 포함) ────────────────────

def _load_cleanup_workspace():
    """importlib으로 cleanup-workspace.py 동적 로드."""
    module_path = WORKSPACE / "scripts" / "cleanup-workspace.py"
    spec = importlib.util.spec_from_file_location("cleanup_workspace", module_path)
    assert spec is not None and spec.loader is not None, f"spec 로드 실패: {module_path}"
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


# ── 테스트 1: protection-list.json 경로 포함 확인 ─────────────────────────────

def test_protection_list_includes_task_paths():
    """memory/specs/protection-list.json에 task 관련 보호 경로가 모두 포함되어야 한다."""
    plist_path = WORKSPACE / "memory" / "specs" / "protection-list.json"
    assert plist_path.exists(), f"protection-list.json 없음: {plist_path}"

    data = json.loads(plist_path.read_text(encoding="utf-8"))
    protected_paths: list = data.get("protected_paths", [])

    required_prefixes = [
        "memory/tasks/",
        "memory/plans/tasks/",
        "memory/reports/",
        "memory/specs/",
    ]
    for required in required_prefixes:
        # trailing slash 유무 무시하여 매칭
        normalized = required.rstrip("/")
        found = any(
            entry.rstrip("/") == normalized or entry.rstrip("/").startswith(normalized)
            for entry in protected_paths
        )
        assert found, (
            f"protection-list.json protected_paths에 '{required}' 없음. "
            f"현재 목록: {protected_paths}"
        )


# ── 테스트 2: cleanup-workspace.py is_protected() — task md 경로 ──────────────

def test_cleanup_workspace_is_protected_for_task_md():
    """cleanup-workspace.py is_protected()가 memory/tasks/task-9999.md → True 반환."""
    # _PROTECTION_CACHE를 초기화하여 실제 JSON 로드 보장
    cw = _load_cleanup_workspace()
    setattr(cw, "_PROTECTION_CACHE", None)  # 캐시 클리어

    task_md_path = WORKSPACE / "memory" / "tasks" / "task-9999.md"
    result = cw.is_protected(task_md_path, WORKSPACE)
    assert result is True, (
        f"is_protected()가 {task_md_path}에 대해 False를 반환했습니다. "
        "protection-list.json 또는 is_protected() 구현을 확인하세요."
    )


# ── 테스트 3: file_cleanup.py SafetyChecker.is_protected() — task md ──────────

def test_file_cleanup_is_protected_for_task_md():
    """file_cleanup.py SafetyChecker.is_protected()가 memory/tasks/task-X.md → True."""
    scripts_dir = str(WORKSPACE / "scripts")
    if scripts_dir not in sys.path:
        sys.path.insert(0, scripts_dir)

    import file_cleanup  # type: ignore[import]

    checker = file_cleanup.SafetyChecker(WORKSPACE)
    task_md_path = WORKSPACE / "memory" / "tasks" / "task-9999.md"
    result = checker.is_protected(task_md_path)
    assert result is True, (
        f"SafetyChecker.is_protected()가 {task_md_path}에 대해 False를 반환했습니다."
    )


# ── 테스트 4: dispatch/__init__.py에 intent-to-add 4회 이상 ──────────────────

def test_dispatch_intent_to_add_called():
    """dispatch/__init__.py에 'intent-to-add' 문자열이 4회 이상 등장해야 한다 (정적 검증)."""
    dispatch_init = WORKSPACE / "dispatch" / "__init__.py"
    assert dispatch_init.exists(), f"dispatch/__init__.py 없음: {dispatch_init}"

    content = dispatch_init.read_text(encoding="utf-8")
    count = content.count("intent-to-add")
    assert count >= 4, (
        f"dispatch/__init__.py에 'intent-to-add' 등장 횟수: {count} (최소 4회 필요). "
        "RC-4 intent-to-add 구현을 확인하세요."
    )
