#!/bin/bash
# AI有声书生成工具 - 启动脚本
# 第二期开发环境

set -e

echo "🚀 开始启动服务..."

# 1. 安装后端依赖
echo "📦 安装后端依赖..."
cd server && npm install

# 2. 数据库迁移
echo "🗄️ 执行数据库迁移..."
cd server && npx prisma generate
cd server && npx prisma db push

# 3. 启动后端服务
echo "🔥 启动后端服务..."
cd server && npm run dev &
BACKEND_PID=$!

# 4. 等待后端启动
echo "⏳ 等待后端服务启动..."
sleep 8

# 5. 验证后端服务
echo "✅ 验证后端服务..."
curl -f http://localhost:3000/health || echo "后端服务启动失败"
curl -f http://localhost:3000/api/audio/list || echo "API服务可能未就绪"

echo ""
echo "🎉 服务启动完成!"
echo "后端服务: http://localhost:3000"
echo "前端服务: npm run dev:h5 (在 my-uniapp-vue3 目录)"
echo "前端访问: http://localhost:5173"
echo "后端进程PID: $BACKEND_PID"

# 6. 可选：运行自动化冒烟测试
if [ "$1" = "--test" ] || [ "$1" = "-t" ]; then
  echo ""
  echo "🧪 运行自动化冒烟测试..."
  cd server && npx playwright test --project=smoke --config=tests/playwright.config.ts
  TEST_EXIT=$?
  if [ $TEST_EXIT -eq 0 ]; then
    echo "✅ 冒烟测试全部通过！"
  else
    echo "❌ 冒烟测试存在失败，请检查！"
  fi
fi
