# GitHub Actions workflow for building and publishing txaio releases.

name: release

on:
  # Build wheels on feature branches and PRs (test only)
  push:
    branches: ["master"] # run for pushes to master branch
    tags: ["v*"] # run for pushes to tags
  pull_request:
    branches: [master] # run for pushes to PR-branches targeting master
  workflow_dispatch:
    inputs:
      release_tag:
        description: "Tag name to publish (leave empty to skip)"
        required: false

env:
  # Ensure uv and just are available in PATH
  UV_CACHE_DIR: ${{ github.workspace }}/.uv-cache

jobs:
  build-docs:
    name: Build documentation
    runs-on: ubuntu-latest

    # Build documentation when merged to master

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

      - name: Install Just
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to ~/bin
          echo "$HOME/bin" >> $GITHUB_PATH

      - name: Install uv
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          curl -LsSf https://astral.sh/uv/install.sh | sh
          source $HOME/.cargo/env
          echo "$HOME/.cargo/bin" >> $GITHUB_PATH

      - name: Setup uv cache
        uses: actions/cache@v4
        with:
          path: ${{ env.UV_CACHE_DIR }}
          key: uv-cache-ubuntu-docs-${{ hashFiles('pyproject.toml') }}
          restore-keys: |
            uv-cache-ubuntu-docs-

      - name: Create Python environment and install tools
        run: |
          just create cpy314
          just install-tools cpy314

      - name: Build documentation
        run: just docs cpy314

      - name: Upload documentation artifacts
        uses: actions/upload-artifact@v4
        with:
          name: documentation
          path: docs/_build/html/
          retention-days: 30

  build-package:
    name: Build wheels and source distribution
    runs-on: ubuntu-latest

    # Build wheels and source distribution when merged to master

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

      - name: Install Just
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to ~/bin
          echo "$HOME/bin" >> $GITHUB_PATH

      - name: Install uv
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          curl -LsSf https://astral.sh/uv/install.sh | sh
          source $HOME/.cargo/env
          echo "$HOME/.cargo/bin" >> $GITHUB_PATH

      - name: Verify toolchain
        run: |
          export PATH="/root/.cargo/bin:$PATH"
          echo "==> Build environment summary:"
          echo "Just: $(just --version)"
          echo "uv: $(uv --version)"
          echo "Rust: $(rustc --version)"
          echo "Python: $(./.venvs/cpy311/bin/python3)"
          echo "GCC: $(gcc --version | head -1)"
          echo "glibc: $(ldd --version 2>/dev/null | head -1 || echo 'N/A')"

      - name: Build package (wheel and source distribution on CPython 3.11)
        run: just build cpy311

      - name: Generate build metadata
        run: |
          mkdir -p dist/
          cat > dist/build-info.txt << EOF
          Build Information
          =================

          Build Date: $(date -u +"%Y-%m-%d %H:%M:%S UTC")
          Platform: AMD64
          Build Method: GitHub Actions + just/uv/venv

          System Information:
          - OS: $(cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)
          - Kernel: $(uname -r)
          - glibc: $(ldd --version 2>/dev/null | head -1 || echo 'N/A')

          Build Tools:
          - Just: $(just --version)
          - uv: $(uv --version)
          - GCC: $(gcc --version | head -1)
          - Rust: $(rustc --version)
          - Python: $(./.venvs/cpy311/bin/python3)
          EOF

      - name: List build artifacts
        run: |
          echo "==> Built package artifacts:"
          ls -la dist/ 2>/dev/null || echo "No dist/ directory found"
          echo ""
          echo "==> Build metadata:"
          cat dist/build-info.txt 2>/dev/null || echo "No build info found"

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: build-artifacts
          path: dist/*
          retention-days: 30

  publish-github-releases:
    name: Publish to GitHub Releases
    needs: [build-package, build-docs]
    runs-on: ubuntu-latest

    # Publish to GitHub Releases when merged to master

    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: build-artifacts
          path: dist/

      - name: Download documentation artifacts
        uses: actions/download-artifact@v4
        with:
          name: documentation
          path: docs-html/

      - name: Create documentation archive
        run: |
          cd docs-html
          tar -czf ../dist/txaio-docs.tar.gz *
          cd ..

      - name: List all artifacts
        run: |
          echo "All built artifacts:"
          ls -la dist/
          echo ""
          echo "Wheel count: $(ls dist/*.whl | wc -l)"
          echo "Source distributions: $(ls dist/*.tar.gz | wc -l)"
          echo "Documentation archives: $(ls dist/*-docs.tar.gz | wc -l)"

      - name: Create GitHub Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Generate release tag based on timestamp and commit
          RELEASE_TAG="wheels-$(date +'%Y%m%d')-${{ github.sha }}"

          # Delete existing release if it exists (ignore errors)
          gh release delete "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --yes || true

          # Create release
          gh release create "$RELEASE_TAG" \
            --repo "$GITHUB_REPOSITORY" \
            --title "Wheels Build - $(date +'%Y-%m-%d')" \
            --notes "Automated wheel build from commit ${{ github.sha }}" \
            dist/*

  publish-rtd:
    name: Publish docs to RTD
    needs: build-docs
    runs-on: ubuntu-latest

    # Publish docs to RTD when merged to and tagged on master
    if: github.ref_type == 'tag' || github.event.inputs.release_tag != ''

    steps:
      - run: echo "Publishing RTD for tag ${{ github.ref_type == 'tag' && github.ref_name || github.event.inputs.release_tag }}"

      - name: Debug GitHub context
        run: |
          echo "github.ref: ${{ github.ref }}"
          echo "github.event_name: ${{ github.event_name }}"
          echo "github.ref_type: ${{ github.ref_type }}"
          echo "github.ref_name: ${{ github.ref_name }}"
          echo "Condition check: startsWith('${{ github.ref }}', 'refs/tags/')"

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

      - name: Trigger RTD build
        env:
          RTD_TOKEN: ${{ secrets.RTD_TOKEN }}
        run: |
          if [ -n "$RTD_TOKEN" ]; then
            echo "Triggering Read the Docs build for txaio..."
            curl -X POST \
              -H "Authorization: Token $RTD_TOKEN" \
              "https://readthedocs.org/api/v3/projects/txaio/versions/latest/builds/"
          else
            echo "RTD_TOKEN not configured, skipping RTD build trigger"
          fi

  publish-pypi:
    name: Publish to PyPI
    needs: build-package
    runs-on: ubuntu-latest

    # Publish to PyPI when merged to and tagged on master
    if: github.ref_type == 'tag' || github.event.inputs.release_tag != ''

    environment:
      name: pypi
      url: https://pypi.org/p/txaio

    permissions:
      id-token: write # IMPORTANT: this permission is mandatory for trusted publishing

    steps:
      - run: echo "Publishing PyPI for tag ${{ github.ref_type == 'tag' && github.ref_name || github.event.inputs.release_tag }}"

      - name: Debug GitHub context
        run: |
          echo "github.ref: ${{ github.ref }}"
          echo "github.event_name: ${{ github.event_name }}"
          echo "github.ref_type: ${{ github.ref_type }}"
          echo "github.ref_name: ${{ github.ref_name }}"
          echo "Condition check: startsWith('${{ github.ref }}', 'refs/tags/')"

      - name: Download distribution package
        uses: actions/download-artifact@v4
        with:
          name: build-artifacts
          path: dist/

      - name: List all artifacts
        run: |
          echo "All built artifacts:"
          ls -la dist/
          echo ""
          echo "Wheel count: $(ls dist/*.whl | wc -l)"
          echo "Source distributions: $(ls dist/*.tar.gz | wc -l)"

      - name: Remove non-distribution files
        run: |
          # Remove build metadata files that shouldn't go to PyPI
          rm -f dist/build-info.txt dist/*-docs.tar.gz

      - name: Publish package to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          verbose: true
          attestations: true
          print-hash: true
