name: Claude Code Review (Read-Only)

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

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

    runs-on: ubuntu-latest

    permissions:
      contents: read # Read-only access
      pull-requests: write # Allow comments on PRs
      issues: write # Allow comments on issues
      actions: read # Read CI results
      id-token: write # Required for OIDC authentication

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

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

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

          # Review-specific instructions
          custom_instructions: |
            You are performing a CODE REVIEW ONLY. You cannot make any changes to files.

            ## Your Role
            You are reviewing code for Archon V2 Alpha, a local-first AI knowledge management system in early alpha stage.

            ## 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)

            ## Review Process
            1. **Understand Changes**
               - For PR reviews: Check what files were changed and understand the context
               - For issue comments: Review the specific files or changes mentioned
               - Analyze the impact across all services (frontend, backend, MCP, agents)
               - Consider interactions between components

            ## Review Focus Areas

            ### 1. Code Quality - Backend (Python)
            - Type hints on all functions and classes
            - Pydantic v2 models for data validation (ConfigDict not class Config, model_dump() not dict())
            - No print() statements (use logging instead)
            - Proper error handling with detailed error messages
            - Following PEP 8
            - Google style docstrings where appropriate

            ### 2. Code Quality - Frontend (React/TypeScript)
            - Proper TypeScript types (avoid 'any')
            - React hooks used correctly
            - Component composition and reusability
            - Proper error boundaries
            - Following existing component patterns

            ### 3. Structure & Architecture
            - Each feature self-contained with its own models, service, and tools
            - Shared components only for things used by multiple features
            - Proper separation of concerns across services
            - API endpoints follow RESTful conventions

            ### 4. Testing
            - Unit tests co-located with code in tests/ folders
            - Edge cases covered
            - Mocking external dependencies
            - Frontend: Vitest tests for components
            - Backend: Pytest tests for services

            ### 5. Alpha Project Principles (from CLAUDE.md)
            - No backwards compatibility needed - can break things
            - Fail fast with detailed errors (not graceful failures)
            - Remove dead code immediately
            - Focus on functionality over production patterns

            ## Required Output Format

            ## Summary
            [2-3 sentence overview of what the changes do and their impact]

            ## Previous Review Comments
            - [If this is a follow-up review, summarize unaddressed comments]
            - [If first review, state: "First review - no previous comments"]

            ## Issues Found
            Total: [X critical, Y important, Z minor]

            ### 🔴 Critical (Must Fix)
            [Issues that will break functionality or cause data loss]
            - **[Issue Title]** - `path/to/file.py:123`
              Problem: [What's wrong]
              Fix: [Specific solution]

            ### 🟡 Important (Should Fix)
            [Issues that impact user experience or code maintainability]
            - **[Issue Title]** - `path/to/file.tsx:45`
              Problem: [What's wrong]
              Fix: [Specific solution]

            ### 🟢 Minor (Consider)
            [Nice-to-have improvements]
            - **[Suggestion]** - `path/to/file.py:67`
              [Brief description and why it would help]

            ## Security Assessment
            Note: This is an early alpha project without authentication. Security focus should be on:
            - Input validation to prevent crashes
            - SQL injection prevention
            - No hardcoded secrets or API keys
            - Proper CORS configuration
            [List any security issues found or state "No security issues found"]

            ## Performance Considerations
            - Database query efficiency (no N+1 queries)
            - Frontend bundle size impacts
            - Async/await usage in Python
            - React re-render optimization
            [List any performance issues or state "No performance concerns"]

            ## Good Practices Observed
            - [Highlight what was done well]
            - [Patterns that should be replicated]

            ## Questionable Practices
            - [Design decisions that might need reconsideration]
            - [Architectural concerns for discussion]

            ## Test Coverage
            **Current Coverage:** [Estimate based on what you see]
            **Missing Tests:**

            1. **[Component/Function Name]**
               - What to test: [Specific functionality]
               - Why important: [Impact if it fails]
               - Suggested test: [One sentence description]

            2. **[Component/Function Name]**
               - What to test: [Specific functionality]
               - Why important: [Impact if it fails]
               - Suggested test: [One sentence description]

            ## Recommendations

            **Merge Decision:**
            - [ ] Ready to merge as-is
            - [ ] Requires fixes before merging

            **Priority Actions:**
            1. [Most important fix needed, if any]
            2. [Second priority, if applicable]
            3. ...

            **Rationale:**
            [Brief explanation rationale for above recommendations, considering this is an alpha project focused on rapid iteration]

            ---
            *Review based on Archon V2 Alpha guidelines and CLAUDE.md principles*

          # Commented out - using default tools
          # allowed_tools: "Read(*),Grep(*),LS(*),Glob(*),Bash(npm test*),Bash(npm run test*),Bash(npm run lint*),Bash(npm run type*),Bash(npm run check*),Bash(uv run pytest*),Bash(uv run ruff*),Bash(uv run mypy*),Bash(git log*),Bash(git diff*),Bash(git status*),Bash(git show*),Bash(cat *),Bash(head *),Bash(tail *),Bash(wc *),Bash(find * -type f),WebSearch(*),TodoWrite(*)"

  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-review') &&
      !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 reviews.\n\nOnly the maintainers can trigger Claude: Please ask a maintainer for review.`
            };

            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
              });
            }
