name: Deploy TinyTorch Jupyter Book (Streamlined with tito)

# Trigger the workflow on push to main branch (publishing) or manual dispatch
# This workflow uses tito CLI for consistent book generation and building
on:
  push:
    branches: [ main ]
    paths:
      - 'book/**'
      - 'modules/source/**'
      - '.github/workflows/deploy-book.yml'
      - 'tito/**'  # Also trigger when tito CLI changes
  pull_request:
    branches: [ main ]
    paths:
      - 'book/**'
      - 'modules/source/**'
      - 'tito/**'
  workflow_dispatch:

# Set permissions for GitHub Pages deployment and content modification
permissions:
  contents: write
  pages: write
  id-token: write

# Allow only one concurrent deployment
concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        token: ${{ secrets.GITHUB_TOKEN }}

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

    - name: Install dependencies
      run: |
        pip install --upgrade pip
        pip install jupyter-book jupytext pytest
        pip install -r book/requirements.txt
        pip install -r requirements.txt  # Install main project dependencies
        pip install -e .  # Install tito CLI
        
    - name: Generate content and build book
      run: |
        # Create and activate virtual environment for tito
        python -m venv .venv
        source .venv/bin/activate
        pip install -r requirements.txt  # Install all dependencies including rich
        pip install -e .  # Install tito CLI in virtual environment
        # Use tito to generate content and build book
        tito book build
        
    - name: Upload book artifact
      uses: actions/upload-pages-artifact@v3
      with:
        path: book/_build/html

  deploy:
    # Only deploy on main branch pushes (not PRs)
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
    - name: Deploy to GitHub Pages
      id: deployment
      uses: actions/deploy-pages@v4 