#!/bin/bash

# 本地部署脚本 - 不使用Docker

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

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

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

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

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查Node.js
check_nodejs() {
    log_step "检查Node.js环境..."
    
    if command -v node &> /dev/null; then
        local version=$(node --version)
        log_info "Node.js版本: $version"
        
        local major=$(echo $version | cut -d'.' -f1 | sed 's/v//')
        if [ "$major" -ge 16 ]; then
            log_info "✓ Node.js版本符合要求"
            return 0
        else
            log_warn "Node.js版本过低，需要16+版本"
        fi
    else
        log_warn "未找到Node.js"
    fi
    
    return 1
}

# 安装Node.js
install_nodejs() {
    log_step "安装Node.js..."
    
    if command -v apt-get &> /dev/null; then
        # Ubuntu/Debian
        sudo apt-get update
        sudo apt-get install -y curl
        curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
        sudo apt-get install -y nodejs
    elif command -v yum &> /dev/null; then
        # CentOS/RHEL
        sudo yum install -y curl
        curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
        sudo yum install -y nodejs
    else
        log_error "不支持的系统，请手动安装Node.js 18+"
        exit 1
    fi
    
    log_info "✓ Node.js安装完成"
}

# 检查Redis
check_redis() {
    log_step "检查Redis..."
    
    if command -v redis-server &> /dev/null; then
        log_info "✓ Redis已安装"
        
        if systemctl is-active --quiet redis-server || systemctl is-active --quiet redis; then
            log_info "✓ Redis服务正在运行"
        else
            log_info "启动Redis服务..."
            sudo systemctl start redis-server || sudo systemctl start redis
        fi
        return 0
    fi
    
    return 1
}

# 安装Redis
install_redis() {
    log_step "安装Redis..."
    
    if command -v apt-get &> /dev/null; then
        sudo apt-get update
        sudo apt-get install -y redis-server
        sudo systemctl enable redis-server
        sudo systemctl start redis-server
    elif command -v yum &> /dev/null; then
        sudo yum install -y redis
        sudo systemctl enable redis
        sudo systemctl start redis
    else
        log_error "不支持的系统，请手动安装Redis"
        exit 1
    fi
    
    log_info "✓ Redis安装完成"
}

# 安装应用依赖
install_dependencies() {
    log_step "安装应用依赖..."
    
    # 设置npm镜像源
    npm config set registry https://registry.npmmirror.com
    
    # 安装依赖
    npm install --production
    
    log_info "✓ 依赖安装完成"
}

# 创建环境配置
create_env() {
    log_step "创建环境配置..."
    
    # 确保.env文件存在
    if [ ! -f .env ]; then
        cp .env.example .env
    fi
    
    # 创建日志目录
    mkdir -p logs
    
    log_info "✓ 环境配置完成"
}

# 创建systemd服务
create_service() {
    log_step "创建系统服务..."
    
    local current_dir=$(pwd)
    local node_path=$(which node)
    
    sudo tee /etc/systemd/system/geoapify-mcp.service > /dev/null << EOF
[Unit]
Description=Geoapify MCP Server
After=network.target redis.service

[Service]
Type=simple
User=root
WorkingDirectory=$current_dir
Environment=NODE_ENV=production
Environment=GEOAPIFY_API_KEY=3234bd7e35264a8aa29fc15e89f8f76f
Environment=PORT=50001
Environment=LOG_LEVEL=info
Environment=REDIS_HOST=localhost
Environment=REDIS_PORT=6379
ExecStart=$node_path src/server.js
Restart=always
RestartSec=10
StandardOutput=append:$current_dir/logs/service.log
StandardError=append:$current_dir/logs/service.log

[Install]
WantedBy=multi-user.target
EOF
    
    sudo systemctl daemon-reload
    sudo systemctl enable geoapify-mcp
    
    log_info "✓ 系统服务创建完成"
}

# 启动服务
start_service() {
    log_step "启动服务..."
    
    sudo systemctl start geoapify-mcp
    
    log_info "✓ 服务启动完成"
}

# 等待服务就绪
wait_for_service() {
    log_step "等待服务就绪..."
    
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if curl -f http://localhost:50001/health &> /dev/null; then
            log_info "✓ 服务就绪"
            return 0
        fi
        
        if [ $((attempt % 5)) -eq 0 ]; then
            log_warn "等待服务启动... ($attempt/$max_attempts)"
            # 显示服务状态
            sudo systemctl status geoapify-mcp --no-pager -l | tail -5
        fi
        
        sleep 2
        ((attempt++))
    done
    
    log_error "服务启动超时"
    return 1
}

