#!/usr/bin/env bash
# CodeGraph 中文版 · 一键部署脚本
#   装 codegraph CLI ＋ 接 Agent ＋ 中文查看器 ＋ codegraph init
# 用法：
#   bash install-codegraph-cn.sh [--dry-run] [--npm] [--yes] [--project DIR]
#   curl -fsSL https://codegraph-cn.gaoqiangq.cn/dl/install-codegraph-cn.sh | bash
#
# 双路径：macOS / Linux。任一步失败都明示原因并退出，不留半截状态。
# codegraph 本体永远从上游官方渠道安装（官方安装器或 npm），本脚本不
# 分发、不改动上游代码；中文层只在第 3 步以“词典＋覆盖脚本”注入。
# 退出码：0 = 全部完成（查看器未发布时第 3 步跳过亦为 0，但总结会明示）；
#         非 0 = 某步失败，见终端最后的 ERROR 行。
set -euo pipefail

DRY_RUN=0
USE_NPM=0
ASSUME_YES=0
PROJECT_DIR="${PWD}"
BASE_URL="${CGCN_BASE_URL:-https://codegraph-cn.gaoqiangq.cn}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

info()  { printf '[codegraph-cn] %s\n' "$*"; }
warn()  { printf '[codegraph-cn] WARNING: %s\n' "$*" >&2; }
error() { printf '[codegraph-cn] ERROR: %s\n' "$*" >&2; }
dry()   { printf '[codegraph-cn] [dry-run] %s\n' "$*"; }

run() {
  if [ "$DRY_RUN" -eq 1 ]; then dry "would run: $*"; else "$@"; fi
}

while [ $# -gt 0 ]; do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    --npm) USE_NPM=1 ;;
    --yes) ASSUME_YES=1 ;;
    --project) PROJECT_DIR="$2"; shift ;;
    --project=*) PROJECT_DIR="${1#--project=}" ;;
    -h|--help)
      sed -n '2,12p' "${BASH_SOURCE[0]}"
      exit 0 ;;
    *) error "未知参数：$1（可用 --dry-run / --npm / --yes / --project DIR）"; exit 2 ;;
  esac
  shift
done

OS="$(uname -s)"
if [ "$OS" != "Darwin" ] && [ "$OS" != "Linux" ]; then
  error "不支持的操作系统：$OS（本脚本只支持 macOS / Linux；Windows 请用上游 install.ps1 装 CLI 后按 docs/安装指南.md 手动接中文查看器）"
  exit 3
fi
info "系统：$OS（$(uname -m)），目标项目：$PROJECT_DIR"

# ── 第 1 步：装 codegraph CLI ──────────────────────────────────────
if command -v codegraph >/dev/null 2>&1; then
  info "第 1 步：codegraph 已安装（$(codegraph --version 2>/dev/null || echo '版本未知')），跳过安装"
else
  info "第 1 步：安装 codegraph CLI（上游官方渠道）"
  if [ "$USE_NPM" -eq 1 ]; then
    command -v npm >/dev/null 2>&1 || { error "指定了 --npm 但本机没有 npm；请先装 Node.js ≥ 18，或去掉 --npm 走官方安装器"; exit 4; }
    run npm i -g @colbymchenry/codegraph
  else
    command -v curl >/dev/null 2>&1 || { error "需要 curl 才能跑上游官方安装器；请先装 curl，或用 --npm 走 npm 路径"; exit 4; }
    if [ "$DRY_RUN" -eq 1 ]; then
      dry "would run: curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh"
    else
      curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh
    fi
  fi
  if [ "$DRY_RUN" -eq 0 ] && ! command -v codegraph >/dev/null 2>&1; then
    error "安装器跑完了，但 codegraph 仍不在 PATH 上。安装器不改当前 shell：请新开一个终端再跑本脚本，或把安装目录（如 ~/.local/bin）加进 PATH"
    exit 5
  fi
fi

# ── 第 2 步：接 Agent ──────────────────────────────────────────────
info "第 2 步：把 CodeGraph 接入本机 Agent（codegraph install）"
if [ "$DRY_RUN" -eq 1 ]; then
  dry "would run: codegraph install --yes"
else
  if [ "$ASSUME_YES" -eq 1 ]; then run codegraph install --yes; else run codegraph install; fi
fi

# ── 第 3 步：中文查看器 ────────────────────────────────────────────
info "第 3 步：中文查看器"
VIEWER_STATUS="skipped"
if [ "$DRY_RUN" -eq 1 ]; then
  dry "would check: codegraph ui availability, then copy viewer-i18n/{zh-CN.json,codegraph-cn-i18n.js} next to the viewer index.html and inject <script src=\"./codegraph-cn-i18n.js\"></script>"
  VIEWER_STATUS="dry-run"
