#!/bin/bash

# ============================================
# 初中物理作业批改工作流 - 快速部署脚本
# ============================================

set -e

echo "======================================"
echo "  初中物理作业批改工作流 - 部署向导"
echo "======================================"
echo ""

# 检测操作系统
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="Linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macOS"
elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
    OS="Windows"
else
    OS="Unknown"
fi

echo "检测到操作系统: $OS"
echo ""

# 步骤1: 检查Python版本
echo "步骤 1/5: 检查 Python 版本..."
if command -v python3 &> /dev/null; then
    PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
    PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1)
    PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d. -f2)
    
    if [ "$PYTHON_MAJOR" -ge 3 ] && [ "$PYTHON_MINOR" -ge 10 ]; then
        echo "✅ Python 版本: $PYTHON_VERSION"
    else
        echo "❌ Python 版本过低: $PYTHON_VERSION (需要 3.10+)"
        exit 1
    fi
else
    echo "❌ 未找到 Python 3"
    exit 1
fi
echo ""

# 步骤2: 创建虚拟环境
echo "步骤 2/5: 创建虚拟环境..."
if [ ! -d "venv" ]; then
    python3 -m venv venv
    echo "✅ 虚拟环境已创建"
else
    echo "✅ 虚拟环境已存在"
fi
echo ""

# 步骤3: 激活虚拟环境
echo "步骤 3/5: 激活虚拟环境..."
if [ "$OS" == "Windows" ]; then
    source venv/Scripts/activate
else
    source venv/bin/activate
fi
echo "✅ 虚拟环境已激活"
echo ""

# 步骤4: 安装依赖
echo "步骤 4/5: 安装依赖包..."
if [ -f "requirements.txt" ]; then
    pip install --upgrade pip
    pip install -r requirements.txt
    echo "✅ 依赖安装完成"
else
    echo "❌ 未找到 requirements.txt"
    exit 1
fi
echo ""

# 步骤5: 配置环境变量
echo "步骤 5/5: 配置环境变量..."
if [ ! -f ".env" ]; then
    if [ -f ".env.example" ]; then
        cp .env.example .env
        echo "✅ 已创建 .env 文件"
        echo ""
        echo "⚠️  请编辑 .env 文件，填写以下必需配置："
        echo "   - LLM_API_KEY"
        echo "   - LLM_BASE_URL"
        echo "   - LLM_MODEL_NAME"
        echo ""
        echo "注意：不需要配置对象存储（图片直接使用原始URL）"
        echo ""
        echo "编辑完成后，运行以下命令启动服务："
        echo "  source .env"
        echo "  bash scripts/http_run.sh -p 8000"
    else
        echo "❌ 未找到 .env.example"
        exit 1
    fi
else
    echo "✅ .env 文件已存在"
    echo ""
    echo "启动服务："
    echo "  source .env"
    echo "  bash scripts/http_run.sh -p 8000"
fi
echo ""

echo "======================================"
echo "  ✅ 部署完成！"
echo "======================================"
