# AIWG Code Review with Codex
#
# Automated code review using OpenAI Codex CLI with AIWG standards.
# This workflow runs on pull requests and posts review comments.
#
# Prerequisites:
# - OPENAI_API_KEY secret configured
# - Codex CLI installed (npm install -g @openai/codex)
#
# Usage:
# Copy this file to .github/workflows/aiwg-codex-review.yml

name: AIWG Code Review (Codex)

on:
  pull_request:
    types: [opened, synchronize, reopened]

permissions:
  contents: read
  pull-requests: write

jobs:
  review:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Codex CLI
        run: npm install -g @openai/codex

      - name: Get changed files
        id: changed
        run: |
          echo "files=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | tr '\n' ' ')" >> $GITHUB_OUTPUT

      - name: Run AIWG Code Review
        id: review
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          codex exec "Review the following files for code quality, security, and best practices:

          Changed files: ${{ steps.changed.outputs.files }}

          Review criteria:
          1. Security - Check for injection vulnerabilities, auth issues, data exposure
          2. Performance - Identify N+1 queries, unnecessary loops, missing caching
          3. Code Quality - Clean code principles, error handling, edge cases
          4. Testing - Verify test coverage, suggest missing tests
          5. Documentation - Check for missing or outdated comments

          Output a structured review with:
          - Overall assessment (approve/request-changes/comment)
          - Critical issues (must fix)
          - Suggestions (nice to have)
          - Specific line-by-line feedback where applicable

          Be constructive and specific. Reference exact files and line numbers." \
            --full-auto \
            --sandbox read-only \
            -o review-output.md

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const fs = require('fs');
            const review = fs.readFileSync('review-output.md', 'utf8');

            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: `## AIWG Code Review (Codex)\n\n${review}\n\n---\n*Automated review by [AIWG](https://aiwg.io) + OpenAI Codex*`
            });
