#!/bin/bash
# 宇之然AI平台 - 项目初始化脚本

set -e

echo "🚀 开始初始化宇之然AI平台..."

# 检查MySQL是否运行
if ! mysqladmin ping -h localhost --silent 2>/dev/null; then
    echo "❌ MySQL未运行，请先启动MySQL服务"
    echo "   Ubuntu/Debian: sudo systemctl start mysql"
    echo "   CentOS: sudo systemctl start mysqld"
    exit 1
fi

# 创建数据库
echo "📦 创建数据库..."
read -p "请输入MySQL root密码: " -s MYSQL_ROOT_PASSWORD
echo

mysql -u root -p"$MYSQL_ROOT_PASSWORD" -e "CREATE DATABASE IF NOT EXISTS yuzhiran_ai CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null || {
    echo "❌ 数据库创建失败，请检查MySQL密码"
    exit 1
}

# 更新后端.env中的数据库密码
sed -i "s|mysql://root:password@|mysql://root:${MYSQL_ROOT_PASSWORD}@|" backend/.env

echo "✅ 数据库配置完成"

# 安装后端依赖
echo "📦 安装后端依赖..."
cd backend
npm install
npx prisma generate
npx prisma db push
cd ..

# 安装前端依赖
echo "📦 安装前端依赖..."
cd frontend
npm install
cd ..

echo "✅ 初始化完成！"
echo ""
echo "启动方式："
echo "  后端: cd backend && npm run dev"
echo "  前端: cd frontend && npm run dev"
echo ""
echo "访问地址："
echo "  前端: http://localhost:3001"
echo "  后端API文档: http://localhost:3000/api"