# 运行测试
test_service() {
    log_step "测试服务..."
    
    # 健康检查
    echo "健康检查:"
    curl -s http://localhost:50001/health | jq . || curl -s http://localhost:50001/health
    echo ""
    
    # 工具列表
    echo "工具列表:"
    curl -s http://localhost:50001/tools | jq '.tools[].name' || curl -s http://localhost:50001/tools
    echo ""
    
    # API测试
    echo "API测试:"
    curl -s -X POST http://localhost:50001/tools/geocode_address \
        -H "Content-Type: application/json" \
        -d '{
            "arguments": {
                "address": "北京市天安门广场",
                "language": "zh"
            }
        }' | jq . || echo "API测试完成"
    
    log_info "✓ 测试完成"
}

# 显示状态
show_status() {
    log_step "服务状态"
    
    echo ""
    echo "=== 系统服务状态 ==="
    sudo systemctl status geoapify-mcp --no-pager -l
    
    echo ""
    echo "=== Redis状态 ==="
    sudo systemctl status redis-server --no-pager -l || sudo systemctl status redis --no-pager -l
    
    echo ""
    echo "=== 端口监听 ==="
    netstat -tlnp | grep -E ":50001|:6379" || ss -tlnp | grep -E ":50001|:6379"
    
    echo ""
    echo "=== 服务访问 ==="
    echo "  主服务: http://localhost:50001"
    echo "  健康检查: http://localhost:50001/health"
    echo "  工具列表: http://localhost:50001/tools"
    
    echo ""
    echo "=== 管理命令 ==="
    echo "  查看日志: sudo journalctl -u geoapify-mcp -f"
    echo "  重启服务: sudo systemctl restart geoapify-mcp"
    echo "  停止服务: sudo systemctl stop geoapify-mcp"
    echo "  查看应用日志: tail -f logs/combined.log"
}

# 主函数
main() {
    log_info "🚀 本地部署 Geoapify MCP Server"
    echo ""
    
    # 检查并安装Node.js
    if ! check_nodejs; then
        install_nodejs
    fi
    
    # 检查并安装Redis
    if ! check_redis; then
        install_redis
    fi
    
    # 安装应用
    install_dependencies
    create_env
    create_service
    start_service
    
    if wait_for_service; then
        show_status
        echo ""
        test_service
        echo ""
        log_info "🎉 本地部署成功完成！"
    else
        log_error "部署失败，请查看日志"
        sudo journalctl -u geoapify-mcp --no-pager -l
        exit 1
    fi
}

# 停止服务
stop_service() {
    log_step "停止服务..."
    sudo systemctl stop geoapify-mcp
    log_info "✓ 服务已停止"
}

# 重启服务
restart_service() {
    log_step "重启服务..."
    sudo systemctl restart geoapify-mcp
    if wait_for_service; then
        log_info "✓ 服务重启成功"
    else
        log_error "服务重启失败"
        exit 1
    fi
}

# 清理安装
cleanup() {
    log_step "清理安装..."
    
    sudo systemctl stop geoapify-mcp || true
    sudo systemctl disable geoapify-mcp || true
    sudo rm -f /etc/systemd/system/geoapify-mcp.service
    sudo systemctl daemon-reload
    
    log_info "✓ 清理完成"
}

# 处理命令行参数
case "${1:-deploy}" in
    "deploy")
        main
        ;;
    "start")
        start_service
        wait_for_service && show_status
        ;;
    "stop")
        stop_service
        ;;
    "restart")
        restart_service
        ;;
    "test")
        test_service
        ;;
    "status")
        show_status
        ;;
    "cleanup")
        cleanup
        ;;
    "help")
        echo "用法: $0 [命令]"
        echo ""
        echo "命令："
        echo "  deploy  - 完整部署（默认）"
        echo "  start   - 启动服务"
        echo "  stop    - 停止服务"
        echo "  restart - 重启服务"
        echo "  test    - 测试服务"
        echo "  status  - 显示状态"
        echo "  cleanup - 清理安装"
        echo "  help    - 显示帮助"
        ;;
    *)
        log_error "未知命令: $1"
        echo "使用 '$0 help' 查看可用命令"
        exit 1
        ;;
esac
