"""
planned_check.py - 보고서 내 planned 항목 검출 verifier
보고서에 planned 상태 항목이 존재하면 FAIL.
"""

import os
import re

DEFAULT_REPORTS_DIR = "/home/jay/workspace/memory/reports"


def verify(task_id: str, reports_dir: str = "") -> dict:
    """
    보고서에서 '수정 파일별 검증 상태' 테이블의 planned 항목을 검출한다.
    planned 항목이 1건 이상이면 FAIL.
    """
    rd = reports_dir or DEFAULT_REPORTS_DIR
    report_path = os.path.join(rd, f"{task_id}.md")

    if not os.path.isfile(report_path):
        return {"status": "SKIP", "details": [f"보고서 파일 없음: {report_path}"]}

    with open(report_path, "r", encoding="utf-8") as f:
        content = f.read()

    if "수정 파일별 검증 상태" not in content:
        return {"status": "SKIP", "details": ["보고서에 '수정 파일별 검증 상태' 테이블 없음 (Lv.2 이하)"]}

    # 마크다운 테이블 파싱
    table_row_re = re.compile(r"^\|(.+)\|$")
    separator_re = re.compile(r"^\|[\s\-|]+\|$")

    planned_items = []
    for line in content.splitlines():
        line = line.strip()
        if not table_row_re.match(line):
            continue
        if separator_re.match(line):
            continue

        cells = [c.strip() for c in line.strip("|").split("|")]
        if len(cells) < 4:
            continue

        # 헤더 행 스킵
        if cells[0].strip().lower() in {"파일", "file"} or cells[3].strip().lower() in {"상태", "status"}:
            continue

        status = cells[3].strip().lower()
        if status == "planned":
            file_path = cells[0].strip()
            description = cells[1].strip()
            planned_items.append(f"{file_path} ({description})")

    if planned_items:
        return {
            "status": "FAIL",
            "details": [
                f"planned 항목 {len(planned_items)}건 발견: {planned_items}"
            ],
            "planned_count": len(planned_items),
            "planned_items": planned_items,
        }

    return {"status": "PASS", "details": ["planned 항목 0건"], "planned_count": 0}
