name: Claude Assistant
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned, labeled]
  pull_request_review:
    types: [submitted]

jobs:
  handle-issue:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code
      - name: Create branch
        run: |
          git config user.name "Claude Agent"
          git config user.email "claude@agent.local"
          git checkout -b fix/issue-${{ github.event.issue.number }}          

      - name: Claude works on issue
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          useradd -m claude-runner
          chown -R claude-runner:claude-runner /workspace
          claude --output-format stream-json --print --verbose "
            Work on issue #${{ github.event.issue.number }}: ${{ github.event.issue.title }}

            Beschreibung:
            ${{ github.event.issue.body }}

            Vorgehensweise:
            1. Analyze the code and understand the issue
            2. Create a detailed plan
            3. Implement the solution
            4. Check if all tests still pass, update them or create new tests if there are failing or missing tests.
          "
                    
      - name: Commit changes
        run: |
          git add .
          git commit -m "${{ github.event.issue.title }}"          

      - name: Push branch
        run: |
          git push origin fix/issue-${{ github.event.issue.number }}          

      - name: Create PR
        run: |
          curl -X POST "${{ secrets.INSTANCE_URL }}/api/v1/repos/${{ github.repository }}/pulls" \
            -H "Authorization: token ${{ secrets.API_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d "{
              \"title\": \"Fix #${{ github.event.issue.number }}: ${{ github.event.issue.title }}\",
              \"head\": \"fix/issue-${{ github.event.issue.number }}\",
              \"base\": \"main\",
              \"body\": \"Automatically resolved by Claude.\n\nCloses #${{ github.event.issue.number }}\"
            }"          