# Filename: .github/workflows/gemini-pr-review.yaml

name: Gemini PR Review

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

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  gemini-pr-review:
    runs-on: ubuntu-latest
    name: Gemini PR Review

    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0 # This fetches the full history

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

      - name: Get npm cache directory
        id: npm-cache-dir
        run: |
          echo "dir=$(npm config get cache)" >> $GITHUB_OUTPUT

      - name: Cache global npm packages
        uses: actions/cache@v4
        with:
          path: ${{ steps.npm-cache-dir.outputs.dir }}
          key: ${{ runner.os }}-npm-global-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-npm-global-

      - name: Install Gemini CLI globally (if not already installed)
        run: |
          if ! command -v gemini &> /dev/null; then
            echo "Gemini CLI not found, installing..."
            npm install -g --loglevel=http @google/gemini-cli
          else
            echo "Gemini CLI already installed."
          fi

      - name: Generate git diff and review with Gemini
        id: review
        env:
          GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
        run: |
          echo "Generating diff..."
          git diff "${{ gitea.event.pull_request.base.sha }}...${{ gitea.event.pull_request.head.sha }}" > pr.diff

          echo "Performing code review with Gemini..."
          cat .github/workflows/gemini-pr-review.md pr.diff |  gemini > /tmp/gemini-output.txt

          cat /tmp/gemini-client-error*.json || true

      - name: Post output to PR comment
        id: post_comment
        run: |
          JSON_PAYLOAD=$(python3 -c 'import json, sys; print(json.dumps({"body": sys.stdin.read()}))' < /tmp/gemini-output.txt)
          curl --request POST --silent --show-error \
          --url "${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/issues/${{ gitea.event.pull_request.number }}/comments" \
          --header "Authorization: token ${{ secrets.GITEA_TOKEN }}" \
          --header "Content-Type: application/json" \
          --header "accept: application/json" \
          --data "${JSON_PAYLOAD}"
