"""engine_v2/qc_hook.py — QC 파이프라인 연결 훅 포인트.

engine_v2 실행 결과를 QC 파이프라인에 연결하기 위한 인터페이스.
PostToolUse 훅과 연동 가능하도록 설계.
"""

from __future__ import annotations

import json
import logging
from pathlib import Path
from typing import Protocol

from engine_v2.engine_result import EngineResult

logger = logging.getLogger(__name__)


class QCHandler(Protocol):
    """QC 핸들러 프로토콜."""

    def on_engine_complete(self, result: EngineResult) -> None:
        """엔진 실행 완료 시 호출."""
        ...

    def on_pipeline_complete(self, results: list[EngineResult]) -> None:
        """파이프라인 전체 완료 시 호출."""
        ...


class FileQCHook:
    """파일 기반 QC 훅.

    engine_v2 실행 결과를 JSON 파일로 저장하여
    외부 QC 도구(qc_verify.py 등)가 읽을 수 있도록 한다.
    """

    def __init__(self, output_dir: Path | None = None) -> None:
        self._output_dir = output_dir or Path("/home/jay/workspace/memory/qc")
        self._output_dir.mkdir(parents=True, exist_ok=True)

    def on_engine_complete(self, result: EngineResult) -> None:
        """개별 엔진 결과 기록."""
        entry = {
            "engine": result.engine,
            "task_id": result.task_id,
            "step": result.step,
            "error": result.error,
            "flagged_count": result.flagged_count,
            "token_est": result.token_est,
            "timestamp": result.timestamp.isoformat(),
        }
        filepath = self._output_dir / f"{result.task_id}_step{result.step}_{result.engine}.json"
        filepath.write_text(json.dumps(entry, ensure_ascii=False, indent=2), encoding="utf-8")
        logger.debug("QC hook: wrote %s", filepath)

    def on_pipeline_complete(self, results: list[EngineResult]) -> None:
        """파이프라인 전체 결과 요약."""
        if not results:
            return
        task_id = results[0].task_id
        summary = {
            "task_id": task_id,
            "total_steps": len(results),
            "errors": sum(1 for r in results if r.error),
            "total_flagged": sum(r.flagged_count for r in results),
            "engines_used": list({r.engine for r in results}),
        }
        filepath = self._output_dir / f"{task_id}_summary.json"
        filepath.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
        logger.info("QC hook: pipeline summary written to %s", filepath)
