name: PR Automation

on:
  pull_request:
    types: [synchronize, opened, ready_for_review, review_requested]
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: pr-automation-${{ gitea.event.pull_request.number }}
  cancel-in-progress: true

jobs:
  auto-approve:
    name: Auto Approve on CI Green
    runs-on: ci-check
    if: github.event_name == 'pull_request' && !github.event.pull_request.draft
    timeout-minutes: 3  # 长等待模式：等CI全绿后自动合并，不遗漏任何PR
    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/step_checkout.sh?ref=${GITHUB_SHA}"             | bash

      - name: "🔍 脚本语法自检"
        shell: bash
        run: |
          ERROR=0
          for f in scripts/ci/*.sh; do [ -f "$f" ] && bash -n "$f" 2>&1 || ERROR=$((ERROR+1)); done
          for f in scripts/ci/*.py; do [ -f "$f" ] && python3 -m py_compile "$f" 2>&1 || ERROR=$((ERROR+1)); done
          if [ "$ERROR" -ne 0 ]; then echo "❌ 语法自检失败 ($ERROR个)"; exit 1; fi
          echo "✅ 脚本语法自检通过"

      - name: Auto approve when CI passes
        shell: bash
        env:
          GITHUB_TOKEN: ${{ github.token }}
          REVIEW_TOKEN: ${{ secrets.REVIEW_GITEA_TOKEN }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
        run: |
          bash scripts/ci/auto_approve.sh
      - name: Report CI trace
        if: always()
        shell: sh
        env:
          AGENTLOOP_LICENSE_KEY: ${{ secrets.AGENTLOOP_LICENSE_KEY }}
        run: |
          STATUS="ok"
          [ ${{ job.status }} = "success" ] || STATUS="error"
          START_TIME=""
          [ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
          python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true

  auto-merge:
    name: Auto Merge on CI Green + Approved
    runs-on: ci-check
    if: github.event_name == 'pull_request' && !github.event.pull_request.draft && github.event.pull_request.base.ref == 'develop'
    timeout-minutes: 3  # 短作业模式：检查一次，不满足就退出，由pr-auto-scan每5分钟定时兜底
    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/step_checkout.sh?ref=${GITHUB_SHA}"             | bash

      - name: "🔍 脚本语法自检（防止脚本bug导致所有PR挂掉）"
        shell: bash
        run: |
          echo "=== CI脚本语法自检 ==="
          ERROR=0
          for f in scripts/ci/*.sh; do
            [ -f "$f" ] || continue
            if ! bash -n "$f" 2>&1; then
              echo "FAIL: $f"
              ERROR=1
            fi
          done
          for f in scripts/ci/*.py; do
            [ -f "$f" ] || continue
            if ! python3 -m py_compile "$f" 2>&1; then
              echo "FAIL: $f"
              ERROR=1
            fi
          done
          if [ "$ERROR" -ne 0 ]; then
            echo "❌ 脚本语法自检失败"
            exit 1
          fi
          echo "✅ 所有CI脚本语法自检通过"

      - name: Auto merge when CI passes and approved
        shell: bash
        env:
          GITHUB_TOKEN: ${{ github.token }}
          MERGE_TOKEN: ${{ secrets.REVIEW_GITEA_TOKEN }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
          BASE_REF: ${{ github.event.pull_request.base.ref }}
        run: |
          bash scripts/ci/auto_merge.sh
      - name: Report CI trace
        if: always()
        shell: sh
        env:
          AGENTLOOP_LICENSE_KEY: ${{ secrets.AGENTLOOP_LICENSE_KEY }}
        run: |
          STATUS="ok"
          [ ${{ job.status }} = "success" ] || STATUS="error"
          START_TIME=""
          [ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
          python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
