#!/bin/bash

# PVE Manager 启动脚本
# PVE Manager Start Script

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

print_header() {
    echo -e "${PURPLE}========================================${NC}"
    echo -e "${PURPLE}    $1${NC}"
    echo -e "${PURPLE}========================================${NC}"
}

# 获取本机IP地址
get_local_ip() {
    if command -v ip >/dev/null 2>&1; then
        ip route get 8.8.8.8 2>/dev/null | grep -oP 'src \K[^ ]+' | head -1
    elif command -v hostname >/dev/null 2>&1; then
        hostname -I 2>/dev/null | awk '{print $1}'
    else
        ifconfig 2>/dev/null | grep -E 'inet.*broadcast' | grep -v '127.0.0.1' | awk '{print $2}' | head -1
    fi
}

# 验证IP地址格式
validate_ip() {
    local ip=$1
    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        return 0
    else
        return 1
    fi
}

# 验证端口号
validate_port() {
    local port=$1
    if [[ $port =~ ^[0-9]+$ ]] && [ $port -ge 1000 ] && [ $port -le 65535 ]; then
        return 0
    else
        return 1
    fi
}

# 加载环境变量
load_env() {
    if [[ -f ".env.global" ]]; then
        print_info "加载全局配置文件: .env.global"
        set -a
        source .env.global
        set +a
        return 0
    else
        return 1
    fi
}

# 保存环境变量到文件
save_env() {
    cat > .env.global << EOF
# PVE Manager 全局配置文件
# Global configuration file for PVE Manager
# 生成时间: $(date)

# 服务器配置 / Server Configuration
SERVER_HOST=${SERVER_HOST}
SERVER_PORT=${SERVER_PORT}

# 客户端配置 / Client Configuration  
CLIENT_HOST=${CLIENT_HOST}
CLIENT_PORT=${CLIENT_PORT}

# API配置 / API Configuration
API_HOST=${API_HOST}

# WebSocket配置 / WebSocket Configuration
WS_HOST=${WS_HOST}

# 运行环境 / Environment
NODE_ENV=${NODE_ENV}

# CORS配置 / CORS Configuration
ALLOWED_ORIGINS=${ALLOWED_ORIGINS}

# 数据库配置 / Database Configuration
DB_PATH=${DB_PATH}

# 日志配置 / Logging Configuration
LOG_LEVEL=${LOG_LEVEL}
EOF
    print_success "配置已保存到: .env.global"
}

# 创建前端环境配置
create_client_env() {
    local protocol="http"
    local ws_protocol="ws"
    
    if [[ "${NODE_ENV}" == "production" ]]; then
        protocol="https"  
        ws_protocol="wss"
    fi
    
    # 确保client目录存在
    print_info "当前目录: $(pwd)"
    if [[ ! -d "client" ]]; then
        print_error "找不到client目录，请确保在项目根目录运行此脚本"
        print_info "目录内容: $(ls -la)"
        return 1
    fi
    
    cat > client/.env << EOF
# 前端环境配置 - 由start.sh自动生成
# Frontend environment configuration - Generated by start.sh
# 生成时间: $(date)

VITE_API_BASE_URL=${protocol}://${API_HOST}:${SERVER_PORT}
VITE_WS_URL=${ws_protocol}://${WS_HOST}:${SERVER_PORT}
VITE_ENV=${NODE_ENV}
EOF
    print_success "前端配置已生成: client/.env"
}

# 项目初始化配置
init_project() {
    print_header "PVE Manager 项目初始化"
    
    print_info "开始配置项目参数..."
    echo ""
    
    # 获取本机IP作为建议
    local suggested_ip
    suggested_ip=$(get_local_ip)
    
    # 部署模式选择
    echo "请选择部署模式:"
    echo "1) 本地开发 (服务器和客户端在同一台机器)"  
    echo "2) 局域网部署 (服务器和客户端在不同机器)"
    echo "3) 生产环境部署"
    echo ""
    read -p "请选择 [1-3]: " deploy_mode
    
    case $deploy_mode in
        1)
            print_info "选择: 本地开发模式"
            SERVER_HOST="0.0.0.0"
            CLIENT_HOST="0.0.0.0"
            API_HOST="localhost"
            WS_HOST="localhost"
            NODE_ENV="development"
            ;;
        2)
            print_info "选择: 局域网部署模式"
            SERVER_HOST="0.0.0.0"
            CLIENT_HOST="0.0.0.0"
            
            if [[ -n "$suggested_ip" ]]; then
                echo "检测到本机IP: $suggested_ip"
                read -p "使用检测到的IP? [Y/n]: " use_detected
                if [[ $use_detected =~ ^[Nn]$ ]]; then
                    read -p "请输入服务器IP地址: " custom_ip
                    if validate_ip "$custom_ip"; then
                        API_HOST=$custom_ip
                        WS_HOST=$custom_ip
                    else
                        print_error "无效的IP地址"
                        exit 1
                    fi
                else
                    API_HOST=$suggested_ip
                    WS_HOST=$suggested_ip
                fi
            else
                read -p "请输入服务器IP地址: " custom_ip
                if validate_ip "$custom_ip"; then
                    API_HOST=$custom_ip
                    WS_HOST=$custom_ip
                else
                    print_error "无效的IP地址"
                    exit 1
                fi
            fi
            NODE_ENV="development"
            ;;
        3)
            print_info "选择: 生产环境部署"
            SERVER_HOST="0.0.0.0"
            CLIENT_HOST="0.0.0.0"
            read -p "请输入域名或服务器地址: " prod_host
            API_HOST=$prod_host
            WS_HOST=$prod_host
            NODE_ENV="production"
            ;;
        *)
            print_error "无效的选择"
            exit 1
            ;;
    esac
    
    # 端口配置
    echo ""
    print_info "配置端口 (按回车使用默认值):"
    
    read -p "后端服务器端口 [3000]: " input_server_port
    SERVER_PORT=${input_server_port:-3000}
    if ! validate_port "$SERVER_PORT"; then
        print_error "无效的服务器端口: $SERVER_PORT"
        exit 1
    fi
    
    read -p "前端开发服务器端口 [5173]: " input_client_port  
    CLIENT_PORT=${input_client_port:-5173}
    if ! validate_port "$CLIENT_PORT"; then
        print_error "无效的客户端端口: $CLIENT_PORT"
        exit 1
    fi
    
    # 其他配置
    ALLOWED_ORIGINS=""
    DB_PATH="server/data"
    LOG_LEVEL="info"
    
    # 显示配置摘要
    echo ""
    print_header "配置摘要"
    echo -e "${CYAN}部署模式:${NC} $deploy_mode"
    echo -e "${CYAN}API地址:${NC} http://${API_HOST}:${SERVER_PORT}"
    echo -e "${CYAN}WebSocket地址:${NC} ws://${WS_HOST}:${SERVER_PORT}"
    echo -e "${CYAN}前端地址:${NC} http://${API_HOST}:${CLIENT_PORT}"
    echo -e "${CYAN}运行环境:${NC} ${NODE_ENV}"
    echo ""
    
    read -p "确认配置并保存? [Y/n]: " confirm
    if [[ $confirm =~ ^[Nn]$ ]]; then
        print_info "配置已取消"
        exit 0
    fi
    
    # 保存配置
    save_env
    create_client_env
    
    print_success "项目初始化完成！"
    echo ""
}

