# ════════════════════════════════════════════════════
# 光湖 · CI检查 + 合并后自动部署
# ────────────────────────────────────────────────────
# main分支: 冰朔合并PR后 → 自动部署到服务器
# dev分支:  铸渊自己push → 只跑检查不部署
# PR到main: 跑检查 → 冰朔看绿✅红❌再决定合不合
# ════════════════════════════════════════════════════
name: 🚀 构建与部署

on:
  pull_request:
    branches: [main]
  push:
    branches: [main, dev]

jobs:
  # ── 所有情况都跑：基础检查 ──────────────────────
  check:
    runs-on: ubuntu
    steps:
      - name: 服务健康检查
        run: |
          echo "═══ 服务健康检查 ═══"
          FAIL=0

          if systemctl is-active --quiet nginx; then
            echo "✅ Nginx 正常"
          else
            echo "❌ Nginx 宕机"
            FAIL=1
          fi

          if curl -sf http://127.0.0.1:3001/ > /dev/null 2>&1; then
            echo "✅ Forgejo 代码仓库 正常"
          else
            echo "❌ Forgejo 代码仓库 未响应"
            FAIL=1
          fi

          if systemctl is-active --quiet gitea-runner; then
            echo "✅ Runner 运行器 正常"
          else
            echo "⚠️  Runner 运行器 未运行"
          fi

          if [ $FAIL -eq 1 ]; then
            echo "❌ 关键服务异常，请通知铸渊检查"
            exit 1
          fi

          echo "═══ 检查通过 ✅ ═══"

      - name: 代码检查
        run: |
          cd /data/guanghulab/repo
          echo "仓库大小: $(du -sh .git | cut -f1)"
          echo "最新提交: $(git log --oneline -1)"
          echo "✅ 代码检查完成"

  # ── 只有合并到main才跑：自动部署 ────────────────
  deploy:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    needs: check
    runs-on: ubuntu
    steps:
      - name: 同步最新代码
        run: |
          cd /data/guanghulab/repo
          git fetch origin
          git reset --hard origin/main
          echo "✅ 代码已同步到最新"

      - name: 安装依赖
        run: |
          echo "═══ 安装依赖 ═══"
          # 逐个检查并安装
          for pkg_dir in server/git-sync server/wake-gate server/secrets-vault server/mcp-server; do
            if [ -f "/data/guanghulab/repo/$pkg_dir/package.json" ]; then
              cd "/data/guanghulab/repo/$pkg_dir"
              npm install --production 2>/dev/null || true
              echo "✅ $pkg_dir 依赖已安装"
            fi
          done

      - name: 部署 MCP Server
        env:
          ZY_REPO_TOKEN: ${{ secrets.ZY_REPO_TOKEN }}
        run: |
          echo "═══ 部署 MCP Server ═══"
          MCP_DIR="/data/guanghulab/repo/server/mcp-server"
          mkdir -p /data/guanghulab/mcp-server /data/guanghulab/.runtime/logs

          # 注入 Gitea 令牌
          if [ -n "$ZY_REPO_TOKEN" ]; then
            sed -i "s/GITEA_TOKEN: ''/GITEA_TOKEN: '$ZY_REPO_TOKEN'/" "$MCP_DIR/ecosystem.config.js"
            echo "✅ Gitea 令牌已注入"
          fi

          # 启动或重启 MCP Server
          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

      - name: 重启服务
        run: |
          echo "═══ 重启服务 ═══"
          if command -v pm2 &>/dev/null; then
            pm2 restart all 2>/dev/null || true
            echo "✅ PM2 服务已重启"
          fi
          echo "═══ 重启完成 ═══"

      - name: 部署验证
        run: |
          sleep 3
          echo "═══ 部署验证 ═══"
          FAIL=0

          if curl -sf http://127.0.0.1:3001/ > /dev/null 2>&1; then
            echo "✅ 代码仓库 正常"
          else
            echo "❌ 代码仓库 异常"
            FAIL=1
          fi

          if curl -sf http://127.0.0.1:8081/api/health > /dev/null 2>&1; then
            echo "✅ 唤醒门 正常"
          else
            echo "⚠️  唤醒门 未响应"
          fi

          if curl -sf http://127.0.0.1:8082/health > /dev/null 2>&1; then
            echo "✅ 代码同步服务 正常"
          else
            echo "⚠️  代码同步服务 未响应"
          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 [ $FAIL -eq 1 ]; then
            echo "❌ 部署后关键服务异常"
            exit 1
          fi

          echo "═══ 部署完成 ✅ $(date '+%Y-%m-%d %H:%M:%S') ═══"
