# AI 代码审查：每次 PR 触发，用 Claude Code 调用智谱 GLM(glm-5.2) 审查 diff，
# 并把结论评论到 PR。走 GLM 的 Anthropic 兼容端点，无需访问 Anthropic 官方。
# 密钥用 Gitea 的 ${{ secrets.* }}（同仓库 PR 正常下发；来自 fork 的跨仓库 PR 会被
# Gitea 隐藏密钥 → 自动跳过审查，不报错）。请在团队仓库内开同仓库 PR。
name: AI Code Review
on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  review:
    runs-on: ubuntu-latest
    env:
      ANTHROPIC_BASE_URL: https://open.bigmodel.cn/api/anthropic
      ANTHROPIC_API_KEY: ${{ secrets.ZHIPU_API_KEY }}
      ANTHROPIC_MODEL: glm-5.2
      CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
      DISABLE_AUTOUPDATER: "1"
      IS_SANDBOX: "1"   # CI 容器以 root 运行，需此项才能用 --dangerously-skip-permissions
    steps:
      - name: 检出代码
        env:
          REVIEW_PAT: ${{ secrets.REVIEW_PAT }}
        run: |
          if [ -z "$REVIEW_PAT" ]; then
            echo "::warning::REVIEW_PAT 为空：通常是来自 fork 的跨仓库 PR（Gitea 会隐藏密钥）。请在团队仓库内开同仓库 PR。本次跳过审查。"
            echo "SKIP_REVIEW=1" >> "$GITHUB_ENV"
            exit 0
          fi
          git config --global http.extraHeader "Authorization: Basic $(printf 'oauth2:%s' "$REVIEW_PAT" | base64 -w0)"
          git clone "http://gitea:3000/${{ gitea.repository }}.git" .
          git checkout "${{ gitea.event.pull_request.head.ref }}"

      - name: 生成 PR diff
        if: env.SKIP_REVIEW != '1'
        run: |
          BASE="${{ gitea.event.pull_request.base.ref }}"
          git fetch origin "$BASE"
          git diff "origin/$BASE...HEAD" > pr.diff
          echo "diff 行数: $(wc -l < pr.diff)"

      - name: 安装 Claude Code（已装则跳过）
        if: env.SKIP_REVIEW != '1'
        run: |
          if command -v claude >/dev/null 2>&1; then
            echo "claude 已存在，跳过安装"
          else
            npm install -g @anthropic-ai/claude-code --registry=https://registry.npmmirror.com
          fi

      - name: 运行 AI 审查
        if: env.SKIP_REVIEW != '1'
        # Claude Code 会自动读取本仓库 CLAUDE.md 与 .claude/skills/*
        run: |
          claude -p "$(cat .claude/review-prompt.md)" \
                 --model glm-5.2 \
                 --output-format text \
                 --dangerously-skip-permissions \
                 --max-turns 15 > review.md || true

      - name: 把审查结论评论到 PR
        if: env.SKIP_REVIEW != '1'
        env:
          REVIEW_PAT: ${{ secrets.REVIEW_PAT }}
          API: ${{ vars.MAIN_API }}
          REPO: ${{ gitea.repository }}
          PR: ${{ gitea.event.pull_request.number }}
        run: |
          if [ -s review.md ]; then
            node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>process.stdout.write(JSON.stringify({body:d})))' < review.md > /tmp/body.json
            curl -fsS -X POST "$API/repos/$REPO/issues/$PR/comments" \
              -H "Authorization: token $REVIEW_PAT" \
              -H "Content-Type: application/json" \
              --data @/tmp/body.json
          else
            echo "review.md 为空，跳过评论"
          fi
