# ════════════════════════════════════════════════════════════════
# 光湖 · 铸渊自动巡逻
# Trigger: 每天08:00/20:00 / 手动触发
# 需要: DEEPSEEK_API_KEY 和/或 QIANWEN_API_KEY (Forgejo Secrets)
# ════════════════════════════════════════════════════════════════

name: 铸渊巡逻

on:
  schedule:
    - cron: '0 0 * * *'   # UTC 00:00 = CST 08:00
    - cron: '0 12 * * *'  # UTC 12:00 = CST 20:00
  workflow_dispatch:

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

      - name: 执行巡逻检查
        env:
          DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }}
          QIANWEN_API_KEY: ${{ secrets.QIANWEN_API_KEY }}
          ZY_REPO_TOKEN: ${{ secrets.ZY_REPO_TOKEN }}
        run: |
          cd /data/guanghulab/repo/scripts/patrol-agent
          node patrol-agent.js --once

      - name: 巡逻结果
        run: |
          REPORT_DIR="/data/guanghulab/.runtime/patrol-reports"
          LATEST=$(ls -t "$REPORT_DIR"/patrol-*.json 2>/dev/null | head -1)
          if [[ -n "$LATEST" ]]; then
            echo "═══════════════════════════════════════"
            cat "$LATEST" | python3 -c "
import json,sys
r = json.load(sys.stdin)
print(f'状态: {r.get(\"status\",\"?\")}')
print(f'总结: {r.get(\"summary\",\"?\")}')
for i in r.get('issues',[]):
    icon = '🔴' if i.get('severity')=='high' else '🟡' if i.get('severity')=='medium' else '🟢'
    auto = ' [可自动修复]' if i.get('auto_fix') else ''
    print(f'  {icon} {i.get(\"component\")}: {i.get(\"description\")}{auto}')
for f in r.get('fix_results',[]):
    print(f'  🔧 修复 {f[\"component\"]}: {f[\"result\"]}')
print(f'分析器: {r.get(\"analyzer\",\"未知\")}')
"
            echo "═══════════════════════════════════════"
          else
            echo "⚠️ 未生成巡检报告"
          fi
