#!/bin/bash
# Server Manager - Linux 启动脚本
# 
# 用法:
#   ./scripts/run/run.sh                 # 进入交互式菜单
#   ./scripts/run/run.sh list            # 列出所有服务器
#   ./scripts/run/run.sh create -t game -i 1
#   ./scripts/run/run.sh start -s ddxq_game_s1
#   ./scripts/run/run.sh stop -s ddxq_game_s1
#   ./scripts/run/run.sh gui             # 启动 GUI（需要桌面环境）

set -e

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$ROOT"
export PYTHONPATH="$ROOT/src${PYTHONPATH:+:$PYTHONPATH}"

# 默认以项目根目录作为服务器根目录；部署到其它项目时可通过 SERVER_MANAGER_ROOT 覆盖。
SERVER_ROOT="${SERVER_MANAGER_ROOT:-$ROOT}"

# 优先使用 PyInstaller 打包的 ServerManager（Linux）：环境变量 SERVER_MANAGER_MAIN，或常见构建路径 src/dist/ServerManager/ServerManager
SM_MAIN="${SERVER_MANAGER_MAIN:-}"
if [[ -z "$SM_MAIN" ]] && [[ -x "$ROOT/src/dist/ServerManager/ServerManager" ]]; then
    SM_MAIN="$ROOT/src/dist/ServerManager/ServerManager"
fi

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Python
check_python() {
    if command -v python3 &> /dev/null; then
        PYTHON=python3
    elif command -v python &> /dev/null; then
        PYTHON=python
    else
        print_error "未找到 Python，请先安装 Python 3.6+"
        exit 1
    fi
    
    # 检查版本（兼容所有 Python 版本）
    PY_VERSION=$($PYTHON -c 'import sys; print(str(sys.version_info[0]) + "." + str(sys.version_info[1]))')
    print_info "使用 Python $PY_VERSION"
    
    # 检查是否为 Python 3.6+
    PY_MAJOR=$($PYTHON -c 'import sys; print(sys.version_info[0])')
    PY_MINOR=$($PYTHON -c 'import sys; print(sys.version_info[1])')
    if [ "$PY_MAJOR" -lt 3 ] || ([ "$PY_MAJOR" -eq 3 ] && [ "$PY_MINOR" -lt 6 ]); then
        print_error "需要 Python 3.6+，当前版本: $PY_VERSION"
        exit 1
    fi
}

# 检查并安装依赖
check_dependencies() {
    # 检查是否需要 GUI 模式
    if [ "$1" == "gui" ]; then
        if ! $PYTHON -c "import PyQt6" 2>/dev/null; then
            print_warn "正在安装 PyQt6..."
            pip3 install PyQt6 || pip install PyQt6
        fi
    fi
}

