name: Fix Formatting

on:
  issue_comment:
    types: [created]

jobs:
  fix-formatting:
    if: github.event.issue.pull_request && contains(github.event.comment.body, '/fix-formatting')
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Get PR info
        id: pr-info
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          PR_DATA=$(gh api repos/${{ github.repository }}/pulls/${{ github.event.issue.number }})
          echo "head_ref=$(echo $PR_DATA | jq -r '.head.ref')" >> $GITHUB_OUTPUT
          echo "base_ref=$(echo $PR_DATA | jq -r '.base.ref')" >> $GITHUB_OUTPUT

      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          ref: ${{ steps.pr-info.outputs.head_ref }}

      - name: Install uv
        uses: astral-sh/setup-uv@v8.1.0

      - name: Run prek
        id: prek
        uses: j178/prek-action@v2
        continue-on-error: true
        with:
          extra-args: --from-ref origin/${{ steps.pr-info.outputs.base_ref }}

      - name: Push fixes if any
        env:
          GH_TOKEN: ${{ github.token }}
          PREK_OUTCOME: ${{ steps.prek.outcome }}
        run: |
          git fetch origin ${{ steps.pr-info.outputs.base_ref }}

          if [ -n "$(git status --porcelain)" ]; then
            git config user.name "github-actions[bot]"
            git config user.email "github-actions[bot]@users.noreply.github.com"
            git add .
            git commit -m "fix: auto-format with prek"
            git push
            gh pr comment ${{ github.event.issue.number }} --body "✅ Fixed formatting with prek and pushed."
          elif [ "$PREK_OUTCOME" = "failure" ]; then
            gh pr comment ${{ github.event.issue.number }} --body "❌ Prek found issues but couldn't auto-fix them. Please check the logs."
            exit 1
          else
            gh pr comment ${{ github.event.issue.number }} --body "✅ No formatting issues found."
          fi
