name: CI

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

permissions:
  contents: write
  issues: write
  pull-requests: write

jobs:
  commitlint:
    name: Commit Lint
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v6
        with:
          node-version: lts/*
      - run: npm install -D @commitlint/cli @commitlint/config-conventional
      - name: Validate current commit (last commit) with commitlint
        if: github.event_name == 'push'
        run: npx commitlint --last --verbose
      - name: Validate PR commits with commitlint
        if: github.event_name == 'pull_request'
        run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Install uv
        uses: astral-sh/setup-uv@v7

      - name: Install dependencies
        run: uv sync

      - name: Run tests
        run: uv run pytest -v

  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Install uv
        uses: astral-sh/setup-uv@v7

      - name: Run ruff check
        run: uvx ruff check src/ tests/

      - name: Run ruff format check
        run: uvx ruff format --check src/ tests/

  typecheck:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Install uv
        uses: astral-sh/setup-uv@v7

      - name: Install dependencies
        run: uv sync

      - name: Run ty type check
        run: uvx ty check src/

  release:
    name: Release
    runs-on: ubuntu-latest
    needs: [commitlint, test, lint, typecheck]
    if: github.event_name == 'push' && github.ref == 'refs/heads/master'
    # Prevent concurrent releases from racing (would cause "tag already exists" errors)
    concurrency:
      group: release
      cancel-in-progress: false
    permissions:
      contents: write
      issues: write
      pull-requests: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
          persist-credentials: false
      - uses: actions/setup-node@v6
        with:
          node-version: lts/*
      - name: Install uv
        uses: astral-sh/setup-uv@v7
      - name: Install dependencies
        run: npm install -D semantic-release @semantic-release/changelog @semantic-release/git @semantic-release/exec
      - name: Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: npx semantic-release
