#!/usr/bin/env bash
# ════════════════════════════════════════════════════════════════
# 光湖 · MCP Server 一键部署脚本
# 在 CVM 服务器上直接运行此脚本完成部署
# ════════════════════════════════════════════════════════════════
#
# 用法: bash deploy-mcp.sh
#
# 此脚本完成以下操作：
#   1. 拉取最新代码
#   2. 安装 MCP Server 依赖
#   3. 注入 Gitea 令牌
#   4. 启动 MCP Server (PM2)
#   5. 更新 Nginx 配置
#   6. 验证部署
#
# 签发: 铸渊 · ICE-GL-ZY001 · TCS-0002∞
# ════════════════════════════════════════════════════════════════

set -e

REPO_DIR="/data/guanghulab/repo"
MCP_DIR="$REPO_DIR/server/mcp-server"
NGINX_CONF_SRC="$REPO_DIR/server/nginx/guanghulab-cvm.conf"

echo "═══════════════════════════════════════"
echo "  铸渊 MCP Server 一键部署"
echo "  $(date '+%Y-%m-%d %H:%M:%S')"
echo "═══════════════════════════════════════"

# 1. 拉取最新代码
echo ""
echo "── 1. 拉取最新代码 ──"
cd "$REPO_DIR"
git fetch origin
git reset --hard origin/main
echo "✅ 代码已同步: $(git log --oneline -1)"

# 2. 安装依赖
echo ""
echo "── 2. 安装依赖 ──"
cd "$MCP_DIR"
npm install --production
echo "✅ 依赖已安装"

# 3. 注入 Gitea 令牌
echo ""
echo "── 3. 注入 Gitea 令牌 ──"
# 从 Vault 获取（如果 Vault 在运行）
TOKEN=""
if curl -sf http://127.0.0.1:8080/internal/fetch/ZY_REPO_TOKEN > /dev/null 2>&1; then
    TOKEN=$(curl -s http://127.0.0.1:8080/internal/fetch/ZY_REPO_TOKEN | python3 -c "import json,sys;print(json.load(sys.stdin).get('value',''))" 2>/dev/null || "")
fi

if [ -z "$TOKEN" ]; then
    echo "⚠️  无法从 Vault 获取令牌"
    echo "   请手动输入 Gitea 令牌（或按回车跳过，稍后手动配置）:"
    read -r TOKEN
fi

if [ -n "$TOKEN" ]; then
    sed -i "s/GITEA_TOKEN: ''/GITEA_TOKEN: '$TOKEN'/" "$MCP_DIR/ecosystem.config.js"
    echo "✅ Gitea 令牌已注入"
else
    echo "⚠️  跳过令牌注入 — 请手动编辑 $MCP_DIR/ecosystem.config.js"
fi

# 4. 启动 MCP Server
echo ""
echo "── 4. 启动 MCP Server ──"
mkdir -p /data/guanghulab/mcp-server /data/guanghulab/.runtime/logs

if pm2 describe guanghulab-mcp-server &>/dev/null; then
    pm2 restart guanghulab-mcp-server
    echo "✅ MCP Server 已重启"
else
    cd "$MCP_DIR"
    pm2 start ecosystem.config.js
    echo "✅ MCP Server 已启动"
fi
pm2 save

# 5. 更新 Nginx 配置
echo ""
echo "── 5. 更新 Nginx 配置 ──"

# 找到当前使用的 Nginx 配置文件
NGINX_CONF=""
for f in /etc/nginx/sites-enabled/guanghulab* /etc/nginx/conf.d/guanghulab*; do
    if [ -f "$f" ]; then
        NGINX_CONF="$f"
        break
    fi
done

if [ -z "$NGINX_CONF" ]; then
    echo "⚠️  未找到现有 Nginx 配置文件"
    echo "   请手动将 $NGINX_CONF_SRC 中的 /mcp location 添加到 Nginx 配置中"
else
    # 检查是否已有 /mcp 配置
    if grep -q "location /mcp" "$NGINX_CONF"; then
        echo "✅ Nginx /mcp 代理已存在"
    else
        echo "   添加 /mcp 代理到 $NGINX_CONF ..."
        # 在 server 块末尾的 } 之前插入
        sed -i '/^[[:space:]]*}$/i\
\
    # ─── 铸渊 MCP Server (/mcp) ───\
    location /mcp {\
        proxy_pass http://127.0.0.1:8083;\
        proxy_http_version 1.1;\
        proxy_set_header Host $host;\
        proxy_set_header X-Real-IP $remote_addr;\
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\
        proxy_set_header X-Forwarded-Proto $scheme;\
        proxy_set_header Connection '"'"''"'"';\
        proxy_buffering off;\
        proxy_cache off;\
        proxy_read_timeout 86400s;\
        proxy_send_timeout 86400s;\
    }\
\
    location = /mcp-health {\
        proxy_pass http://127.0.0.1:8083/health;\
        access_log off;\
    }' "$NGINX_CONF"
        echo "✅ /mcp 代理已添加"
    fi

    # 测试并重载
    if nginx -t 2>/dev/null; then
        nginx -s reload
        echo "✅ Nginx 已重载"
    else
        echo "❌ Nginx 配置测试失败，请手动检查"
        nginx -t
    fi
fi

# 6. 验证
echo ""
echo "── 6. 验证部署 ──"
sleep 2

# PM2 状态
if pm2 describe guanghulab-mcp-server &>/dev/null; then
    STATUS=$(pm2 jlist | python3 -c "
import json,sys
procs=json.load(sys.stdin)
for p in procs:
    if p.get('name')=='guanghulab-mcp-server':
        print(p.get('pm2_env',{}).get('status','?'))
" 2>/dev/null || echo "unknown")
    echo "PM2: $STATUS"
else
    echo "❌ PM2 中未找到 guanghulab-mcp-server"
fi

# 健康检查
if curl -sf http://127.0.0.1:8083/health > /dev/null 2>&1; then
    echo "✅ MCP Server 健康检查通过"
else
    echo "❌ MCP Server 健康检查失败"
fi

# 显示访问密钥
if [ -f "/data/guanghulab/mcp-server/.access-key" ]; then
    KEY=$(cat /data/guanghulab/mcp-server/.access-key)
    echo ""
    echo "═══════════════════════════════════════"
    echo "  🔑 MCP 连接信息"
    echo "═══════════════════════════════════════"
    echo ""
    echo "  URL: https://guanghulab.com/mcp"
    echo "  密钥: $KEY"
    echo ""
    echo "  WorkBuddy 配置:"
    echo '  {'
    echo '    "mcpServers": {'
    echo '      "guanghulab": {'
    echo '        "url": "https://guanghulab.com/mcp",'
    echo "        \"headers\": { \"Authorization\": \"Bearer $KEY\" }"
    echo '      }'
    echo '    }'
    echo '  }'
    echo ""
    echo "═══════════════════════════════════════"
fi

echo ""
echo "铸渊 MCP Server 部署完成 ✅"
echo "ICE-GL-ZY001 · TCS-0002∞"
