# 光湖 · 安全关机检测
name: 🔒 安全关机检测

on:
  workflow_dispatch:

jobs:
  shutdown-check:
    runs-on: ubuntu
    steps:
      - name: 同步代码
        run: |
          cd /data/guanghulab/repo
          git fetch origin
          git reset --hard origin/main

      - name: 全面安全检查
        env:
          DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
          QIANWEN_API_KEY: ${{ secrets.QIANWEN_API_KEY }}
          ZY_REPO_TOKEN: ${{ secrets.ZY_REPO_TOKEN }}
        run: |
          echo "═══════════════════════════════════════"
          echo "  🔍 安全关机检测"
          echo "  $(date '+%Y-%m-%d %H:%M:%S %Z')"
          echo "═══════════════════════════════════════"
          echo ""

          CAN_SHUTDOWN=true
          WARNINGS=""
          ERRORS=""

          # 1. 检查是否有正在运行的workflow
          echo "── 1. Workflow状态 ──"
          RUNNING=$(curl -s -H "Authorization: token $ZY_REPO_TOKEN" \
            "http://127.0.0.1:3001/api/v1/repos/bingshuo/guanghulab/actions/tasks" \
            | python3 -c "
          import json,sys
          d=json.load(sys.stdin)
          running=[r for r in d.get('workflow_runs',[]) if r.get('status') not in ('success','failure')]
          print(len(running))
          " 2>/dev/null || echo "0")
          if [[ "$RUNNING" -gt 0 ]]; then
            echo "  ❌ 有 ${RUNNING} 个workflow正在运行"
            CAN_SHUTDOWN=false
            ERRORS="$ERRORS workflow运行中"
          else
            echo "  ✅ 无正在运行的workflow"
          fi

          # 2. 检查Git是否有未提交的变更
          echo "── 2. Git状态 ──"
          cd /data/guanghulab/repo
          DIRTY=$(git status --porcelain 2>/dev/null | wc -l)
          if [[ "$DIRTY" -gt 0 ]]; then
            echo "  ⚠️  有 ${DIRTY} 个未提交的文件变更"
            WARNINGS="$WARNINGS git有未提交变更"
          else
            echo "  ✅ Git工作区干净"
          fi

          # 3. 检查关键服务状态
          echo "── 3. 服务状态 ──"
          for svc in forgejo gitea-runner nginx; do
            if systemctl is-active --quiet $svc 2>/dev/null; then
              echo "  ✅ $svc: 运行中"
            else
              echo "  ⚠️  $svc: 未运行"
              WARNINGS="$WARNINGS $svc未运行"
            fi
          done

          # 4. 检查PM2进程
          echo "── 4. PM2进程 ──"
          if command -v pm2 &>/dev/null; then
            PM2_STATUS=$(pm2 jlist 2>/dev/null | python3 -c "
          import json,sys
          procs=json.load(sys.stdin)
          for p in procs:
            status=p.get('pm2_env',{}).get('status','?')
            name=p.get('name','?')
            icon='✅' if status=='online' else '⚠️'
            print(f'  {icon} {name}: {status}')
          " 2>/dev/null || echo "  (PM2无进程)")
            echo "$PM2_STATUS"
          fi

          # 5. 检查内存和磁盘
          echo "── 5. 资源状态 ──"
          MEM_AVAIL=$(free -m | awk '/Mem:/ {print $7}')
          DISK_AVAIL=$(df -h /data | awk 'NR==2 {print $4}')
          echo "  内存可用: ${MEM_AVAIL}MB"
          echo "  磁盘可用: ${DISK_AVAIL}"

          # 6. 检查是否有未处理的工单
          echo "── 6. 待处理工单 ──"
          TICKET_DIR="/data/guanghulab/.runtime/tickets"
          if [[ -d "$TICKET_DIR" ]]; then
            OPEN=$(ls "$TICKET_DIR"/ticket-*.json 2>/dev/null | wc -l)
            if [[ "$OPEN" -gt 0 ]]; then
              echo "  ⚠️  有 ${OPEN} 个未处理工单"
              WARNINGS="$WARNINGS ${OPEN}个未处理工单"
            else
              echo "  ✅ 无待处理工单"
            fi
          else
            echo "  ✅ 无工单目录"
          fi

          # 7. 检查Vault
          echo "── 7. Vault状态 ──"
          if curl -sf http://127.0.0.1:8080/admin/__healthz > /dev/null 2>&1; then
            echo "  ✅ Vault: 运行中"
          else
            echo "  ⚠️  Vault: 未运行（关机无影响）"
          fi

          # ─── 结论 ───
          echo ""
          echo "═══════════════════════════════════════"
          if $CAN_SHUTDOWN; then
            if [[ -n "$WARNINGS" ]]; then
              echo "  🟡 可以关机（有警告）"
              echo "  警告:$WARNINGS"
              echo ""
              echo "  建议：检查警告项后再关机"
            else
              echo "  🟢 可以安全关机 ✅"
              echo "  所有检查通过，关机不会丢失数据"
            fi
          else
            echo "  🔴 不建议关机 ❌"
            echo "  问题:$ERRORS"
            echo ""
            echo "  请等workflow完成后再关机"
          fi
          echo ""
          echo "  关机后："
          echo "  · 计算费用停止（只收云盘费）"
          echo "  · 数据盘100GB数据完整保留"
          echo "  · 下次开机所有服务自动启动"
          echo "═══════════════════════════════════════"
