#!/bin/bash
# 快速部署：本地构建 → rsync → pm2 reload
# 用法: bash deploy-fast.sh           # 仅后端
#       bash deploy-fast.sh --all     # 后端+前端
#       bash deploy-fast.sh --dry     # 预览变更文件

set -e

HOST="root@8.159.134.106"
PORT="22622"
REMOTE_DIR="/data/ai/audio_codebuddy/server"
LOCAL_DIR="c:/Users/caoyg/ai/audio-tts/audio_codebuddy/server"
SSH_OPTS="-p $PORT -o StrictHostKeyChecking=no"

DRY=false
DEPLOY_ALL=false
while [[ $# -gt 0 ]]; do
  case $1 in --dry) DRY=true; shift;; --all) DEPLOY_ALL=true; shift;; *) shift;;
  esac
done

# 1. 构建
echo "=== 构建后端 ==="
cd "$LOCAL_DIR"
npm run build

# 2. rsync（增量同步，只传变化的文件）
SYNC_FILES=(
  "dist/"
  "prisma/schema.prisma"
  "src/config/models.json"
  "package.json"
)

RSYNC_ARGS="-avz --delete -e \"ssh $SSH_OPTS\""
if [ "$DRY" = true ]; then
  RSYNC_ARGS="$RSYNC_ARGS --dry-run"
fi

echo "=== 同步文件 ==="
for f in "${SYNC_FILES[@]}"; do
  echo "  $f"
  rsync $RSYNC_ARGS "$LOCAL_DIR/$f" "$HOST:$REMOTE_DIR/$f"
done

# 3. 服务器操作
if [ "$DRY" = true ]; then
  echo "=== DRY RUN 完成 ==="
  exit 0
fi

echo "=== 服务器部署 ==="
ssh $SSH_OPTS $HOST << 'ENDSSH'
cd /data/ai/audio_codebuddy/server

# 只在新依赖变化时才 install
if [ package.json -nt node_modules ]; then
  echo "依赖有更新，安装..."
  npm install --production
  touch node_modules  # 更新时间戳
fi

# 复制 models.json 到 dist（确保运行时能读到）
cp src/config/models.json dist/config/models.json 2>/dev/null || true

# Prisma generate（只 schema 变化时才需要）
if [ prisma/schema.prisma -nt node_modules/.prisma ]; then
  echo "Prisma schema 有更新，生成 Client..."
  npx prisma generate
fi

# 重启
pm2 reload server
echo ""
echo "=== 部署完成 ==="
pm2 status | grep server
ENDSSH

# 4. 验证
echo ""
echo "=== 验证部署 ==="
sleep 3
echo -n "API健康检查: "
curl -s -o /dev/null -w "%{http_code}" http://book.rrbrr.com/api/health 2>/dev/null || echo "检查失败"

echo ""
echo "git commit: $(cd $LOCAL_DIR && git log --oneline -1)"
echo "服务器版本: $(ssh $SSH_OPTS $HOST 'cd /data/ai/audio_codebuddy/server && git log --oneline -1')"
