#!/usr/bin/env python3
"""callback_cause_classifier.py — callback 미발사 원인 구분 + finish profile(task_mode) 연결.

task-2700 Phase 1 모듈 3.
"""
from __future__ import annotations

import argparse
import json

NORMAL_CALLBACK_MISSING = "NORMAL_CALLBACK_MISSING"
FINISH_TASK_GIT_GATE_BLOCKED = "FINISH_TASK_GIT_GATE_BLOCKED"

# dirty_registry 와 동일한 문자열 상수 (import 없이 독립 사용 가능하도록 로컬 정의)
_EXTERNAL_DIRTY_BLOCKER = "EXTERNAL_DIRTY_BLOCKER"
_OWN_DIRTY_FAIL = "OWN_DIRTY_FAIL"

FINISH_PROFILES: dict[str, dict] = {
    "read_only_watcher": {
        "create_done": False,
        "git_gate": False,
        "merge": False,
        "callback": True,
        "desc": "관찰 전용 — .done 미생성, GIT-GATE 미적용",
    },
    "diagnosis": {
        "create_done": True,
        "git_gate": False,
        "merge": False,
        "callback": True,
        "desc": "진단 — 마커만, 머지 없음",
    },
    "callback_only": {
        "create_done": True,
        "git_gate": False,
        "merge": False,
        "callback": True,
        "desc": "콜백 전용 — 머지 없이 callback",
    },
    "closeout_marker_only": {
        "create_done": True,
        "git_gate": False,
        "merge": False,
        "callback": False,
        "desc": "종결 마커 전용",
    },
    "code": {
        "create_done": True,
        "git_gate": True,
        "merge": True,
        "callback": True,
        "desc": "기본 코드 task — GIT-GATE+머지+callback",
    },
}


# ---------------------------------------------------------------------------
# Finish profile resolver
# ---------------------------------------------------------------------------

def resolve_finish_profile(task_mode: str) -> dict:
    """task_mode 에 해당하는 FINISH_PROFILES 항목 반환. 미지정 키는 "code" fallback."""
    profile = FINISH_PROFILES.get(task_mode)
    if profile is None:
        profile = FINISH_PROFILES["code"]
    return dict(profile)  # shallow copy


# ---------------------------------------------------------------------------
# Callback missing classifier
# ---------------------------------------------------------------------------

def classify_callback_missing(
    *,
    done_exists: bool,
    git_gate_blocked: bool,
    blocker_classification: str | None = None,
    task_mode: str = "code",
) -> dict:
    """callback 미발사 원인 분류.

    git_gate_blocked=True 이고 done_exists=False
      → FINISH_TASK_GIT_GATE_BLOCKED
      sub_cause = blocker_classification
        EXTERNAL_DIRTY_BLOCKER → 환경 책임 (task 재실행 불필요)
        OWN_DIRTY_FAIL         → task 책임 (own dirty 커밋 후 재실행)

    그 외(done_exists=True 인데 callback 미발사)
      → NORMAL_CALLBACK_MISSING

    반환: {"cause", "sub_cause", "remediation", "finish_profile", "task_mode"}
    """
    finish_profile = resolve_finish_profile(task_mode)

    if git_gate_blocked and not done_exists:
        sub_cause = blocker_classification or "UNKNOWN"

        if blocker_classification == _EXTERNAL_DIRTY_BLOCKER:
            remediation = (
                "origin/main sync 또는 무관 dirty 정리 — task 재실행 불필요"
            )
        elif blocker_classification == _OWN_DIRTY_FAIL:
            remediation = "own dirty 커밋 후 finish-task 재실행"
        else:
            remediation = (
                "git 상태 점검 후 dirty 정리 또는 sync 후 finish-task 재실행"
            )

        return {
            "cause": FINISH_TASK_GIT_GATE_BLOCKED,
            "sub_cause": sub_cause,
            "remediation": remediation,
            "finish_profile": finish_profile,
            "task_mode": task_mode,
        }

    # done_exists=True (or git_gate 미차단) → callback runner 문제
    return {
        "cause": NORMAL_CALLBACK_MISSING,
        "sub_cause": None,
        "remediation": "callback runner/네트워크 점검 — .done은 정상 생성됨",
        "finish_profile": finish_profile,
        "task_mode": task_mode,
    }


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def _build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        description="Classify why callback was not fired.",
    )
    p.add_argument("--done-exists", action="store_true",
                   help="pass if .done marker exists")
    p.add_argument("--git-gate-blocked", action="store_true",
                   help="pass if finish-task GIT-GATE was blocked")
    p.add_argument("--blocker-classification", default=None,
                   help="EXTERNAL_DIRTY_BLOCKER | OWN_DIRTY_FAIL | CLEAN")
    p.add_argument("--task-mode", default="code",
                   help="finish profile mode (default: code)")
    return p


def main(argv: list[str] | None = None) -> None:
    parser = _build_parser()
    args = parser.parse_args(argv)

    result = classify_callback_missing(
        done_exists=args.done_exists,
        git_gate_blocked=args.git_gate_blocked,
        blocker_classification=args.blocker_classification,
        task_mode=args.task_mode,
    )
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()