# 显示帮助
show_help() {
    echo "Server Manager - Linux 版本"
    echo ""
    echo "用法: $0 [命令] [参数]"
    echo ""
    echo "服务器根目录: $SERVER_ROOT"
    echo ""
    echo "命令:"
    echo "  (无参数)                进入交互式菜单"
    echo "  list                    列出所有服务器"
    echo "  create                  创建服务器"
    echo "  start                   启动服务器"
    echo "  stop                    停止服务器"
    echo "  connect                 连接到服务器"
    echo "  compile                 编译代码"
    echo "  regen                   重新生成 sys.config"
    echo "  info                    显示项目路径、版本和工具信息"
    echo "  status                  检查服务器节点在线状态"
    echo "  config                  查看或修改项目/服务器配置"
    echo "  logs                    列出、读取或检索服务器日志"
    echo "  command                 只生成并打印启动/停止/连接命令"
    echo "  ids                     查看已有服务器 ID 和下一个可用 ID"
    echo "  doctor                  检查目录、配置模板和外部工具"
    echo "  migrate                 手动执行项目配置迁移"
    echo "  gui                     启动 GUI 界面（需要桌面环境）"
    echo "  mcp                     启动 MCP stdio 服务"
    echo ""
    echo "start 命令参数:"
    echo "  --server, -s  服务器目录名 (必填)"
    echo "  --quick, -q   快速启动 (直接用 erl，不使用 rebar3)"
    echo "  --background, -b  后台运行 (打开新窗口/screen)"
    echo ""
    echo "compile 命令参数:"
    echo "  --target, -t  编译目标 (all/code/proto/table/tbllog, 默认 all)"
    echo "  --type        服务器类型 (game/login, 默认 game)"
    echo ""
    echo "示例:"
    echo "  $0                              # 交互式模式"
    echo "  $0 list                         # 列出服务器"
    echo "  $0 create --type game --id 1"
    echo "  $0 start -s ddxq_game_s1        # rebar3 模式，前台运行"
    echo "  $0 start -s ddxq_game_s1 -q     # 快速启动，前台运行"
    echo "  $0 start -s ddxq_game_s1 -b     # rebar3 模式，后台运行"
    echo "  $0 start -s ddxq_game_s1 -q -b  # 快速启动，后台运行"
    echo "  $0 stop -s ddxq_game_s1"
    echo "  $0 compile                      # 编译游戏服"
    echo "  $0 compile --type login         # 编译登录服"
    echo "  $0 compile -t code              # 只编译游戏服代码"
    echo "  $0 compile -t code --type login # 只编译登录服代码"
    echo "  $0 status --json                # JSON 输出节点状态"
    echo "  $0 config show -s ddxq_game_s1  # 查看单服合并配置"
    echo "  $0 logs search ddxq_game_s1 error"
    echo "  $0 command start ddxq_game_s1   # 只打印启动命令"
    echo "  $0 mcp                          # 启动 MCP 服务"
    echo ""
    echo "更多帮助: $PYTHON -m entrypoints.cli --help"
    if [[ -n "${SM_MAIN:-}" ]]; then
        echo ""
        echo "已检测到打包程序: $SM_MAIN"
        echo "  也可直接: $SM_MAIN list"
        echo "  GUI: $SM_MAIN   （无参数）"
    fi
}

# 主函数
main() {
    if [ "${1:-}" = "mcp" ]; then
        if [[ -n "${SM_MAIN:-}" ]]; then
            exec "$SM_MAIN" --root "$SERVER_ROOT" mcp
        fi
        if command -v python3 >/dev/null 2>&1; then
            exec python3 -m entrypoints.cli --root "$SERVER_ROOT" mcp
        elif command -v python >/dev/null 2>&1; then
            exec python -m entrypoints.cli --root "$SERVER_ROOT" mcp
        else
            echo "[ERROR] Python not found. Install Python 3.6+" >&2
            exit 1
        fi
    fi

    check_python
    
    print_info "服务器根目录: $SERVER_ROOT"
    
    # 如果没有参数，进入交互式模式
    if [ $# -eq 0 ]; then
        if [[ -n "${SM_MAIN:-}" ]]; then
            print_info "使用打包程序: $SM_MAIN"
            exec "$SM_MAIN" --root "$SERVER_ROOT" interactive
        fi
        $PYTHON -m entrypoints.cli --root "$SERVER_ROOT" interactive
        exit 0
    fi
    
    case "$1" in
        gui)
            check_dependencies gui
            print_info "启动 GUI 界面..."
            if [[ -n "${SM_MAIN:-}" ]]; then
                exec "$SM_MAIN"
            fi
            $PYTHON -m entrypoints
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            # 其他命令传递给 CLI 工具，自动传递服务器根目录
            if [[ -n "${SM_MAIN:-}" ]]; then
                exec "$SM_MAIN" --root "$SERVER_ROOT" "$@"
            fi
        $PYTHON -m entrypoints.cli --root "$SERVER_ROOT" "$@"
            ;;
    esac
}

main "$@"
