#!/bin/bash

# 少儿智慧阅读 - 启动脚本

echo "🚀 启动少儿智慧阅读..."
echo ""

# 检查项目目录
BACKEND_DIR="/Users/retirado/ccProgram/reading-platform-backend"
FRONTEND_DIR="/Users/retirado/ccProgram/reading-platform-frontend"

# 检查Node.js
if ! command -v node &> /dev/null; then
    echo "❌ Node.js 未安装，请先安装 Node.js >= 18.0.0"
    exit 1
fi

echo "✅ Node.js 版本: $(node --version)"
echo "✅ npm 版本: $(npm --version)"
echo ""

# 选择数据库模式
echo "请选择数据库模式："
echo "1) SQLite（快速启动，无需安装数据库）"
echo "2) PostgreSQL（完整功能，需要先安装PostgreSQL）"
read -p "请输入选择 (1/2): " db_choice

if [ "$db_choice" = "2" ]; then
    # PostgreSQL 模式
    if ! command -v psql &> /dev/null; then
        echo "⚠️  PostgreSQL 未检测到"
        echo "请先安装 PostgreSQL 或选择 SQLite 模式"
        echo ""
        echo "macOS 安装 PostgreSQL:"
        echo "  brew install postgresql@15"
        echo "  brew services start postgresql@15"
        exit 1
    fi

    # 使用PostgreSQL
    echo "DATABASE_URL=\"postgresql://admin:password@localhost:5432/reading_platform\"" > $BACKEND_DIR/.env.development
else
    # SQLite 模式
    echo "DATABASE_URL=\"file:./dev.db\"" > $BACKEND_DIR/.env.development
fi

# 添加其他环境变量
cat >> $BACKEND_DIR/.env.development << 'EOF'
NODE_ENV=development
PORT=3000
JWT_SECRET="your-super-secret-jwt-key"
JWT_EXPIRES_IN="7d"
FRONTEND_URL="http://localhost:5173"
EOF

echo ""
echo "📦 安装后端依赖..."
cd $BACKEND_DIR
if [ ! -d "node_modules" ]; then
    npm install
fi

echo ""
echo "🔧 配置数据库..."
npx prisma generate

if [ "$db_choice" = "2" ]; then
    echo "⚠️  请确保已创建PostgreSQL数据库 'reading_platform'"
    echo "   创建命令："
    echo "   createdb reading_platform -U admin"
    read -p "按Enter继续..."
else
    echo "📊 使用SQLite数据库"
fi

npx prisma migrate dev --name init

echo ""
echo "🚀 启动后端服务..."
npm run start:dev &
BACKEND_PID=$!

# 等待后端启动
sleep 5

echo ""
echo "📦 安装前端依赖..."
cd $FRONTEND_DIR
if [ ! -d "node_modules" ]; then
    npm install
fi

echo ""
echo "🚀 启动前端服务..."
npm run dev &
FRONTEND_PID=$!

echo ""
echo "✅ 服务启动完成！"
echo ""
echo "📍 访问地址："
echo "   前端：http://localhost:5173"
echo "   后端：http://localhost:3000/api/v1"
echo ""
echo "🔑 测试账号："
echo "   超管端：admin / 123456"
echo ""
echo "按 Ctrl+C 停止所有服务"

# 等待用户中断
wait
