name: Release

on:
  push:
    tags: ["v*"]
  workflow_dispatch:

permissions: {}

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      contents: read
    steps:
      - name: Validate tag ref
        run: |
          if [[ "$GITHUB_REF_NAME" != v* ]]; then
            echo "::error::Release must be triggered by a v* tag push. For manual dispatch, use: gh workflow run release.yml --ref v1.2.3"
            exit 1
          fi
      - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
      - uses: astral-sh/setup-uv@e58605a9b6da7c637471fab8847a5e5a6b8df081 # v5
      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
        with:
          python-version: "3.13"
      - run: uv build
      - run: uvx twine check dist/*
      - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
        with:
          name: dist
          path: dist/
          retention-days: 1

  testpypi:
    needs: build
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment: testpypi
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
        with:
          name: dist
          path: dist/
      - uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # release/v1
        with:
          repository-url: https://test.pypi.org/legacy/

  test-install:
    needs: testpypi
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: astral-sh/setup-uv@e58605a9b6da7c637471fab8847a5e5a6b8df081 # v5
      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
        with:
          python-version: "3.13"
      - name: Install from TestPyPI
        run: |
          VERSION="${GITHUB_REF_NAME#v}"
          for attempt in 1 2 3 4 5; do
            echo "Attempt $attempt: installing {{ package_name }}==$VERSION from TestPyPI..."
            if uv pip install --system \
              --index-url https://test.pypi.org/simple/ \
              --extra-index-url https://pypi.org/simple/ \
              "{{ package_name }}==$VERSION"; then
              echo "Successfully installed {{ package_name }}==$VERSION"
              exit 0
            fi
            echo "Attempt $attempt failed, waiting 30s..."
            sleep 30
          done
          echo "Failed to install {{ package_name }}==$VERSION after 5 attempts"
          exit 1
      - name: Verify CLI
        run: {{ cli_command }} --help

  pypi:
    needs: test-install
    runs-on: ubuntu-latest
    timeout-minutes: 10
    environment: release
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
        with:
          name: dist
          path: dist/
      - uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # release/v1
