#!/bin/bash

# AIGC Demo 启动脚本
# 支持环境变量配置

echo "=== AIGC Demo 启动脚本 ==="
echo ""

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "❌ Java未安装或未配置到PATH"
    echo "请安装Java 21或更高版本"
    exit 1
fi

# 检查Java版本
JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f1)
if [ "$JAVA_VERSION" -lt 21 ]; then
    echo "❌ Java版本过低，需要Java 21或更高版本"
    echo "当前版本: $(java -version 2>&1 | head -n 1)"
    exit 1
fi

echo "✅ Java版本检查通过: $(java -version 2>&1 | head -n 1)"

# 检查Maven
if ! command -v mvn &> /dev/null; then
    echo "❌ Maven未安装或未配置到PATH"
    exit 1
fi

echo "✅ Maven检查通过: $(mvn -version | head -n 1)"

# 检查环境变量文件
if [ -f ".env" ]; then
    echo "✅ 发现.env文件，加载环境变量"
    export $(cat .env | grep -v '^#' | xargs)
else
    echo "⚠️  未发现.env文件，使用默认配置"
    echo "   如需自定义配置，请复制env.example为.env并修改"
fi

# 设置默认环境变量
export DB_URL=${DB_URL:-"jdbc:mysql://localhost:3306/aigc?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true"}
export DB_USERNAME=${DB_USERNAME:-"root"}
export DB_PASSWORD=${DB_USERNAME:-"177615"}
export JWT_SECRET=${JWT_SECRET:-"aigc-demo-secret-key-for-jwt-token-generation-very-long-secret-key"}
export JWT_EXPIRATION=${JWT_EXPIRATION:-"604800000"}

# 检查数据库连接
echo ""
echo "🔍 检查数据库连接..."
if command -v mysql &> /dev/null; then
    if mysql -h localhost -u "$DB_USERNAME" -p"$DB_PASSWORD" -e "SELECT 1;" &> /dev/null; then
        echo "✅ 数据库连接正常"
    else
        echo "⚠️  数据库连接失败，请检查配置"
        echo "   数据库URL: $DB_URL"
        echo "   用户名: $DB_USERNAME"
    fi
else
    echo "⚠️  未安装MySQL客户端，跳过数据库连接检查"
fi

# 编译项目
echo ""
echo "🔨 编译项目..."
if mvn clean compile -q; then
    echo "✅ 项目编译成功"
else
    echo "❌ 项目编译失败"
    exit 1
fi

# 启动应用
echo ""
echo "🚀 启动应用..."
echo "   配置文件: application-dev.properties"
echo "   端口: 8080"
echo "   日志文件: startup.log"
echo ""

# 创建日志目录
mkdir -p logs

# 启动应用
java -jar target/demo-0.0.1-SNAPSHOT.jar \
    --spring.profiles.active=dev \
    --server.port=8080 \
    --logging.file.name=logs/application.log \
    > startup.log 2>&1 &

# 获取进程ID
APP_PID=$!
echo "📝 应用进程ID: $APP_PID"
echo "📝 进程ID已保存到: app.pid"

# 保存进程ID
echo $APP_PID > app.pid

# 等待应用启动
echo "⏳ 等待应用启动..."
for i in {1..30}; do
    if curl -s http://localhost:8080/api/public/health &> /dev/null; then
        echo ""
        echo "🎉 应用启动成功！"
        echo ""
        echo "📱 访问地址:"
        echo "   后端API: http://localhost:8080"
        echo "   前端应用: http://localhost:3000 (需要单独启动)"
        echo "   健康检查: http://localhost:8080/api/public/health"
        echo ""
        echo "🛑 停止应用: kill $APP_PID 或运行 ./stop.sh"
        echo "📋 查看日志: tail -f startup.log"
        echo ""
        break
    fi
    echo -n "."
    sleep 1
done

if [ $i -eq 30 ]; then
    echo ""
    echo "❌ 应用启动超时"
    echo "📋 查看日志: cat startup.log"
    exit 1
fi


