name: Format Check

# This workflow triggers when a PR is opened/updated
# Posts inline suggestion comments instead of auto-committing
on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - main
      - release

concurrency:
  group: format-check-${{ github.event.pull_request.number }}
  cancel-in-progress: true

env:
  PYTHON_VERSION: "3.14.3"

jobs:
  format_check:
    permissions:
      contents: read
      pull-requests: write
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          persist-credentials: false

      - uses: reviewdog/action-actionlint@0d952c597ef8459f634d7145b0b044a9699e5e43 # v1.71.0

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt

      - name: Run cargo fmt
        run: cargo fmt --all

      - name: Install ruff
        uses: astral-sh/ruff-action@4919ec5cf1f49eff0871dbcea0da843445b837e6 # v3.6.1
        with:
          version: "0.15.4"
          args: "--version"

      - name: Run ruff format
        run: ruff format

      - name: Run ruff check import sorting
        run: ruff check --select I --fix

      - uses: actions/setup-python@v6.2.0
        with:
          python-version: ${{ env.PYTHON_VERSION }}

      - name: Run generate_opcode_metadata.py
        run: python scripts/generate_opcode_metadata.py

      - name: Check for formatting changes
        run: |
          if ! git diff --exit-code; then
            echo "::error::Formatting changes detected. Please run 'cargo fmt --all', 'ruff format', and 'ruff check --select I --fix' locally."
            exit 1
          fi

      - name: Post formatting suggestions
        if: failure()
        uses: reviewdog/action-suggester@v1
        with:
          tool_name: auto-format
          github_token: ${{ secrets.GITHUB_TOKEN }}
          level: warning
          filter_mode: diff_context
