# ════════════════════════════════════════════════════════════════
# 光湖 · MCP Server 部署
# 部署铸渊 MCP Server 到 CVM，让 WorkBuddy 可以一键连接
# ════════════════════════════════════════════════════════════════
name: 部署 MCP Server

on:
  workflow_dispatch:
    inputs:
      action:
        description: '操作: deploy / restart / status'
        default: 'deploy'

jobs:
  deploy-mcp:
    runs-on: ubuntu
    steps:
      - name: 同步最新代码
        run: |
          cd /data/guanghulab/repo
          git fetch origin
          git reset --hard origin/main
          echo "✅ 代码已同步"

      - name: 安装 MCP Server 依赖
        run: |
          cd /data/guanghulab/repo/server/mcp-server
          if [ -d "node_modules" ]; then
            npm install --production 2>/dev/null || true
          else
            npm install --production
          fi
          echo "✅ 依赖已安装"

      - name: 配置并启动 MCP Server
        env:
          ZY_REPO_TOKEN: ${{ secrets.ZY_REPO_TOKEN }}
        run: |
          ACTION="${{ github.event.inputs.action }}"

          # 注入 Gitea 令牌到 PM2 配置
          cd /data/guanghulab/repo/server/mcp-server
          if [ -n "$ZY_REPO_TOKEN" ]; then
            # 更新 ecosystem.config.js 中的 GITEA_TOKEN
            sed -i "s/GITEA_TOKEN: ''/GITEA_TOKEN: '$ZY_REPO_TOKEN'/" ecosystem.config.js
            echo "✅ Gitea 令牌已注入"
          else
            echo "⚠️ ZY_REPO_TOKEN 未配置"
          fi

          # 创建运行时目录
          mkdir -p /data/guanghulab/mcp-server
          mkdir -p /data/guanghulab/.runtime/logs

          case "$ACTION" in
            deploy)
              # 检查是否已有进程
              if pm2 describe guanghulab-mcp-server &>/dev/null; then
                pm2 restart guanghulab-mcp-server
                echo "✅ MCP Server 已重启"
              else
                pm2 start ecosystem.config.js
                echo "✅ MCP Server 已启动"
              fi
              pm2 save
              ;;
            restart)
              pm2 restart guanghulab-mcp-server
              pm2 save
              echo "✅ MCP Server 已重启"
              ;;
            status)
              pm2 describe guanghulab-mcp-server || echo "MCP Server 未运行"
              ;;
          esac

      - name: 更新 Nginx 配置
        run: |
          # 检查是否已有 /mcp 配置
          if ! grep -q "location /mcp" /etc/nginx/sites-enabled/guanghulab* 2>/dev/null && \
             ! grep -q "location /mcp" /etc/nginx/conf.d/guanghulab* 2>/dev/null; then
            echo "⚠️ Nginx 中尚未配置 /mcp 代理，需要手动添加"
            echo "   参考配置: server/nginx/guanghulab-cvm.conf"
          else
            echo "✅ Nginx /mcp 代理已配置"
          fi

          # 测试并重载 Nginx
          nginx -t 2>/dev/null && nginx -s reload 2>/dev/null && echo "✅ Nginx 已重载" || echo "⚠️ Nginx 重载失败（可能需要手动操作）"

      - name: 验证部署
        run: |
          sleep 2

          echo "═══ MCP Server 部署验证 ═══"

          # 检查进程
          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 "✅ 健康检查通过"
            curl -s http://127.0.0.1:8083/health | python3 -m json.tool 2>/dev/null
          else
            echo "❌ 健康检查失败"
          fi

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

          echo "═══════════════════════════"
