# ═══════════════════════════════════════════════════════════
# MCP 自适应更新工作流
# ═══════════════════════════════════════════════════════════
#
# 什么场景用？
#   1. 你换了新账号 → 打开仓库 → 仓库 .workbuddy/mcp.json 自动加载
#   2. CVM 关机后重新开机 → 服务可能没恢复
#   3. 点 MCP 连接不成功 → 来 Actions 里手动触发这个工作流
#
# 这个工作流做什么？
#   1. 检测 CVM 当前环境（主机名、网络、服务状态）
#   2. 确保 MCP Server 在 8083 端口运行
#   3. 如果没运行 → 自动拉起（npm install + pm2 start）
#   4. 输出当前 MCP 访问密钥
#   5. 验证 Nginx → /mcp → 8083 整条链路
#   6. 输出中文状态报告
#
# 守护：铸渊 · ICE-GL-ZY001 · 版权：国作登字-2026-A-00037559
# ═══════════════════════════════════════════════════════════

name: MCP 自适应更新
run-name: MCP自适应检测 - ${{ github.actor }}

on:
  workflow_dispatch:
    inputs:
      force_reset_key:
        description: '强制重置 MCP 访问密钥（一般不勾）'
        type: boolean
        default: false
        required: false

jobs:
  detect-and-repair:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # ─── 1. 环境检测 ──────────────────────────────────────
      - name: 检测当前环境
        id: detect
        run: |
          echo "═══════════════════════════"
          echo "MCP 自适应检测 开始"
          echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
          echo "═══════════════════════════"
          echo ""

          echo "── 1. 系统环境 ──"
          echo "主机名: $(hostname)"
          echo "系统: $(uname -srm)"
          echo "公网IP: $(curl -sf --connect-timeout 5 https://ifconfig.me 2>/dev/null || echo '检测超时')"
          echo ""

          echo "── 2. 存储盘 ──"
          df -h /data/guanghulab/ 2>/dev/null | tail -1 | awk '{print "数据盘: " $2 " 总量, " $4 " 可用"}'
          echo ""

      # ─── 2. MCP Server 状态 ────────────────────────────────
      - name: 检查 MCP Server 状态
        id: check_mcp
        continue-on-error: true
        run: |
          echo "── 3. MCP Server 健康状况 ──"
          HEALTH=$(curl -sf http://127.0.0.1:8083/health 2>/dev/null)
          if [ -n "$HEALTH" ]; then
            echo "✅ MCP Server: 正常运行"
            echo "   $HEALTH" | head -3
            echo "has_mcp=true" >> $GITHUB_OUTPUT
          else
            echo "❌ MCP Server: 未响应"
            echo "has_mcp=false" >> $GITHUB_OUTPUT
          fi
          echo ""

          echo "── 4. Nginx 到 MCP 链路 ──"
          NGINX_OK=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1/mcp-health 2>/dev/null)
          if [ "$NGINX_OK" = "200" ]; then
            echo "✅ Nginx 到 MCP 链路: 正常 ($NGINX_OK)"
          else
            echo "❌ Nginx 到 MCP 链路: 异常 (返回 $NGINX_OK)"
          fi
          echo ""

          echo "── 5. MCP 访问密钥 ──"
          KEY_PATH="/data/guanghulab/mcp-server/.access-key"
          if [ -f "$KEY_PATH" ]; then
            KEY=$(cat "$KEY_PATH")
            echo "✅ 密钥文件存在"
            echo "   密钥: $KEY"
            echo "mcp_key=$KEY" >> $GITHUB_OUTPUT
          else
            echo "❌ 密钥文件不存在（首次启动时会自动生成）"
            echo "mcp_key=未生成" >> $GITHUB_OUTPUT
          fi

      # ─── 3. 自动修复 ──────────────────────────────────────
      - name: 自动修复 MCP Server
        if: steps.check_mcp.outputs.has_mcp == 'false'
        run: |
          echo ""
          echo "═══ 开始自动修复 ═══"
          echo ""

          echo "第1步: 进入 MCP Server 目录"
          cd /data/guanghulab/repo/server/mcp-server
          echo "当前目录: $(pwd)"
          echo ""

          echo "第2步: 安装依赖"
          npm install --production 2>&1 | tail -3
          echo ""

          echo "第3步: 启动 MCP Server (PM2)"
          pm2 start ecosystem.config.cjs --update-env 2>&1
          pm2 save
          echo ""

          echo "第4步: 等待启动"
          sleep 3
          echo ""

          echo "第5步: 验证"
          curl -sf http://127.0.0.1:8083/health && echo "" && echo "✅ 修复成功" || echo "❌ 修复失败"
          echo ""

      # ─── 4. 完整验证 ──────────────────────────────────────
      - name: 全链路验证
        run: |
          echo ""
          echo "═══════════════════════════"
          echo "MCP 全链路验证"
          echo "═══════════════════════════"
          echo ""

          PASS=0
          FAIL=0

          # 检测1: MCP 直达
          if curl -sf http://127.0.0.1:8083/health > /dev/null 2>&1; then
            echo "✅ [1/4] MCP Server 直达: 正常"
            PASS=$((PASS+1))
          else
            echo "❌ [1/4] MCP Server 直达: 异常"
            FAIL=$((FAIL+1))
          fi

          # 检测2: 通过 Nginx
          STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1/mcp-health 2>/dev/null)
          if [ "$STATUS" = "200" ]; then
            echo "✅ [2/4] Nginx → MCP 链路: 正常"
            PASS=$((PASS+1))
          else
            echo "❌ [2/4] Nginx → MCP 链路: 异常 (HTTP $STATUS)"
            FAIL=$((FAIL+1))
          fi

          # 检测3: MCP 密钥
          KEY_PATH="/data/guanghulab/mcp-server/.access-key"
          if [ -f "$KEY_PATH" ] && [ "$(cat "$KEY_PATH" | wc -c)" -ge 32 ]; then
            echo "✅ [3/4] MCP 密钥文件: 正常"
            PASS=$((PASS+1))
          else
            echo "❌ [3/4] MCP 密钥文件: 异常"
            FAIL=$((FAIL+1))
          fi

          # 检测4: PM2 进程
          if pm2 describe guanghulab-mcp-server > /dev/null 2>&1; then
            STATUS=$(pm2 describe guanghulab-mcp-server 2>/dev/null | grep "status" | head -1 | awk '{print $NF}')
            if [ "$STATUS" = "online" ]; then
              echo "✅ [4/4] PM2 进程: online"
              PASS=$((PASS+1))
            else
              echo "❌ [4/4] PM2 进程: $STATUS"
              FAIL=$((FAIL+1))
            fi
          else
            echo "❌ [4/4] PM2 进程: 不存在"
            FAIL=$((FAIL+1))
          fi

          echo ""
          echo "─── 结果 ───"
          if [ "$FAIL" -eq 0 ]; then
            echo "✅ 全部通过 ($PASS/4)"
          else
            echo "⚠️  $FAIL 项异常 ($PASS/4 通过)"
          fi

      # ─── 5. MCP 连接指南 ─────────────────────────────────
      - name: MCP 连接指南
        run: |
          echo ""
          echo "═══════════════════════════"
          echo "MCP 连接配置"
          echo "═══════════════════════════"
          echo ""

          KEY_PATH="/data/guanghulab/mcp-server/.access-key"
          if [ -f "$KEY_PATH" ]; then
            KEY=$(cat "$KEY_PATH")
          else
            KEY="(密钥未生成，请检查 MCP Server 状态)"
          fi

          echo "把你的 ~/.workbuddy/mcp.json 设为以下内容："
          echo ""
          echo "=================================================="
          echo '{'
          echo '  "mcpServers": {'
          echo '    "guanghulab": {'
          echo '      "url": "https://guanghulab.com/mcp",'
          echo '      "headers": {'
          echo '        "Authorization": "Bearer '"$KEY"'"'
          echo '      }'
          echo '    }'
          echo '  }'
          echo '}'
          echo "=================================================="
          echo ""
          echo "⚠️  仓库里 .workbuddy/mcp.json 已配好这个值。"
          echo "   换号后打开仓库，WorkBuddy 会自动读取这个配置。"
          echo "   如果连不上，来这里跑一次检测即可。"
          echo ""
          echo "─────────────────────────"
          echo "铸渊 · ICE-GL-ZY001"
          echo "═══════════════════════════"