# 检查环境依赖
check_dependencies() {
    print_info "检查系统依赖..."
    
    # 检查Node.js
    if ! command -v node &> /dev/null; then
        print_error "Node.js 未安装，请先安装 Node.js 16+"
        exit 1
    fi
    
    # 检查npm
    if ! command -v npm &> /dev/null; then
        print_error "npm 未安装，请先安装 npm"
        exit 1
    fi
    
    print_info "Node.js 版本: $(node --version)"
    print_info "npm 版本: $(npm --version)"
}

# 安装项目依赖
install_dependencies() {
    print_info "检查并安装项目依赖..."
    
    # 安装根项目依赖
    if [ ! -d "node_modules" ]; then
        print_info "安装根项目依赖..."
        npm install
    fi
    
    # 安装服务器依赖
    if [ ! -d "server/node_modules" ]; then
        print_info "安装服务器依赖..."
        (cd server && npm install)
    fi
    
    # 安装客户端依赖
    if [ ! -d "client/node_modules" ]; then
        print_info "安装客户端依赖..."
        (cd client && npm install)
    fi
    
    print_success "依赖安装完成"
}

# 构建项目
build_project() {
    print_info "构建服务器代码..."
    cd server
    if npm run build; then
        cd ..
        print_success "构建完成"
    else
        cd ..
        print_error "构建失败"
        return 1
    fi
}

# 启动服务
start_services() {
    print_header "启动 PVE Manager"
    
    # 记录启动日志
    if [[ -f "dev-logger/simple-logger.js" ]]; then
        node dev-logger/simple-logger.js log "application_started" || true
    fi
    
    # 显示访问地址
    print_success "服务启动中..."
    echo ""
    echo -e "${CYAN}前端地址:${NC} http://${API_HOST}:${CLIENT_PORT}"
    echo -e "${CYAN}后端API:${NC} http://${API_HOST}:${SERVER_PORT}"
    echo -e "${CYAN}运行环境:${NC} ${NODE_ENV}"
    echo ""
    print_info "按 Ctrl+C 停止服务"
    echo ""
    
    # 导出环境变量供子进程使用
    export SERVER_HOST SERVER_PORT CLIENT_HOST CLIENT_PORT
    export API_HOST WS_HOST NODE_ENV ALLOWED_ORIGINS
    export DB_PATH LOG_LEVEL
    
    # 启动服务
    npm run dev
}

# 显示帮助信息
show_help() {
    echo "PVE Manager 启动脚本"
    echo ""
    echo "用法:"
    echo "  $0                # 正常启动（如果未配置则进入初始化）"
    echo "  $0 --init         # 重新初始化项目配置"  
    echo "  $0 --reset        # 重置所有配置"
    echo "  $0 --help         # 显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0                # 启动项目"
    echo "  $0 --init         # 重新配置项目参数"
    echo ""
}

# 主函数
main() {
    # 检查是否在项目根目录
    if [[ ! -f "package.json" ]] || [[ ! -d "client" ]] || [[ ! -d "server" ]]; then
        print_error "请在PVE Manager项目根目录下运行此脚本"
        exit 1
    fi
    
    # 处理命令行参数
    case "${1:-}" in
        --help|-h)
            show_help
            exit 0
            ;;
        --init)
            init_project
            exit 0
            ;;
        --reset)
            print_warning "重置所有配置..."
            rm -f .env.global client/.env
            print_success "配置已重置"
            init_project
            exit 0
            ;;
        "")
            # 正常启动流程
            print_header "PVE Manager 启动脚本"
            
            # 检查系统依赖
            check_dependencies
            
            # 加载或初始化配置
            if ! load_env; then
                print_warning "未找到配置文件，开始初始化..."
                echo ""
                init_project
                echo ""
            else
                print_success "已加载配置文件"
            fi
            
            # 安装依赖
            install_dependencies
            echo ""
            
            # 构建项目
            build_project
            echo ""
            
            # 创建前端环境配置（确保最新）
            create_client_env
            echo ""
            
            # 启动服务
            start_services
            ;;
        *)
            print_error "未知参数: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"