#!/bin/bash
# moziplus v2 E2E 测试准备脚本
# 功能：停止服务 → 备份当前数据 → 清理测试残留 → 准备干净测试环境
# 用法：bash scripts/e2e-prepare.sh

set -e

TARGET_DIR="${MOZIPLUS_V2_DIR:-$HOME/.sanguo_projects/sanguo_moziplus_v2}"
DATA_DIR="$TARGET_DIR/data"
BACKUP_DIR="$TARGET_DIR/.e2e-backup"
REGISTRY="$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
DATA_DIR="$TARGET_DIR/data"
BACKUP_DIR="$TARGET_DIR/.e2e-backup"
REGISTRY="$DATA_DIR/_registry.yaml"

echo "=== moziplus v2 E2E 测试准备 ==="
echo "时间: $(date)"
echo ""

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

# Step 2: 备份当前数据
echo "💾 [2/5] 备份当前数据到 .e2e-backup/..."
mkdir -p "$BACKUP_DIR"

# 备份注册表
if [ -f "$REGISTRY" ]; then
  cp "$REGISTRY" "$BACKUP_DIR/_registry.yaml.bak.$TIMESTAMP"
  echo "  ✅ 注册表已备份"
fi

# 备份 _mail 项目 DB
if [ -d "$DATA_DIR/_mail" ]; then
  mkdir -p "$BACKUP_DIR/_mail"
  cp "$DATA_DIR/_mail/blackboard.db" "$BACKUP_DIR/_mail/blackboard.db.bak.$TIMESTAMP" 2>/dev/null || true
  echo "  ✅ _mail DB 已备份"
fi

# 备份 demo 项目
if [ -d "$DATA_DIR/demo" ]; then
  mkdir -p "$BACKUP_DIR/demo"
  cp "$DATA_DIR/demo/blackboard.db" "$BACKUP_DIR/demo/blackboard.db.bak.$TIMESTAMP" 2>/dev/null || true
  echo "  ✅ demo DB 已备份"
fi

# 备份 e2e-routing-test 项目
if [ -d "$DATA_DIR/e2e-routing-test" ]; then
  mkdir -p "$BACKUP_DIR/e2e-routing-test"
  cp "$DATA_DIR/e2e-routing-test/blackboard.db" "$BACKUP_DIR/e2e-routing-test/blackboard.db.bak.$TIMESTAMP" 2>/dev/null || true
  echo "  ✅ e2e-routing-test DB 已备份"
fi

# Step 3: 清理 e2e 残留数据
echo "🧹 [3/5] 清理 e2e-v27 残留数据..."
COUNT=$(ls -d "$DATA_DIR"/e2e-v27-* 2>/dev/null | wc -l | tr -d ' ')
if [ "$COUNT" -gt 0 ]; then
  rm -rf "$DATA_DIR"/e2e-v27-*
  echo "  ✅ 已清理 $COUNT 个 e2e-v27 项目目录"
else
  echo "  ℹ️ 无 e2e-v27 残留数据"
fi

# 清理 e2e-routing-test
if [ -d "$DATA_DIR/e2e-routing-test" ]; then
  rm -rf "$DATA_DIR/e2e-routing-test"
  echo "  ✅ 已清理 e2e-routing-test"
fi

# 清理 debug-task-1
if [ -d "$DATA_DIR/debug-task-1" ]; then
  rm -rf "$DATA_DIR/debug-task-1"
  echo "  ✅ 已清理 debug-task-1"
fi

# Step 4: 清理注册表中的测试项目
echo "📋 [4/5] 清理注册表..."
python3 -c "
import yaml
with open('$REGISTRY') as f:
    reg = yaml.safe_load(f) or {}
before = len(reg.get('projects', {}))
reg['projects'] = {k: v for k, v in reg.get('projects', {}).items() 
                   if not k.startswith('e2e-') and not k.startswith('debug-')}
after = len(reg.get('projects', {}))
with open('$REGISTRY', 'w') as f:
    yaml.dump(reg, f, default_flow_style=False, allow_unicode=True)
print(f'  ✅ 清理了 {before - after} 个测试项目注册（保留 {after} 个）')
"

# Step 5: 清理 _mail 中的测试数据
echo "📬 [5/5] 清理 _mail 测试数据..."
MAIL_DB="$DATA_DIR/_mail/blackboard.db"
if [ -f "$MAIL_DB" ]; then
  python3 -c "
import sqlite3
conn = sqlite3.connect('$MAIL_DB')
# 删除测试产生的邮件（subject 包含 e2e 或 test）
deleted = conn.execute(\"DELETE FROM tasks WHERE title LIKE '%e2e%' OR title LIKE '%E2E%' OR title LIKE '%test-%'\").rowcount
conn.commit()
conn.close()
print(f'  ✅ 清理了 {deleted} 条测试邮件')
" 2>/dev/null || echo "  ⚠️ _mail DB 清理失败（可忽略）"
else
  echo "  ℹ️ _mail DB 不存在"
fi

echo ""
echo "=== 准备完成 ==="
echo "备份位置: $BACKUP_DIR"
echo "现在可以运行 E2E 测试了"
