name: Code Quality

on:
  pull_request:
    branches:
      - main
  push:
    branches:
      - main

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install uv
        uses: astral-sh/setup-uv@v4
        with:
          enable-cache: true
      - name: Set up Python
        run: uv python install
      - name: Install the project
        run: uv sync --all-extras --dev
      - name: Activate venv
        run: |
          source .venv/bin/activate
          echo "VIRTUAL_ENV=${VIRTUAL_ENV}" >> $GITHUB_ENV
          echo "${VIRTUAL_ENV}/bin" >> $GITHUB_PATH
          echo "VIRTUAL_ENV=${VIRTUAL_ENV}"

      - name: Linting rules
        run: ruff check --output-format=github
      - name: Formatting rules
        run: |
          set +e

          echo "::add-matcher::.github/matchers/ruff-format.json"

          ruff format --check
          RUFF_EXIT_CODE="$?"

          echo "::remove-matcher owner=ruff::"

          exit "$RUFF_EXIT_CODE"
      - name: Type checking
        run: |
          GIT_TOPLEVEL=$(git rev-parse --show-toplevel)

          pyright --version

          echo "::add-matcher::.github/matchers/pyright.json"

          pyright --outputjson \
            | jq ".generalDiagnostics" \
            | jq --arg "GIT_TOPLEVEL" "$GIT_TOPLEVEL" '.[].file |= ltrimstr($GIT_TOPLEVEL) | .[].file |= ltrimstr("/")' \
            | jq -r '.[] | .file + ":" + (.range.start.line | tostring) + ":" + (.range.end.line | tostring) + " - " + (.message | split("\n")[0])'
          PYRIGHT_EXIT_CODE="${PIPESTATUS[0]}"

          echo "::remove-matcher owner=pyright::"

          exit "$PYRIGHT_EXIT_CODE"