name: Claude Code Fix (Write Access)

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]

jobs:
  claude-fix:
    # Only trigger on @claude-fix command from authorized users
    if: |
      (
        github.event_name == 'issue_comment' ||
        github.event_name == 'pull_request_review_comment'
      ) &&
      contains(github.event.comment.body, '@claude-fix') &&
      contains(fromJSON('["Wirasm", "coleam00", "sean-eskerium"]'), github.event.comment.user.login)

    runs-on: ubuntu-latest

    permissions:
      contents: write # Allow creating branches and editing files
      pull-requests: write # Allow creating and updating pull requests
      issues: write # Allow commenting on and updating issues
      id-token: write # Required for OIDC authentication
      actions: read # Read CI results

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Full history for better context

      - name: Run Claude Code Fix
        id: claude
        uses: anthropics/claude-code-action@beta
        timeout-minutes: 30
        with:
          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}

          # Custom trigger phrase for fix workflow
          trigger_phrase: "@claude-fix"

          # Fix-specific instructions
          custom_instructions: |
            You are authorized to IMPLEMENT FIXES and CREATE PULL REQUESTS.

            ## Your Role
            You are fixing issues in Archon V2 Beta. Follow CLAUDE.md for project principles and commands.

            ## Architecture Context
            - Frontend: React + TypeScript + Vite (port 3737)
            - Backend: FastAPI + Socket.IO + Python (port 8181)
            - MCP Service: MCP protocol server (port 8051)
            - Agents Service: PydanticAI agents (port 8052)
            - Database: Supabase (PostgreSQL + pgvector)

            ## Fix Workflow - MINIMAL CHANGES ONLY

            ### 1. ROOT CAUSE ANALYSIS (RCA)
            - **Reproduce**: Can you reproduce the issue? If not, state why
            - **Identify**: Use ripgrep to search for error messages, function names, patterns
            - **Trace**: Follow the execution path using git blame and code navigation
            - **Root Cause**: What is the ACTUAL cause vs symptoms?
               - Is it a typo/syntax error?
               - Is it a logic error?
               - Is it a missing dependency?
               - Is it a type mismatch?
               - Is it an async/timing issue?
               - Is it a state management issue?

            ### 2. MINIMAL FIX STRATEGY
            - **Scope**: Fix ONLY the root cause, nothing else
            - **Pattern Match**: Look for similar code in the codebase - follow existing patterns
            - **Side Effects**: Will this break anything else? Check usages with ripgrep
            - **Alternative**: If fix seems too invasive, document alternative approaches

            ### 3. IMPLEMENTATION
            - Create branch: `fix/issue-{number}` or `fix/pr-{number}-{description}` or `fix/{brief-description}`
            - Make the minimal change that fixes the root cause
            - If existing tests break, understand why before changing them
            - Add test to prevent regression (especially for bug fixes)

            ### 4. VERIFICATION LOOP
            - Run tests according to CLAUDE.md commands
            - If tests fail:
               - Analyze why they failed
               - Is it your fix or unrelated?
               - Fix and retry until all green
            - If fix breaks something else:
               - Do another RCA on the new issue
               - Consider alternative approach
               - Document tradeoffs in PR

            ### 5. PULL REQUEST
            Use the template in .github/pull_request_template.md:
            - Fill all sections accurately
            - Mark type as "Bug fix"
            - Show test evidence with actual command outputs
            - If can't fix completely, document what's blocking in Additional Notes

            ## Decision Points
            - **Don't fix if**: Needs product decision, requires major refactoring, or changes core architecture
            - **Document blockers**: If something prevents a complete fix, explain in PR
            - **Ask for guidance**: Use PR description to ask questions if uncertain

            ## Remember
            - The person triggering this workflow wants a fix - deliver one or explain why you can't
            - Follow CLAUDE.md for all commands and project principles
            - Prefer ripgrep over grep for searching
            - Keep changes minimal - resist urge to refactor
            - Beta project: Quick fixes over perfect solutions

          # Commented out - using default tools
          # allowed_tools: "Edit(*),MultiEdit(*),Write(*),Read(*),Grep(*),LS(*),Glob(*),TodoWrite(*),NotebookEdit(*),Bash(git *),Bash(npm *),Bash(uv *),Bash(python *),Bash(pip *),Bash(cd *),Bash(pwd),Bash(ls *),Bash(cat *),Bash(head *),Bash(tail *),Bash(wc *),Bash(find *),Bash(grep *),Bash(rg *),Bash(sed *),Bash(awk *),Bash(curl *),Bash(wget *),Bash(echo *),Bash(mkdir *),Bash(rm -rf node_modules),Bash(rm -rf __pycache__),Bash(rm -rf .pytest_cache),WebSearch(*),WebFetch(*)"

  unauthorized-message:
    # Post message for unauthorized users
    if: |
      (
        github.event_name == 'issue_comment' ||
        github.event_name == 'pull_request_review_comment'
      ) &&
      contains(github.event.comment.body, '@claude-fix') &&
      !contains(fromJSON('["Wirasm", "coleam00", "sean-eskerium"]'), github.event.comment.user.login)

    runs-on: ubuntu-latest

    permissions:
      issues: write
      pull-requests: write

    steps:
      - name: Post unauthorized message
        uses: actions/github-script@v7
        with:
          script: |
            const comment = {
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `❌ @${context.actor} - You are not authorized to trigger Claude fixes.\n\nOnly maintainers can trigger Claude: Please ask a maintainer to run the fix command.`
            };

            if (context.eventName === 'issue_comment') {
              await github.rest.issues.createComment({
                ...comment,
                issue_number: context.issue.number
              });
            } else if (context.eventName === 'pull_request_review_comment') {
              await github.rest.pulls.createReplyForReviewComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: context.payload.pull_request.number,
                comment_id: context.payload.comment.id,
                body: comment.body
              });
            }
