name: PR Auto Scan
# 定时扫描所有open PR，对CI全绿的触发审批/合并
# 作为短作业模式的兜底，防止事件驱动遗漏
on:
  schedule:
    - cron: "*/5 * * * *"  # 每5分钟扫描一次
  workflow_dispatch:

permissions:
  contents: read

jobs:
  auto-scan:
    name: Auto Scan Open PRs
    runs-on: ci-check
    timeout-minutes: 5
    if: github.repository == 'xiaoxia/xiaoxia-saas'
    steps:
      - name: Checkout code
        shell: sh
        env:
          GITHUB_TOKEN: ${{ github.token }}
        run: |
          curl -sH "Authorization: token $GITHUB_TOKEN"             "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/pr_auto_scan.py?ref=develop"             -o /tmp/pr_auto_scan.py
          python3 /tmp/pr_auto_scan.py --help > /dev/null 2>&1 || {
            # fallback: checkout
            echo "使用checkout方式"
            curl -sH "Authorization: token $GITHUB_TOKEN"               "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/step_checkout.sh?ref=develop"               | bash
          }

      - name: Scan and auto process PRs
        shell: bash
        env:
          GITHUB_TOKEN: ${{ github.token }}
          REVIEW_TOKEN: ${{ secrets.REVIEW_GITEA_TOKEN }}
          MERGE_TOKEN: ${{ secrets.REVIEW_GITEA_TOKEN }}
        run: |
          set -eu
          echo "=== 扫描所有open PR并自动处理 ==="
          echo "时间: $(date)"
          echo

          python3 /tmp/pr_auto_scan.py             --token "$REVIEW_TOKEN"             --repo "$GITHUB_REPOSITORY"             --base develop             --approve             --merge             --dry-run false

          echo ""
          echo "✅ 扫描完成"

      - name: Report CI trace
        if: always()
        shell: sh
        env:
          AGENTLOOP_LICENSE_KEY: ${{ secrets.AGENTLOOP_LICENSE_KEY }}
        run: |
          STATUS="ok"
          [ ${{ job.status }} = "success" ] || STATUS="error"
          python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "" || true
