#!/usr/bin/env bash
# install-to-existing.sh — 把 AppGenesisForge agent team 部署到已有项目
#
# 用法：
#   bash install-to-existing.sh <target-project-path>
#   bash install-to-existing.sh ~/Documents/DevApps/OOTDLab
#
# 行为：
# - 安全：先备份 target 已有 .claude/ 与 CLAUDE.md（带时间戳）
# - 自动化：复制 .claude/ 全套 + 根脚本 + docs/ 模板 + git pre-commit hook
# - 不自动覆盖：CLAUDE.md / ADR-000 / settings.json 已有时各保留为 .backup-* 让 user 手工 merge
# - 输出 next-steps 清单 + 回滚命令到 target/AGF_INSTALL_NEXT_STEPS.md

set -euo pipefail

# ---- helpers -----------------------------------------------------------------
if [[ -t 1 ]]; then
  R=$'\033[0;31m'; G=$'\033[0;32m'; Y=$'\033[0;33m'; B=$'\033[0;34m'
  C=$'\033[0;36m'; BOLD=$'\033[1m'; N=$'\033[0m'
else
  R= G= Y= B= C= BOLD= N=
fi
ok()   { echo "${G}✅${N} $1"; }
warn() { echo "${Y}⚠️ ${N} $1"; }
fail() { echo "${R}❌${N} $1" >&2; }
info() { echo "${B}→${N} $1"; }
hdr()  { echo; echo "${BOLD}$1${N}"; }

