name: Handle PR Review Feedback

# This workflow allows Claude to respond to PR review feedback on PRs it created.
# When a review is submitted on a claude-code labeled PR, Claude will attempt
# to address the feedback and push fixes.

on:
  pull_request_review:
    types: [submitted]

jobs:
  handle-review:
    name: Handle PR Review with Claude
    # Only run on PRs with the claude-code label and when review requests changes or comments
    if: |
      contains(github.event.pull_request.labels.*.name, 'claude-code') &&
      (github.event.review.state == 'changes_requested' || github.event.review.state == 'commented')
    runs-on: ubuntu-latest

    permissions:
      contents: write
      pull-requests: write

    steps:
    - name: Check for API key
      id: check-key
      run: |
        if [[ -z "${{ secrets.ANTHROPIC_API_KEY }}" ]]; then
          echo "ANTHROPIC_API_KEY secret is not configured, skipping Claude review handler"
          echo "skip=true" >> $GITHUB_OUTPUT
        else
          echo "skip=false" >> $GITHUB_OUTPUT
        fi

    - name: Checkout PR branch
      if: steps.check-key.outputs.skip != 'true'
      uses: actions/checkout@v4
      with:
        ref: ${{ github.event.pull_request.head.ref }}
        fetch-depth: 0

    - name: Configure Git
      if: steps.check-key.outputs.skip != 'true'
      run: |
        git config user.name "timescale-automation"
        git config user.email "123763385+github-actions[bot]@users.noreply.github.com"

    - name: Setup Node.js
      if: steps.check-key.outputs.skip != 'true'
      uses: actions/setup-node@v4
      with:
        node-version: "20"

    - name: Install Claude Code
      if: steps.check-key.outputs.skip != 'true'
      run: npm install -g @anthropic-ai/claude-code

    - name: Handle review feedback
      if: steps.check-key.outputs.skip != 'true'
      env:
        ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        PR_NUMBER: ${{ github.event.pull_request.number }}
        PR_BRANCH: ${{ github.event.pull_request.head.ref }}
        REVIEW_ID: ${{ github.event.review.id }}
        REVIEW_BODY: ${{ github.event.review.body }}
        REVIEW_STATE: ${{ github.event.review.state }}
        REVIEWER: ${{ github.event.review.user.login }}
        # PR_REPOSITORY is where the PR lives (for API calls)
        PR_REPOSITORY: ${{ github.repository }}
        # PUSH_REPOSITORY is where to push (may be a fork)
        PUSH_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
      run: .github/scripts/claude-handle-pr-review.sh

    - name: Upload Claude review handler output
      if: always() && steps.check-key.outputs.skip != 'true'
      uses: actions/upload-artifact@v4
      with:
        name: Claude review handler output PR-${{ github.event.pull_request.number }}
        path: /tmp/claude-review-*/
        if-no-files-found: ignore
        retention-days: 7
