"""
test_three_docs_check.py - three_docs_check 검증기 테스트

벨레스(Veles) dev6팀 테스터 작성
task-1872_6.4
"""

import sys

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

from verifiers.three_docs_check import verify


# ──────────────────────────────────────────────────────────
# 헬퍼 함수
# ──────────────────────────────────────────────────────────

def _create_docs(
    base_dir,
    task_id,
    plan_status="completed",
    plan_body="실제 계획 내용",
    context_body="실제 맥락 내용",
    checklist_body="- [x] 완료\n- [x] 완료2",
):
    """3문서 디렉토리와 파일 생성 헬퍼"""
    docs_dir = base_dir / "memory" / "plans" / "tasks" / task_id
    docs_dir.mkdir(parents=True, exist_ok=True)

    # plan.md
    (docs_dir / "plan.md").write_text(
        f"""---
task_id: {task_id}
type: plan
scope: task
status: {plan_status}
---

{plan_body}
""",
        encoding="utf-8",
    )

    # context-notes.md
    (docs_dir / "context-notes.md").write_text(
        f"""---
task_id: {task_id}
type: context
scope: task
status: active
---

{context_body}
""",
        encoding="utf-8",
    )

    # checklist.md
    (docs_dir / "checklist.md").write_text(
        f"""---
task_id: {task_id}
type: checklist
scope: task
status: active
---

{checklist_body}
""",
        encoding="utf-8",
    )

    return docs_dir


# ──────────────────────────────────────────────────────────
# 테스트 케이스
# ──────────────────────────────────────────────────────────


def test_pass_complete_docs(tmp_path):
    """Lv.3+ 작업, 3문서 정상 존재 + status=completed + 체크리스트 100% + 플레이스홀더 없음 → PASS"""
    task_id = "task-9901"
    _create_docs(
        tmp_path,
        task_id,
        plan_status="completed",
        plan_body="실제 계획 내용입니다.",
        context_body="실제 맥락 내용입니다.",
        checklist_body="- [x] 완료항목1\n- [x] 완료항목2\n- [x] 완료항목3",
    )

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "PASS"


def test_warn_status_draft(tmp_path):
    """Lv.3+ 작업, 3문서 존재하지만 plan.md status=draft → WARN"""
    task_id = "task-9902"
    _create_docs(
        tmp_path,
        task_id,
        plan_status="draft",
        plan_body="아직 초안 상태의 계획 내용입니다.",
        checklist_body="- [x] 완료항목1\n- [x] 완료항목2",
    )

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "WARN"


def test_fail_missing_directory(tmp_path):
    """3문서 디렉토리 없음 → SKIP (디렉토리 없으면 SKIP)"""
    task_id = "task-9903"
    # 디렉토리를 생성하지 않음

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "SKIP"


def test_skip_no_docs_dir(tmp_path):
    """Lv.2 작업, 디렉토리 없음 → SKIP"""
    task_id = "task-9904-lv2"
    # Lv.2 작업은 3문서 디렉토리가 없으므로 생성하지 않음

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "SKIP"


def test_fail_broken_yaml(tmp_path):
    """YAML frontmatter가 깨진 파일 → FAIL"""
    task_id = "task-9905"
    docs_dir = tmp_path / "memory" / "plans" / "tasks" / task_id
    docs_dir.mkdir(parents=True, exist_ok=True)

    # plan.md - 깨진 YAML frontmatter (닫는 --- 없음)
    (docs_dir / "plan.md").write_text(
        """---
task_id: task-9905
type: plan
scope: task
status: completed
이 YAML은 닫히지 않습니다

실제 계획 내용
""",
        encoding="utf-8",
    )

    # context-notes.md - 정상
    (docs_dir / "context-notes.md").write_text(
        """---
task_id: task-9905
type: context
scope: task
status: active
---

실제 맥락 내용
""",
        encoding="utf-8",
    )

    # checklist.md - 정상
    (docs_dir / "checklist.md").write_text(
        """---
task_id: task-9905
type: checklist
scope: task
status: active
---

- [x] 완료항목
""",
        encoding="utf-8",
    )

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "FAIL"


def test_warn_low_checklist(tmp_path):
    """checklist 완료율 50% 미만 → WARN"""
    task_id = "task-9906"
    _create_docs(
        tmp_path,
        task_id,
        plan_status="completed",
        plan_body="실제 계획 내용입니다.",
        context_body="실제 맥락 내용입니다.",
        # 완료 1개, 미완료 3개 → 25% (50% 미만)
        checklist_body="- [x] 완료항목1\n- [ ] 미완료1\n- [ ] 미완료2\n- [ ] 미완료3",
    )

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "WARN"


def test_warn_placeholder_unfilled(tmp_path):
    """템플릿 플레이스홀더 그대로인 파일 → WARN"""
    task_id = "task-9907"
    _create_docs(
        tmp_path,
        task_id,
        plan_status="completed",
        # 플레이스홀더 패턴 포함: [작업 내용]
        plan_body="여기에 [작업 내용]을 입력하세요.",
        checklist_body="- [x] 완료항목1\n- [x] 완료항목2",
    )

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "WARN"


def test_fail_missing_files(tmp_path):
    """디렉토리는 있지만 파일 1개 누락 (checklist.md 없음) → FAIL"""
    task_id = "task-9908"
    docs_dir = tmp_path / "memory" / "plans" / "tasks" / task_id
    docs_dir.mkdir(parents=True, exist_ok=True)

    # plan.md 생성
    (docs_dir / "plan.md").write_text(
        f"""---
task_id: {task_id}
type: plan
scope: task
status: completed
---

실제 계획 내용
""",
        encoding="utf-8",
    )

    # context-notes.md 생성
    (docs_dir / "context-notes.md").write_text(
        f"""---
task_id: {task_id}
type: context
scope: task
status: active
---

실제 맥락 내용
""",
        encoding="utf-8",
    )

    # checklist.md 는 의도적으로 생성하지 않음

    result = verify(task_id=task_id, workspace=str(tmp_path))

    assert result["name"] == "three_docs_check"
    assert result["status"] == "FAIL"
    assert "checklist.md" in result["details"].get("missing_files", [])
