name: Semantic Release

on:
  push:
    branches:
      - main

concurrency:
  group: semantic-release
  cancel-in-progress: true

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
    env:
      FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

    steps:
      - name: Checkout source code
        uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install uv
        uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5

      - name: Set up Python
        run: uv python install 3.12

      - name: Version and Build (Semantic Release)
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        # This calculates the version, updates files, commits, tags, and runs `uv build` to populate the dist/ folder
        run: uv tool run --from python-semantic-release semantic-release version

      - name: Sync spec file version
        if: hashFiles('dist/*') != ''
        run: |
          NEW_VERSION=$(grep '^version' pyproject.toml | head -1 | sed 's/.*"\(.*\)"/\1/')
          sed -i "s/^Version:.*/Version:        ${NEW_VERSION}/" dracs.spec
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add dracs.spec
          git diff --cached --quiet || git commit -m "chore: sync spec file version to ${NEW_VERSION} [skip ci]"
          git push

      - name: Publish package to PyPI
        # 👇 Only run if the dist directory exists and has files
        if: hashFiles('dist/*') != ''
        uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # release/v1
        # No password/token needed here! It uses the id-token permission to authenticate securely.
        # It will automatically find the .whl and .tar.gz files in the dist/ folder.

      - name: Create GitHub Release
        # 👇 Only run if the dist directory exists and has files
        if: hashFiles('dist/*') != ''
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        # Pushes the GitHub Release out to your repository
        run: uv tool run --from python-semantic-release semantic-release publish

