#!/usr/bin/env bash
# kimi-subagent-router 一键部署脚本
# 将仓库文件同步到 Kimi Code 插件安装目录，并重新执行 setup-config + doctor。
# 幂等，可重复运行。用法：bash scripts/deploy.sh
set -euo pipefail

PLUGIN_ID="kimi-subagent-router"
DEFAULT_ROOT="$HOME/.kimi-code/plugins/managed/kimi-subagent-router"
INSTALLED_JSON="$HOME/.kimi-code/plugins/installed.json"

# 仓库根目录（本脚本位于 scripts/ 下）
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

info() { printf '[部署] %s\n' "$*"; }
err()  { printf '[错误] %s\n' "$*" >&2; }

# 1. 定位部署目标：优先读 installed.json 的 root 字段，失败回退默认路径
ROOT=""
if [ -f "$INSTALLED_JSON" ]; then
    ROOT="$(python3 - "$INSTALLED_JSON" "$PLUGIN_ID" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as f:
    data = json.load(f)
for p in data.get("plugins", []):
    if p.get("id") == sys.argv[2]:
        print(p.get("root") or "")
        break
PY
)" || ROOT=""
fi
[ -n "$ROOT" ] || ROOT="$DEFAULT_ROOT"

# 2. 安全检查：目标必须已存在且是插件安装目录（防止 rsync --delete 误删）
if [ ! -d "$ROOT" ]; then
    err "插件安装目录不存在：$ROOT"
    err "请先安装插件：/plugins install <仓库路径> && /plugins enable $PLUGIN_ID"
    exit 1
fi
if [ ! -f "$ROOT/kimi.plugin.json" ]; then
    err "$ROOT 下没有 kimi.plugin.json，不像插件安装目录，已中止以防误删文件。"
    exit 1
fi
if [ "$ROOT" = "$SRC_DIR" ]; then
    err "部署目标与源仓库相同（$ROOT），无需部署。"
    exit 0
fi

info "源目录：$SRC_DIR"
info "目标目录：$ROOT"

# 3. 同步文件（镜像源仓库，排除 .git/.qoder/.gitignore，与现有部署副本一致）
rsync -a --delete --delete-excluded \
    --filter='protect .git/' --filter='protect .qoder/' \
    --exclude='.git/' --exclude='.qoder/' --exclude='.gitignore' \
    --exclude='__pycache__/' --exclude='*.pyc' \
    --itemize-changes --out-format='  %n' \
    "$SRC_DIR/" "$ROOT/" | { grep -v '^  \./$' || true; }

info "文件同步完成。"

# 4. 重新注册模型变体并刷新 [secondary_model] 池（幂等，内部自动备份 config.toml）
info "执行 setup-config ..."
python3 "$ROOT/scripts/kimi_subagent_router.py" setup-config

# 5. 一致性检查
info "执行 doctor ..."
if ! python3 "$ROOT/scripts/kimi_subagent_router.py" doctor; then
    err "doctor 报告错误，请按上方提示修复后重跑本脚本。"
    exit 1
fi

info "部署完成。请在 Kimi Code TUI 中执行 /reload 或 /new 使更新生效。"
