#!/bin/bash
# moziplus v2 E2E 测试恢复脚本（恢复出厂设置）
# 功能：从备份恢复数据 → 清理测试残留 → 重启服务
# 用法：bash scripts/e2e-restore.sh

set -e

TARGET_DIR="${MOZIPLUS_V2_DIR:-$HOME/.sanguo_projects/sanguo_moziplus_v2}"
DATA_DIR="$HOME/.sanguo_projects/sanguo_moziplus/data"
V2_DATA_DIR="$TARGET_DIR/data"
BACKUP_DIR="$TARGET_DIR/.e2e-backup"
REGISTRY="$V2_DATA_DIR/_registry.yaml"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# 解析参数
for arg in "$@"; do
  case "$arg" in
    --target=*) TARGET_DIR="${arg#*=}" ;;
  esac
done
V2_DATA_DIR="$TARGET_DIR/data"
BACKUP_DIR="$TARGET_DIR/.e2e-backup"
REGISTRY="$V2_DATA_DIR/_registry.yaml"

echo "=== moziplus v2 恢复出厂设置 ==="
echo "时间: $(date)"
echo ""

# Step 1: 停止服务
echo "📦 [1/4] 停止 moziplus-v2 服务..."
pm2 stop sanguo-moziplus-v2 2>/dev/null && echo "  ✅ 服务已停止" || echo "  ⚠️ 服务未运行"

# Step 2: 查找最新备份
LATEST_BACKUP=$(ls -t "$BACKUP_DIR"/_registry.yaml.bak.* 2>/dev/null | head -1)
if [ -z "$LATEST_BACKUP" ]; then
  echo "❌ 未找到备份数据，无法恢复"
  echo "  将执行全新初始化..."
  
  # 全新初始化：清理所有数据
  echo "🧹 清理所有项目数据..."
  for d in "$V2_DATA_DIR"/*/; do
    dirname=$(basename "$d")
    if [ "$dirname" != "_mail" ]; then
      rm -rf "$d"
      echo "  已删除: $dirname"
    fi
  done
  
  # 重建干净注册表
  echo "projects:" > "$REGISTRY"
  echo "  ✅ 注册表已重置"
  
  # 重建 _mail DB
  python3 -c "
from pathlib import Path
import sys
sys.path.insert(0, '$HOME/.sanguo_projects/sanguo_moziplus_v2')
from src.blackboard.db import init_db
init_db(Path('$V2_DATA_DIR/_mail/blackboard.db'))
print('  ✅ _mail DB 已重建')
"
  
  echo ""
  echo "=== 全新初始化完成 ==="
  exit 0
fi

echo "📂 找到备份: $LATEST_BACKUP"

# Step 3: 恢复数据
echo "💾 [2/4] 恢复数据..."

# 恢复注册表
cp "$LATEST_BACKUP" "$REGISTRY"
echo "  ✅ 注册表已恢复"

# 恢复 _mail DB
MAIL_BACKUP=$(ls -t "$BACKUP_DIR/_mail/"blackboard.db.bak.* 2>/dev/null | head -1)
if [ -n "$MAIL_BACKUP" ]; then
  cp "$MAIL_BACKUP" "$V2_DATA_DIR/_mail/blackboard.db"
  echo "  ✅ _mail DB 已恢复"
fi

# 恢复 demo DB
DEMO_BACKUP=$(ls -t "$BACKUP_DIR/demo/"blackboard.db.bak.* 2>/dev/null | head -1)
if [ -n "$DEMO_BACKUP" ]; then
  mkdir -p "$V2_DATA_DIR/demo"
  cp "$DEMO_BACKUP" "$V2_DATA_DIR/demo/blackboard.db"
  echo "  ✅ demo DB 已恢复"
fi

# Step 4: 清理测试产生的项目
echo "🧹 [3/4] 清理测试产生的项目..."
for d in "$V2_DATA_DIR"/e2e-v27-*/; do
  [ -d "$d" ] && rm -rf "$d" && echo "  已删除: $(basename $d)"
done
for d in "$V2_DATA_DIR"/e2e-routing-test/; do
  [ -d "$d" ] && rm -rf "$d" && echo "  已删除: $(basename $d)"
done
for d in "$V2_DATA_DIR"/debug-task-*/; do
  [ -d "$d" ] && rm -rf "$d" && echo "  已删除: $(basename $d)"
done

echo "🔄 [4/4] 重启 moziplus-v2 服务..."
pm2 restart sanguo-moziplus-v2 2>/dev/null && echo "  ✅ 服务已重启" || echo "  ⚠️ 重启失败，请手动检查"

echo ""
echo "=== 恢复完成 ==="
echo "服务状态:"
pm2 status sanguo-moziplus-v2 2>/dev/null || true
