name: Release & Publish

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
      - uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
      - run: uv sync --extra dev
      - run: uv run pytest
      - run: uv run ruff check
      - run: uv run ruff format --check

  release:
    needs: test
    runs-on: ubuntu-latest
    environment: pypi
    concurrency: release
    permissions:
      contents: write
      id-token: write

    steps:
      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          fetch-depth: 0

      - name: Install uv
        uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0
        with:
          python-version: "3.12"

      - name: Python Semantic Release
        id: release
        uses: python-semantic-release/python-semantic-release@754a065a2ea187da71977ada6630a8ec0f98e380 # v10.5.3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}

      - name: Build wheel
        if: steps.release.outputs.released == 'true'
        run: uv build

      - name: Upload to GitHub Release
        if: steps.release.outputs.released == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        # --clobber: allow safe re-runs if the workflow is retried
        run: gh release upload --clobber ${{ steps.release.outputs.tag }} dist/*

      - name: Publish to PyPI
        if: steps.release.outputs.released == 'true'
        uses: pypa/gh-action-pypi-publish@v1.13.0

      - name: Snapshot versioned docs
        if: steps.release.outputs.released == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Extract major.minor from tag (e.g. v1.7.0 -> v1.7)
          TAG="${{ steps.release.outputs.tag }}"
          VERSION_DIR="v${TAG#v}"
          VERSION_DIR="${VERSION_DIR%.*}"

          # Build docs
          cd docs-site
          npm ci
          npm run build
          cd ..

          # Copy built docs into versioned directory
          mkdir -p "docs-site/versioned/${VERSION_DIR}"
          cp -r docs-site/.vitepress/dist/* "docs-site/versioned/${VERSION_DIR}/"

          # Commit versioned snapshot
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add "docs-site/versioned/${VERSION_DIR}"
          git commit -m "docs: snapshot ${VERSION_DIR} docs" || true
          git push || true
