name: Publish to PyPI

on:
  push:
    tags:
      - "v*.*.*"  # Trigger only on version tags like v0.1.9

jobs:
  validate:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get_version.outputs.version }}
      tag_version: ${{ steps.get_version.outputs.tag_version }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Get version from tag and pyproject.toml
        id: get_version
        run: |
          TAG_VERSION=${GITHUB_REF#refs/tags/v}
          echo "tag_version=$TAG_VERSION" >> $GITHUB_OUTPUT

          PYPROJECT_VERSION=$(grep -Po '(?<=^version = ")[^"]*' pyproject.toml)
          echo "version=$PYPROJECT_VERSION" >> $GITHUB_OUTPUT

          echo "Tag version: v$TAG_VERSION"
          echo "pyproject.toml version: $PYPROJECT_VERSION"

      - name: Verify version match
        run: |
          if [ "${{ steps.get_version.outputs.tag_version }}" != "${{ steps.get_version.outputs.version }}" ]; then
            echo "Error: Tag version (${{ steps.get_version.outputs.tag_version }}) does not match pyproject.toml version (${{ steps.get_version.outputs.version }})"
            exit 1
          fi
          echo "Version validation passed: ${{ steps.get_version.outputs.version }}"

  test:
    runs-on: ubuntu-latest
    needs: validate

    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.10", "3.11", "3.12", "3.13"]

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
          cache: 'pip'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install .[dev]

      - name: Run tests
        run: pytest -v

  publish:
    runs-on: ubuntu-latest
    needs: [validate, test]
    environment:
      name: pypi
      url: https://pypi.org/project/uniface/

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"
          cache: 'pip'

      - name: Install build tools
        run: |
          python -m pip install --upgrade pip
          python -m pip install build twine

      - name: Build package
        run: python -m build

      - name: Check package
        run: twine check dist/*

      - name: Publish to PyPI
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: twine upload dist/*

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          files: dist/*
          generate_release_notes: true