else
  if ! codegraph ui --help >/dev/null 2>&1; then
    warn "第 3 步跳过：本机装到的 codegraph 版本还没有 'codegraph ui' 命令。"
    warn "上游查看器在 2026-11-27 尚未随正式版发布（上游文档注明 Not released yet）。"
    warn "CLI 索引与 MCP 功能不受影响；上游发布含查看器的版本后，重跑本脚本即可补装中文查看器。"
    warn "等待期间可用本仓 viewer-i18n/demo/ 演示查看器先看中文界面效果。"
    VIEWER_STATUS="pending-upstream-release"
  else
    # 定位查看器静态资源目录（随上游版本布局而定，尽力而为，找不到就明示）
    VIEWER_DIR=""
    CG_PATH="$(command -v codegraph)"
    for cand in "$(dirname "$CG_PATH")/../share/codegraph/ui" \
                "$(dirname "$CG_PATH")/../lib/node_modules/@colbymchenry/codegraph/dist/ui" \
                "$HOME/.local/share/codegraph/ui"; do
      if [ -f "$cand/index.html" ]; then VIEWER_DIR="$cand"; break; fi
    done
    if [ -z "$VIEWER_DIR" ]; then
      warn "第 3 步未完成：找到了 'codegraph ui'，但定位不到查看器静态资源目录（index.html）。"
      warn "请手动执行：把 viewer-i18n/zh-CN.json 与 codegraph-cn-i18n.js 拷到查看器资源目录，"
      warn "并在 index.html 的 </body> 前加一行 <script src=\"./codegraph-cn-i18n.js\"></script>。"
      warn "定位方法见 docs/安装指南.md 第三步；定位到后重跑本脚本即可。"
      VIEWER_STATUS="locate-failed"
    else
      I18N_SRC=""
      if [ -f "$SCRIPT_DIR/../viewer-i18n/zh-CN.json" ]; then
        I18N_SRC="$SCRIPT_DIR/../viewer-i18n"
      else
        info "从分发站下载中文语言包：$BASE_URL/dl/codegraph-cn-i18n.tar.gz"
        TMPD="$(mktemp -d)"
        if curl -fsSL "$BASE_URL/dl/codegraph-cn-i18n.tar.gz" -o "$TMPD/i18n.tar.gz" && tar -xzf "$TMPD/i18n.tar.gz" -C "$TMPD"; then
          I18N_SRC="$TMPD"
        else
          error "中文语言包下载失败（$BASE_URL 不可达或分发站未部署）。请确认分发站已上线，或从仓库检出后重跑。"
          exit 6
        fi
      fi
      cp "$I18N_SRC/zh-CN.json" "$I18N_SRC/codegraph-cn-i18n.js" "$VIEWER_DIR/"
      if ! grep -q "codegraph-cn-i18n.js" "$VIEWER_DIR/index.html"; then
        cp "$VIEWER_DIR/index.html" "$VIEWER_DIR/index.html.bak"
        perl -0pi -e 's{</body>}{<script src="./codegraph-cn-i18n.js"></script>\n</body>}' "$VIEWER_DIR/index.html"
      fi
      info "中文查看器已注入：$VIEWER_DIR（备份 index.html.bak）"
      VIEWER_STATUS="installed"
    fi
  fi
fi

# ── 第 4 步：自检＋初始化项目 ─────────────────────────────────────
info "第 4 步：自检"
if [ "$DRY_RUN" -eq 1 ]; then
  dry "would run: codegraph --version"
  dry "would run: codegraph init in $PROJECT_DIR (if --project given or run from a project dir)"
else
  codegraph --version || { error "自检失败：codegraph --version 非 0，请检查安装"; exit 7; }
  if [ -d "$PROJECT_DIR" ]; then
    info "为项目建索引：$PROJECT_DIR"
    (cd "$PROJECT_DIR" && run codegraph init) || {
      error "codegraph init 失败（见上文输出）。常见原因：目录不是代码项目、磁盘空间不足、权限不足。"
      exit 8
    }
  else
    error "目标项目目录不存在：$PROJECT_DIR"
    exit 8
  fi
fi

# ── 总结 ──────────────────────────────────────────────────────────
if [ "$DRY_RUN" -eq 1 ]; then
info "dry-run 结束：未做任何实际安装。上述步骤为将要执行的步骤（CLI 安装、Agent 接入、中文查看器检查与注入、自检＋项目索引）。"
else
info "完成。总结：CLI=已安装，Agent 接入=已执行，中文查看器=$VIEWER_STATUS，项目索引=已执行（$PROJECT_DIR）。"
fi
case "$VIEWER_STATUS" in
  installed) info "打开中文查看器：codegraph ui（http://127.0.0.1:4747），顶栏可切 中文 / EN。" ;;
  pending-upstream-release) info "下一步：等上游发布含 codegraph ui 的版本后重跑本脚本；期间先用 viewer-i18n/demo/ 看中文界面。" ;;
  locate-failed) info "下一步：按上方提示手动定位查看器目录后重跑本脚本。" ;;
esac
info "文档：docs/安装指南.md · docs/使用指南.md · docs/部署指南.md"
