#!/bin/bash

echo "🚀 启动大模型微调平台..."
echo ""

# 确保在正确的目录中
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "📂 当前目录: $SCRIPT_DIR"
echo ""

# 获取本机IP地址
SERVER_IP=$(hostname -I | awk '{print $1}')

# 从 config.yaml 读取端口配置
CONFIG_FILE="$SCRIPT_DIR/../config.yaml"
if [ -f "$CONFIG_FILE" ]; then
    # 使用 python 读取 yaml 文件
    WEB_PORT=$(python3 -c "import yaml; print(yaml.safe_load(open('$CONFIG_FILE'))['app'].get('web_port', 7862))" 2>/dev/null)
    if [ -z "$WEB_PORT" ]; then
        WEB_PORT=7862
    fi
else
    WEB_PORT=7862
fi

echo "请选择启动方式:"
echo "1) 直接打开文件（本地访问）"
echo "2) 启动HTTP服务器（可通过IP访问）"
echo ""

read -p "请输入选择 (1-2): " choice

case $choice in
    1)
        echo ""
        echo "🌐 打开本地文件..."
        echo "   - 主页: file://$SCRIPT_DIR/pages/main.html"
        echo "   - 登录: file://$SCRIPT_DIR/pages/login.html"
        echo ""

        # 检测操作系统并打开浏览器
        if [[ "$OSTYPE" == "darwin"* ]]; then
            # macOS
            open "pages/main.html"
        elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
            # Linux
            xdg-open "pages/main.html"
        elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
            # Windows (Git Bash or Cygwin)
            start "pages/main.html"
        else
            echo "请手动打开以下文件:"
            echo "   $SCRIPT_DIR/pages/main.html"
        fi

        echo "✅ 已在浏览器中打开主页"
        ;;

    2)
        echo ""
        echo "🌐 本机 IP 地址: $SERVER_IP"
        echo ""

        # 检查Python是否可用
        if command -v python3 &> /dev/null; then
            PYTHON_CMD="python3"
        elif command -v python &> /dev/null; then
            PYTHON_CMD="python"
        else
            echo "❌ 错误: 未找到 Python"
            echo "请安装 Python 或使用方式 1 直接打开文件"
            exit 1
        fi

        echo "📱 访问地址:"
        echo "   - 主页: http://$SERVER_IP:$WEB_PORT/pages/main.html"
        echo "   - 登录: http://$SERVER_IP:$WEB_PORT/pages/login.html"
        echo ""
        echo "⚠️  服务器将在端口 $WEB_PORT 启动"
        echo "按 Ctrl+C 停止服务器"
        echo ""

        # 启动HTTP服务器
        $PYTHON_CMD -m http.server $WEB_PORT
        ;;

    *)
        echo "❌ 无效选择，请运行脚本重新选择"
        exit 1
        ;;
esac
