# This workflow will upload the CSE.LK Python Package to PyPI when a release is created
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries

name: Publish CSE.LK to PyPI

on:
  release:
    types: [published]
  # Allow manual triggering for testing
  workflow_dispatch:

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]

    steps:
      - uses: actions/checkout@v4

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

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

      - name: Run tests
        run: |
          python -m pytest tests/ -v --tb=short

      - name: Run linting
        run: |
          python -m black --check cse_lk/ tests/ examples/
          python -m flake8 cse_lk/ tests/ examples/ --max-line-length=88 --extend-ignore=E203,W503

  release-build:
    runs-on: ubuntu-latest
    needs: test  # Only build if tests pass

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.x"

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

      - name: Build release distributions
        run: |
          python -m build

      - name: Check distributions
        run: |
          python -m twine check dist/*

      - name: Upload distributions as artifacts
        uses: actions/upload-artifact@v4
        with:
          name: release-dists
          path: dist/

  pypi-publish:
    runs-on: ubuntu-latest
    needs: release-build
    permissions:
      # IMPORTANT: this permission is mandatory for trusted publishing
      id-token: write

    # Use a dedicated environment for PyPI publishing with protection rules
    environment:
      name: pypi
      url: https://pypi.org/project/cse.lk/

    steps:
      - name: Retrieve release distributions
        uses: actions/download-artifact@v4
        with:
          name: release-dists
          path: dist/

      - name: Publish CSE.LK to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          packages-dir: dist/
          print-hash: true 