# Build and publish to PyPI when a version tag (v*) is pushed.
# Also supports manual run (workflow_dispatch); then version is taken from pyproject.toml.

name: Build and Publish

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

permissions:
  id-token: write   # Required for PyPI Trusted Publishing (OIDC)
  contents: write   # Required to create GitHub Release from tag

jobs:
  build-and-publish:
    name: Build and Publish to PyPI
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

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

      - name: Set up Node.js
        if: hashFiles('src/pycharter/ui/package.json') != ''
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: src/pycharter/ui/package-lock.json

      - name: Install UI dependencies
        if: hashFiles('src/pycharter/ui/package.json') != ''
        run: |
          cd src/pycharter/ui
          npm ci

      - name: Build UI
        if: hashFiles('src/pycharter/ui/package.json') != ''
        run: |
          cd src/pycharter/ui
          npm run build

      - name: Copy UI build to static
        if: hashFiles('src/pycharter/ui/package.json') != ''
        run: |
          if [ -d src/pycharter/ui/out ] && [ -f src/pycharter/ui/out/index.html ]; then
            rm -rf src/pycharter/ui/static
            cp -r src/pycharter/ui/out src/pycharter/ui/static
          fi

      - name: Install build tools
        run: pip install build

      - name: Build package
        run: python -m build

      - name: Verify package
        run: |
          python -m zipfile -l dist/pycharter-*.whl | head -30
          echo "Package built successfully"

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          packages-dir: dist/

      - name: Create GitHub Release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v2.4.2
        with:
          tag_name: ${{ github.ref_name }}
          name: ${{ github.ref_name }}
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
