#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""scripts/anu_terminal_artifact_surface.py — Terminal Artifact Surface CLI (task-2778_a).

worktree-local terminal artifact 를 canonical manifest index 로 surface 하는 CLI.
read/surface only — callback/fire/cron/driver/subprocess 절대 없음.

사용법:
  python3 anu_terminal_artifact_surface.py \\
      --task-id task-2778_a \\
      --worktree /path/to/worktree \\
      [--canonical-root /home/jay/workspace] \\
      [--branch feature/foo] \\
      [--head abc1234] \\
      [--json] \\
      [--no-write]

  --no-write: build 만 하고 surface write 안 함 (read-only 모드).
  --json:     manifest.to_dict() JSON 출력.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

# ── import 부트스트랩: scripts/ 에 있으므로 repo root = parents[1] ───────────
_REPO_ROOT = Path(__file__).resolve().parents[1]
if str(_REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(_REPO_ROOT))

from dispatch.terminal_artifact_index import (  # noqa: E402
    build_manifest,
    surface_manifest,
    STATUS_SURFACED_TO_CANONICAL,
    STATUS_TERMINAL_CALLBACK_MISSING,
)


def _build_parser() -> argparse.ArgumentParser:
    """argparse 파서 생성."""
    p = argparse.ArgumentParser(
        description="Terminal Artifact Surface CLI — read/surface only (task-2778_a).",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    p.add_argument("--task-id", required=True, help="대상 task ID (예: task-2778_a).")
    p.add_argument("--worktree", required=True, help="worktree root 경로 (절대경로 권장).")
    p.add_argument(
        "--canonical-root",
        default="/home/jay/workspace",
        help="canonical root 경로 (기본: /home/jay/workspace).",
    )
    p.add_argument("--branch", default=None, help="git branch 이름 (선택).")
    p.add_argument("--head", default=None, help="git HEAD SHA (선택).")
    p.add_argument(
        "--json",
        action="store_true",
        dest="output_json",
        help="manifest.to_dict() JSON 출력.",
    )
    p.add_argument(
        "--no-write",
        action="store_true",
        dest="no_write",
        help="build 만 하고 surface write 안 함 (read-only 모드).",
    )
    return p


def _human_summary(manifest, *, wrote_path: str) -> str:
    """사람이 읽을 수 있는 요약 문자열 반환."""
    lines = [
        f"task_id        : {manifest.task_id}",
        f"status         : {manifest.status}",
        f"statuses       : {manifest.statuses!r}",
        f"worktree_path  : {manifest.worktree_path}",
        f"report_path    : {manifest.report_path}",
        f"done_path      : {manifest.done_path}",
        f"envelope_path  : {manifest.envelope_path}",
        f"branch         : {manifest.branch}",
        f"head           : {manifest.head}",
        f"schema_version : {manifest.schema_version}",
        f"generated_at   : {manifest.generated_at}",
    ]
    if wrote_path:
        lines.append(f"surfaced_to    : {wrote_path}")
    else:
        lines.append("surfaced_to    : (no-write mode or write failed)")
    return "\n".join(lines)


def main(argv=None) -> int:
    """CLI 메인 진입점.

    fail-open: 예외 시 error JSON 출력하고 exit code 1 반환 (traceback 노출 금지).
    """
    parser = _build_parser()
    try:
        args = parser.parse_args(argv)
    except SystemExit as exc:
        # argparse 자체 exit (--help 또는 필수 인자 누락) — 그대로 전달
        return int(exc.code) if exc.code is not None else 1

    try:
        manifest = build_manifest(
            args.task_id,
            canonical_root=args.canonical_root,
            worktree_root=args.worktree,
            branch=args.branch,
            head=args.head,
        )

        wrote_path = ""
        if not args.no_write:
            wrote_path = surface_manifest(manifest, canonical_root=args.canonical_root)

        if args.output_json:
            out = manifest.to_dict()
            if wrote_path:
                out["_surfaced_index_path"] = wrote_path
            print(json.dumps(out, ensure_ascii=False, indent=2))
        else:
            print(_human_summary(manifest, wrote_path=wrote_path))

        # surface 실패(no-write 아닌데 경로 없음)는 warn 수준 — exit 0 유지
        return 0

    except Exception as exc:  # noqa: BLE001 — fail-open: traceback 노출 금지
        error_payload = {
            "error": True,
            "message": str(exc),
            "task_id": getattr(args, "task_id", None) if "args" in dir() else None,
        }
        try:
            print(json.dumps(error_payload, ensure_ascii=False), file=sys.stderr)
        except Exception:  # noqa: BLE001
            print("ERROR: unexpected failure in anu_terminal_artifact_surface", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