# ---- args + validate ---------------------------------------------------------
if [[ $# -lt 1 ]]; then
  fail "Usage: $0 <target-project-path>"
  exit 2
fi

SOURCE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET="$(cd "$1" 2>/dev/null && pwd)" || { fail "Target path not accessible: $1"; exit 1; }
STAMP=$(date +%Y%m%d-%H%M%S)

hdr "Validating source (AppGenesisForge) and target"

# Source must be AGF root
for f in .claude/agents .claude/standards .claude/hooks .claude/commands .claude/skills .claude/rules .claude/scripts init-team.sh agf-team-start.sh; do
  [[ -e "$SOURCE/$f" ]] || { fail "Source not a valid AGF root (missing $f)"; exit 1; }
done
ok "Source: $SOURCE"

# Target must be a git repo (worktree isolation requires git)
git -C "$TARGET" rev-parse --git-dir >/dev/null 2>&1 || {
  fail "Target is not a git repo: $TARGET"
  exit 1
}
ok "Target: $TARGET (git repo)"

if [[ "$SOURCE" == "$TARGET" ]]; then
  fail "Source and target are the same directory"
  exit 1
fi

# ---- backup ------------------------------------------------------------------
hdr "Backing up existing target state"

BACKUP_DIR="$TARGET/.claude.backup-$STAMP"
if [[ -d "$TARGET/.claude" ]]; then
  mv "$TARGET/.claude" "$BACKUP_DIR"
  ok "Backed up .claude/ → $(basename "$BACKUP_DIR")"
else
  info "No existing .claude/ (fresh install)"
fi

if [[ -f "$TARGET/CLAUDE.md" ]]; then
  cp "$TARGET/CLAUDE.md" "$TARGET/CLAUDE.md.backup-$STAMP"
  ok "Backed up CLAUDE.md → CLAUDE.md.backup-$STAMP (current file kept for now)"
else
  info "No existing CLAUDE.md (will copy template directly)"
fi

if [[ -f "$TARGET/.git/hooks/pre-commit" && ! -L "$TARGET/.git/hooks/pre-commit" ]]; then
  cp "$TARGET/.git/hooks/pre-commit" "$TARGET/.git/hooks/pre-commit.backup-$STAMP"
  ok "Backed up .git/hooks/pre-commit"
fi

# ---- copy .claude/ ----------------------------------------------------------
hdr "Copying .claude/ assets"

mkdir -p "$TARGET/.claude"
for d in agents standards hooks commands skills rules scripts; do
  cp -r "$SOURCE/.claude/$d" "$TARGET/.claude/"
  ok ".claude/$d/ ($(ls "$TARGET/.claude/$d" | wc -l | tr -d ' ') items)"
done

# settings.json: 不覆盖现有项目定制；若 target 无 settings.json 则直接复制
if [[ -f "$BACKUP_DIR/settings.json" ]]; then
  cp "$SOURCE/.claude/settings.json" "$TARGET/.claude/settings.json.agf-template"
  cp "$BACKUP_DIR/settings.json"     "$TARGET/.claude/settings.json"
  warn "settings.json: kept your existing version. Template saved as settings.json.agf-template — manual merge needed"
else
  cp "$SOURCE/.claude/settings.json" "$TARGET/.claude/settings.json"
  ok "settings.json (from template)"
fi

# ---- copy root scripts -------------------------------------------------------
hdr "Copying root scripts"

cp "$SOURCE/init-team.sh"      "$TARGET/init-team.sh"
cp "$SOURCE/agf-team-start.sh" "$TARGET/agf-team-start.sh"
chmod +x "$TARGET/init-team.sh" "$TARGET/agf-team-start.sh"
chmod +x "$TARGET/.claude/hooks/"*.sh
chmod +x "$TARGET/.claude/scripts/"*.sh
ok "init-team.sh + agf-team-start.sh (+ executable bits on hooks/scripts)"

# ---- copy docs/ templates (non-destructive) ---------------------------------
hdr "Copying docs/ templates (non-destructive — won't overwrite existing)"

mkdir -p "$TARGET/docs/adr" "$TARGET/docs/prd" "$TARGET/docs/reviews" \
         "$TARGET/docs/qa" "$TARGET/docs/design" "$TARGET/docs/content" "$TARGET/docs/growth"

for f in FIRST_RUN.md team-capability-map.md product-workflow.md; do
  if [[ -f "$TARGET/docs/$f" ]]; then
    warn "docs/$f exists — skipped"
  else
    cp "$SOURCE/docs/$f" "$TARGET/docs/$f"
    ok "docs/$f"
  fi
done

# prd / reviews 模板
[[ -f "$TARGET/docs/prd/_TEMPLATE.md" ]] || cp "$SOURCE/docs/prd/_TEMPLATE.md" "$TARGET/docs/prd/" 2>/dev/null && ok "docs/prd/_TEMPLATE.md" || true
[[ -f "$TARGET/docs/reviews/retro-_TEMPLATE.md" ]] || cp "$SOURCE/docs/reviews/retro-_TEMPLATE.md" "$TARGET/docs/reviews/" 2>/dev/null && ok "docs/reviews/retro-_TEMPLATE.md" || true

# ADR-000 — 模板版与现有项目大概率不匹配；保存为 .template 由 user 重写
if [[ -f "$TARGET/docs/adr/000-system-architecture.md" ]]; then
  warn "docs/adr/000-system-architecture.md exists — kept; template saved as .agf-template"
  cp "$SOURCE/docs/adr/000-system-architecture.md" "$TARGET/docs/adr/000-system-architecture.md.agf-template"
else
  cp "$SOURCE/docs/adr/000-system-architecture.md" "$TARGET/docs/adr/000-system-architecture.md.agf-template"
  warn "ADR-000 saved as .agf-template — you MUST write project-specific 000-system-architecture.md"
fi

# ---- CLAUDE.md — 永远不覆盖，保留模板供手工合并 -----------------------------
cp "$SOURCE/CLAUDE.md" "$TARGET/CLAUDE.md.agf-template"
if [[ -f "$TARGET/CLAUDE.md.backup-$STAMP" ]]; then
  warn "CLAUDE.md: your project version kept; template saved as CLAUDE.md.agf-template — manual merge needed"
else
  cp "$SOURCE/CLAUDE.md" "$TARGET/CLAUDE.md"
  ok "CLAUDE.md (from template — review & customize)"
fi

# ---- progress/ ---------------------------------------------------------------
hdr "Setting up progress/ directory (Self-Reporting Pattern)"
mkdir -p "$TARGET/progress"
[[ -f "$TARGET/progress/README.md" ]] || cp "$SOURCE/progress/README.md" "$TARGET/progress/"
touch "$TARGET/progress/.gitkeep"
ok "progress/ ready"

# ---- tools/team-dashboard ---------------------------------------------------
# Zero-invasion observer (FastAPI SSE + React/Vite). Source-only copy;
# user runs `pip install -e ./server` + `pnpm install` in web/ on first start.
if [[ -d "$SOURCE/tools/team-dashboard" ]]; then
  hdr "Copying tools/team-dashboard (excluding node_modules / pytest_cache)"
  mkdir -p "$TARGET/tools"
  rsync -a \
    --exclude='node_modules' \
    --exclude='__pycache__' \
    --exclude='.pytest_cache' \
    --exclude='.venv' \
    --exclude='dist' \
    --exclude='*.egg-info' \
    "$SOURCE/tools/team-dashboard/" "$TARGET/tools/team-dashboard/"
  chmod +x "$TARGET/tools/team-dashboard/start.sh" 2>/dev/null || true
  ok "tools/team-dashboard ($(find "$TARGET/tools/team-dashboard" -type f | wc -l | tr -d ' ') files)"
fi

# ---- git pre-commit hook -----------------------------------------------------
hdr "Installing git pre-commit hook (secret scan)"
mkdir -p "$TARGET/.git/hooks"
ln -sf "../../.claude/hooks/scan-commit.sh" "$TARGET/.git/hooks/pre-commit"
ok ".git/hooks/pre-commit → .claude/hooks/scan-commit.sh"

# ---- generate next-steps doc -------------------------------------------------
hdr "Writing AGF_INSTALL_NEXT_STEPS.md to target"

cat > "$TARGET/AGF_INSTALL_NEXT_STEPS.md" <<EOF
# AGF Install — Next Steps

> Generated by AppGenesisForge \`install-to-existing.sh\` on $(date '+%Y-%m-%d %H:%M:%S').
> Backup stamp: \`$STAMP\`. Delete this file once you finish the checklist.

## 1. 合并 CLAUDE.md（必做）

你的旧 CLAUDE.md 保留为 \`CLAUDE.md\`（项目专属内容仍在）。
模板版本保存在 \`CLAUDE.md.agf-template\`。

**合并策略**：
- 保留 CLAUDE.md 你的项目特定段：\`Project Overview\` / \`Tech Stack\` / \`Quick Commands\` 等
- 从 \`CLAUDE.md.agf-template\` **追加**这几个团队基础设施段：
  - \`Project-Specific Rules\`（含 SSOT 指针 / 设计交付路径 / skill 调用提醒）
  - \`Tool Boundaries\`（四层 hook 防御说明）
  - \`Team Runtime Contract\`（角色 / 工作流 / standards 索引）

完成后删除：\`rm CLAUDE.md.agf-template CLAUDE.md.backup-$STAMP\`

## 2. 写 ADR-000（必做）

\`docs/adr/000-system-architecture.md.agf-template\` 是模板（FastAPI+React+Postgres）。
你必须基于本项目实际 stack 写自己的 \`docs/adr/000-system-architecture.md\`。

**推荐方式**：让 tech-lead 自动生成
\`\`\`bash
cd $TARGET
claude --agent tech-lead "基于现有代码（backend/ frontend/ miniapp/ 等）识别 ADR-000 基线，输出到 docs/adr/000-system-architecture.md"
\`\`\`

完成后删除：\`rm docs/adr/000-system-architecture.md.agf-template\`

## 3. 检查 .claude/settings.json（如有 .agf-template 后缀）

如果存在 \`.claude/settings.json.agf-template\`，说明你的项目已有 settings.json 被保留。

模板版含完整四层防御（permissions.deny / hooks 注册 / env），你的版本可能不全。
建议参考模板把缺的部分合并进 \`.claude/settings.json\`：
- \`permissions.deny\`（必加，否则 .env / SSH 等敏感路径不受保护）
- \`hooks\` 块（必加，否则 PreToolUse / UserPromptSubmit 等防御不触发）
- \`env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS\`（启用 Agent Teams）

完成后删除：\`rm .claude/settings.json.agf-template\`

## 4. 安装 Claude Code plugins（agent skills 依赖）

进入 \`$TARGET\` 后跑 \`claude\`，然后：

\`\`\`
/plugin install superpowers
/plugin install code-review
/plugin install code-simplifier
/plugin install feature-dev
/plugin install frontend-design     # 如有前端
/plugin install chrome-devtools-mcp # 如做 E2E
\`\`\`

## 5. Day-1 体检

\`\`\`bash
cd $TARGET
bash init-team.sh
\`\`\`

预期全绿。失败项按提示修复。

## 6. 首次启动 Agent Team

\`\`\`bash
cd $TARGET
./agf-team-start.sh
\`\`\`

按交互菜单选 teammate + 输入 feature 描述。

## 7.（可选）启动 team-dashboard

\`tools/team-dashboard/\` 是单任务只读 web 看板（FastAPI SSE + React/Vite），跑 \`agf-team-start\` 时可在另一个终端打开看实时进度。**零侵入**，不开也不影响团队。

首次启动：

\`\`\`bash
cd $TARGET/tools/team-dashboard
pip install -e ./server     # 一次性（建议进 venv）
(cd web && pnpm install)    # 一次性
./start.sh                  # 打开 http://localhost:5173/
\`\`\`

---

## 回滚（如出问题）

\`\`\`bash
cd $TARGET
rm -rf .claude
mv .claude.backup-$STAMP .claude
[ -f CLAUDE.md.backup-$STAMP ] && cp CLAUDE.md.backup-$STAMP CLAUDE.md
rm -f init-team.sh agf-team-start.sh AGF_INSTALL_NEXT_STEPS.md
rm -rf docs/FIRST_RUN.md docs/team-capability-map.md docs/product-workflow.md
[ -f .git/hooks/pre-commit.backup-$STAMP ] && mv .git/hooks/pre-commit.backup-$STAMP .git/hooks/pre-commit || rm -f .git/hooks/pre-commit
\`\`\`
EOF

ok "AGF_INSTALL_NEXT_STEPS.md written"

# ---- summary -----------------------------------------------------------------
hdr "DONE"

echo "Source : $SOURCE"
echo "Target : $TARGET"
echo "Backup : .claude.backup-$STAMP / CLAUDE.md.backup-$STAMP"
echo ""
echo "${BOLD}Next${N}: cd $TARGET && cat AGF_INSTALL_NEXT_STEPS.md"
