#!/usr/bin/env python3
"""
png_check verifier — HTML 배너 파일에 대응하는 PNG 렌더링 파일 존재 검증

배너/이미지 작업에서 .html 파일이 존재하면 대응하는 .png 파일도 반드시 존재해야 함.
"""

import os


def verify(task_id: str, output_dir: str = "") -> dict:
    """HTML 배너에 대응하는 PNG 파일 존재 여부 검증.

    Args:
        task_id: 작업 ID
        output_dir: 산출물 디렉토리 경로 (기본: /home/jay/workspace/memory/outputs/{task_id})

    Returns:
        QC 결과 dict (status, details)
    """
    workspace_root = os.environ.get("WORKSPACE_ROOT", "/home/jay/workspace")
    if not output_dir:
        output_dir = os.path.join(workspace_root, "memory", "outputs", task_id)

    if not os.path.isdir(output_dir):
        return {
            "status": "SKIP",
            "details": [f"산출물 디렉토리 없음: {output_dir}. 이미지 작업이 아니면 SKIP."],
        }

    # 산출물 디렉토리에서 .html 파일 찾기 (재귀)
    html_files = []
    for root, _dirs, files in os.walk(output_dir):
        for f in files:
            if f.endswith(".html"):
                html_files.append(os.path.join(root, f))

    if not html_files:
        return {
            "status": "SKIP",
            "details": ["산출물 디렉토리에 .html 파일 없음. PNG 검증 불필요."],
        }

    # 각 .html 파일에 대응하는 .png 파일 존재 확인
    missing_png = []
    found_pairs = []
    for html_path in html_files:
        base = os.path.splitext(html_path)[0]
        png_path = base + ".png"
        if os.path.isfile(png_path):
            found_pairs.append(os.path.basename(png_path))
        else:
            missing_png.append(os.path.basename(html_path))

    if missing_png:
        return {
            "status": "FAIL",
            "details": [
                f"HTML 배너 {len(missing_png)}개에 대응 PNG 파일 없음:",
                *[f"  - {name} → .png 파일 누락" for name in missing_png],
                "Playwright로 HTML → PNG 렌더링 후 재검증 필요.",
            ],
        }

    return {
        "status": "PASS",
        "details": [
            f"HTML 배너 {len(found_pairs)}개 모두 대응 PNG 파일 존재 확인.",
            *[f"  - {name}" for name in found_pairs],
        ],
    }
