"""
test_critical_gap_false_positive_2506.py — task-2506 회귀 테스트

회장 명시 15건 (10 false-positive + 5 true-positive) 검증.
- False-positive: critical_gap fix 후 PASS여야 함
- True-positive: 기존 룰 유지 — FAIL이어야 함

수정 대상: teams/shared/verifiers/critical_gap.py
"""

import importlib.util
import sys
from pathlib import Path

WORKSPACE = Path("/home/jay/workspace")


def _load_module(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"Failed to load module spec for {path}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


critical_gap = _load_module(
    "critical_gap_t2506",
    WORKSPACE / "teams" / "shared" / "verifiers" / "critical_gap.py",
)


# ══════════════════════════════════════════════
# False-positive 케이스 — fix 후 PASS여야 함 (10건)
# ══════════════════════════════════════════════

def test_fp_priority_label_only(tmp_path):
    """FP1: '- 우선순위: critical' 단독 줄 → PASS (메타 정보, 이슈 아님)."""
    body = "- 우선순위: critical\n"
    report = tmp_path / "task-fp1.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp1", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP1 메타 우선순위 라벨이 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_task_priority_bracket_header(tmp_path):
    """FP2: '## task: [CRITICAL] 20개 컨셉' 헤더 → PASS (태스크 제목 우선순위 표기, 이슈 아님)."""
    body = "## task: [CRITICAL] 20개 컨셉\n본문 내용 없음.\n"
    report = tmp_path / "task-fp2.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp2", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP2 태스크 헤더 우선순위 표기가 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_critical_path_in_list(tmp_path):
    """FP3: '1. critical path 분석' 번호 목록 항목 → PASS (방법론 용어, 이슈 아님)."""
    body = "1. critical path 분석\n2. 일정 최적화\n"
    report = tmp_path / "task-fp3.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp3", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP3 critical path 방법론 용어가 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_critical_chain_in_scqa(tmp_path):
    """FP4: SCQA 프레임 상황절 내 'critical chain 중복 투입 문제' → PASS (상황 묘사, 이슈 마커 아님)."""
    body = "### S 상황\n- critical chain 중복 투입 문제\n"
    report = tmp_path / "task-fp4.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp4", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP4 SCQA 상황절 critical chain이 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_dispatch_level_critical_first_line(tmp_path):
    """FP5: 보고서 첫줄 '- 작업 레벨: critical' 단독 → PASS (디스패치 레벨 메타, 이슈 아님)."""
    body = "- 작업 레벨: critical\n작업이 완료되었습니다.\n"
    report = tmp_path / "task-fp5.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp5", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP5 작업 레벨 메타 라벨이 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_bracket_critical_only_header(tmp_path):
    """FP6: '## [CRITICAL]' 대괄호 prefix만 있는 헤더 (이슈 본문 없음) → PASS (분류 헤더, 본문 이슈 없음)."""
    body = "## [CRITICAL]\n작업 완료.\n"
    report = tmp_path / "task-fp6.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp6", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP6 분류 헤더 [CRITICAL]이 미해결 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_critical_thinking_phrase(tmp_path):
    """FP7: '이 작업은 critical thinking이 필요하다' 평문 문장 → PASS (일반 용어, 이슈 아님)."""
    body = "이 작업은 critical thinking이 필요하다.\n분석 완료.\n"
    report = tmp_path / "task-fp7.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp7", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP7 'critical thinking' 일반 문구가 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_level_critical_meta(tmp_path):
    """FP8: '- level: critical' 메타 라벨 → PASS (severity와 다른 level 필드, 이슈 아님)."""
    body = "- level: critical\n작업 정상 완료.\n"
    report = tmp_path / "task-fp8.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp8", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP8 'level: critical' 메타 라벨이 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_dispatch_level_critical_inline(tmp_path):
    """FP9: 'dispatch level critical' 명시 → PASS (디스패치 시스템 레벨 태그, 이슈 아님)."""
    body = "dispatch level critical\n모든 항목 처리 완료.\n"
    report = tmp_path / "task-fp9.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp9", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP9 'dispatch level critical' 태그가 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


def test_fp_launch_priority_critical(tmp_path):
    """FP10: '발사 우선순위: critical' → PASS (발사/배포 우선순위 메타 정보, 이슈 아님)."""
    body = "발사 우선순위: critical\n배포 준비 완료.\n"
    report = tmp_path / "task-fp10.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-fp10", report_path=str(report))
    assert result["status"] == "PASS", (
        f"FP10 '발사 우선순위: critical' 메타가 이슈로 오인식: status={result['status']}, details={result.get('details')}"
    )


# ══════════════════════════════════════════════
# True-positive 케이스 — fix 후에도 FAIL이어야 함 (5건)
# ══════════════════════════════════════════════

def test_tp_critical_issue_section_with_body(tmp_path):
    """TP1: '## CRITICAL 이슈 1건 발견\\n- token 누락' → FAIL (실제 이슈 헤더 + 미해결)."""
    body = "## CRITICAL 이슈 1건 발견\n- token 누락\n"
    report = tmp_path / "task-tp1.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-tp1", report_path=str(report))
    assert result["status"] == "FAIL", (
        f"TP1 CRITICAL 이슈 헤더 + 미해결이 감지되지 않음: status={result['status']}, details={result.get('details')}"
    )


def test_tp_severity_critical_meta_in_issue_section(tmp_path):
    """TP2: '## 발견된 이슈\\n- severity: critical' → FAIL (severity는 이슈 자체를 나타냄)."""
    body = "## 발견된 이슈\n- severity: critical\n"
    report = tmp_path / "task-tp2.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-tp2", report_path=str(report))
    assert result["status"] == "FAIL", (
        f"TP2 'severity: critical' 이슈가 감지되지 않음: status={result['status']}, details={result.get('details')}"
    )


def test_tp_unresolved_in_issue_section(tmp_path):
    """TP3: '## 미해결 항목\\n- CRITICAL: 누락' → FAIL (CRITICAL 리스트 마커 + 미해결)."""
    body = "## 미해결 항목\n- CRITICAL: 누락\n"
    report = tmp_path / "task-tp3.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-tp3", report_path=str(report))
    assert result["status"] == "FAIL", (
        f"TP3 'CRITICAL: 누락' 마커가 감지되지 않음: status={result['status']}, details={result.get('details')}"
    )


def test_tp_security_critical_badge(tmp_path):
    """TP4: '## 발견된 이슈\\n- ![security-critical] 발견' → FAIL (보안 배지 마커 + 미해결)."""
    body = "## 발견된 이슈\n- ![security-critical] 발견\n"
    report = tmp_path / "task-tp4.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-tp4", report_path=str(report))
    assert result["status"] == "FAIL", (
        f"TP4 '![security-critical]' 배지가 감지되지 않음: status={result['status']}, details={result.get('details')}"
    )


def test_tp_critical_no_resolved_marker(tmp_path):
    """TP5: '## CRITICAL 이슈\\n- 보안 누락' (RESOLVED 마커 없음) → FAIL (이슈 있으나 해결 확인 없음)."""
    body = "## CRITICAL 이슈\n- 보안 누락\n"
    report = tmp_path / "task-tp5.md"
    report.write_text(body, encoding="utf-8")
    result = critical_gap.verify("task-tp5", report_path=str(report))
    assert result["status"] == "FAIL", (
        f"TP5 CRITICAL 이슈 + RESOLVED 없음이 감지되지 않음: status={result['status']}, details={result.get('details')}"
    )
