name: Claude PR Review

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

jobs:
  review:
    # Only review when all CI checks pass — avoids reviewing code that still
    # has lint/format errors and wastes tokens on already-known problems.
    if: |
      github.event.workflow_run.conclusion == 'success' &&
      github.event.workflow_run.event == 'pull_request'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write

    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event.workflow_run.head_sha }}
          fetch-depth: 1

      - name: Get PR number
        id: pr
        env:
          GH_TOKEN: ${{ github.token }}
          HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
          REPO: ${{ github.repository }}
        run: |
          PR_NUMBER=$(gh api "repos/$REPO/pulls" \
            --jq ".[] | select(.head.sha == \"$HEAD_SHA\") | .number" | head -1)
          if [ -z "$PR_NUMBER" ]; then
            echo "::warning::No open PR found for SHA $HEAD_SHA — skipping review"
          fi
          echo "number=$PR_NUMBER" >> "$GITHUB_OUTPUT"

      - uses: anthropics/claude-code-action@v1
        if: steps.pr.outputs.number != ''
        with:
          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
          settings: |
            {
              "permissions": {
                "allow": [
                  "Bash(gh pr view:*)",
                  "Bash(gh pr diff:*)",
                  "Bash(gh pr list:*)",
                  "Bash(gh api:*)",
                  "WebFetch(*)"
                ]
              }
            }
          prompt: |
            Review Pull Request #${{ steps.pr.outputs.number }} in this repository.

            Respond entirely in English (US). Check the changed files for:
            - Code quality and correctness
            - Logic errors or edge cases
            - Security issues (command injection, path traversal, secret exposure)
            - Rust best practices: no `.unwrap()` in production paths, use `Result<T,E>`, no `unsafe` without justification
            - Project conventions from CONTRIBUTING.md:
              - One concern per crate — no cross-crate circular dependencies
              - Traits must be defined in garudust-core before being implemented elsewhere
              - Type names must use correct suffixes: *Adapter, *Transport, *Store
              - No "what" comments — only "why" comments where the reason is non-obvious
            - Clippy lints to watch for: unnecessary_wraps, single_match_else, redundant_closure

            Use emoji to indicate severity: 🔴 critical, 🟡 warning, 🟢 ok
            Be concise and highlight only significant issues. If no problems are found, reply with LGTM.

      - name: Post review as PR comment
        if: steps.pr.outputs.number != ''
        env:
          GH_TOKEN: ${{ github.token }}
          PR_NUMBER: ${{ steps.pr.outputs.number }}
          GH_REPO: ${{ github.repository }}
        run: |
          python3 - << 'PYEOF'
          import json, subprocess, sys, os

          candidates = [
              '/home/runner/work/_temp/claude-execution-output.json',
          ]
          review_text = None
          for path in candidates:
              if not os.path.exists(path):
                  continue
              with open(path) as f:
                  content = f.read().strip()
              try:
                  data = json.loads(content)
                  items = data if isinstance(data, list) else [data]
                  for item in items:
                      if isinstance(item, dict) and item.get('type') == 'result' and item.get('result'):
                          review_text = item['result']
                          break
              except (json.JSONDecodeError, TypeError):
                  pass
              if not review_text:
                  for line in content.splitlines():
                      try:
                          obj = json.loads(line)
                          if isinstance(obj, dict) and obj.get('type') == 'result' and obj.get('result'):
                              review_text = obj['result']
                              break
                      except (json.JSONDecodeError, TypeError):
                          pass
              if review_text:
                  break

          if not review_text:
              print("No review text found", file=sys.stderr)
              sys.exit(0)

          r = subprocess.run(
              ['gh', 'pr', 'comment', os.environ['PR_NUMBER'],
               '--repo', os.environ['GH_REPO'],
               '--body', review_text],
              capture_output=True, text=True
          )
          if r.returncode != 0:
              print(f"Error: {r.stderr}", file=sys.stderr)
              sys.exit(1)
          print("Review comment posted")
          PYEOF
