"""
통합 테스트: _create_task_docs + three_docs_check.verify E2E 라이프사이클
task-1837_5.1 - 엔키 작성

흐름:
1. _create_task_docs로 3문서 생성 (mock 템플릿 사용)
2. 생성된 파일 존재 확인
3. three_docs_check.verify()로 검증 → WARN (status=draft)
4. plan.md status를 completed로 수정 후 → PASS
5. 디렉토리 없으면 → SKIP
6. 파일 누락 시 → FAIL
"""

import sys
from pathlib import Path

sys.path.insert(0, "/home/jay/workspace")

# 템플릿 내용 상수 (실제 템플릿 파일 구조와 동일)
_PLAN_TEMPLATE = """\
---
task_id: {task_id}
type: plan
scope: task
created: {date}
updated: {date}
status: draft
---

# 계획서: {task_id}
## 목표
테스트용 계획서
## 범위
테스트 범위
## 검증 기준
테스트 기준
"""

_CONTEXT_TEMPLATE = """\
---
task_id: {task_id}
type: context
scope: task
created: {date}
updated: {date}
status: draft
---

# 맥락 노트: {task_id}
## 결정 근거
테스트 결정 근거
"""

_CHECKLIST_TEMPLATE = """\
---
task_id: {task_id}
type: checklist
scope: task
created: {date}
updated: {date}
status: draft
---

# 체크리스트: {task_id}
## Phase 1
- [x] A. 작업 항목 완료
- [x] B. 작업 항목 완료
"""


def _setup_templates(tmp_path: Path) -> None:
    """tmp_path 아래 템플릿 디렉토리와 파일을 생성한다."""
    tmpl_dir = tmp_path / "prompts" / "templates" / "task-docs"
    tmpl_dir.mkdir(parents=True, exist_ok=True)
    (tmpl_dir / "plan.template.md").write_text(_PLAN_TEMPLATE, encoding="utf-8")
    (tmpl_dir / "context-notes.template.md").write_text(_CONTEXT_TEMPLATE, encoding="utf-8")
    (tmpl_dir / "checklist.template.md").write_text(_CHECKLIST_TEMPLATE, encoding="utf-8")


def _create_docs(tmp_path: Path, task_id: str, monkeypatch=None) -> Path:
    """dispatch._create_task_docs를 tmp_path WORKSPACE로 호출하고 결과 디렉토리를 반환한다."""
    import dispatch as _d

    if monkeypatch is not None:
        monkeypatch.setattr(_d, "WORKSPACE", tmp_path)
    else:
        _d.WORKSPACE = tmp_path
    result = _d._create_task_docs(task_id, level=3)
    assert result is not None, "_create_task_docs가 None을 반환함"
    return result


# ── 1 & 2. 3문서 생성 후 파일 존재 확인 ────────────────────────────────────

def test_create_task_docs_generates_three_files(tmp_path, monkeypatch):
    """_create_task_docs 호출 후 plan.md, context-notes.md, checklist.md가 생성되어야 한다."""
    _setup_templates(tmp_path)
    task_id = "task-9001"
    docs_dir = _create_docs(tmp_path, task_id, monkeypatch)

    assert (docs_dir / "plan.md").exists(), "plan.md 미생성"
    assert (docs_dir / "context-notes.md").exists(), "context-notes.md 미생성"
    assert (docs_dir / "checklist.md").exists(), "checklist.md 미생성"


def test_create_task_docs_replaces_placeholders(tmp_path, monkeypatch):
    """생성된 파일 내용에서 {task_id}와 {date} 플레이스홀더가 치환되어야 한다."""
    _setup_templates(tmp_path)
    task_id = "task-9002"
    docs_dir = _create_docs(tmp_path, task_id, monkeypatch)

    plan_content = (docs_dir / "plan.md").read_text(encoding="utf-8")
    assert "{task_id}" not in plan_content, "plan.md에 {task_id} 플레이스홀더 미치환"
    assert "{date}" not in plan_content, "plan.md에 {date} 플레이스홀더 미치환"
    assert task_id in plan_content, f"plan.md에 task_id({task_id}) 미포함"


# ── 3. verify → WARN (status=draft) ────────────────────────────────────────

def test_three_docs_verify_returns_warn_for_draft_status(tmp_path, monkeypatch):
    """생성 직후(status=draft) verify 결과는 WARN이어야 한다."""
    _setup_templates(tmp_path)
    task_id = "task-9003"
    _create_docs(tmp_path, task_id, monkeypatch)

    from teams.shared.verifiers.three_docs_check import verify

    result = verify(task_id=task_id, workspace=str(tmp_path))
    assert result["status"] == "WARN", f"WARN 기대, 실제: {result['status']} - {result['message']}"
    assert "draft" in result["message"].lower() or "warn" in result["message"].lower()


# ── 4. plan.md status=completed 수정 후 → PASS ──────────────────────────────

def test_three_docs_verify_returns_pass_after_status_update(tmp_path, monkeypatch):
    """plan.md status를 completed로 수정한 후 verify 결과는 PASS여야 한다."""
    _setup_templates(tmp_path)
    task_id = "task-9004"
    docs_dir = _create_docs(tmp_path, task_id, monkeypatch)

    # plan.md status를 completed로 변경
    plan_path = docs_dir / "plan.md"
    content = plan_path.read_text(encoding="utf-8")
    updated = content.replace("status: draft", "status: completed", 1)
    plan_path.write_text(updated, encoding="utf-8")

    from teams.shared.verifiers.three_docs_check import verify

    result = verify(task_id=task_id, workspace=str(tmp_path))
    assert result["status"] == "PASS", f"PASS 기대, 실제: {result['status']} - {result['message']}"


# ── 5. 디렉토리 없으면 → SKIP ──────────────────────────────────────────────

def test_three_docs_verify_returns_skip_when_no_directory(tmp_path):
    """3문서 디렉토리가 없으면 verify 결과는 SKIP이어야 한다."""
    from teams.shared.verifiers.three_docs_check import verify

    result = verify(task_id="task-nonexistent-99999", workspace=str(tmp_path))
    assert result["status"] == "SKIP", f"SKIP 기대, 실제: {result['status']}"


# ── 6. 파일 누락 시 → FAIL ─────────────────────────────────────────────────

def test_three_docs_verify_returns_fail_when_file_missing(tmp_path, monkeypatch):
    """checklist.md가 없으면 verify 결과는 FAIL이어야 한다."""
    _setup_templates(tmp_path)
    task_id = "task-9005"
    docs_dir = _create_docs(tmp_path, task_id, monkeypatch)

    # checklist.md 삭제
    (docs_dir / "checklist.md").unlink()

    from teams.shared.verifiers.three_docs_check import verify

    result = verify(task_id=task_id, workspace=str(tmp_path))
    assert result["status"] == "FAIL", f"FAIL 기대, 실제: {result['status']}"
    assert "checklist.md" in result["message"]


def test_three_docs_verify_returns_fail_when_all_files_missing(tmp_path):
    """3문서 디렉토리가 있지만 파일이 하나도 없으면 FAIL이어야 한다."""
    task_id = "task-9006"
    # 디렉토리만 생성, 파일 없음
    docs_dir = tmp_path / "memory" / "plans" / "tasks" / task_id
    docs_dir.mkdir(parents=True, exist_ok=True)

    from teams.shared.verifiers.three_docs_check import verify

    result = verify(task_id=task_id, workspace=str(tmp_path))
    assert result["status"] == "FAIL", f"FAIL 기대, 실제: {result['status']}"
