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<1.0"
        pip install -r book/requirements.txt
        
    - name: Build Jupyter Book
      run: |
        cd book
        jupyter-book clean . || true
        jupyter-book build .
        echo "=== Contents of book after build ==="
        ls -la 
        echo "=== Contents of _build (if exists) ==="
        ls -la _build/ || echo "_build doesn't exist"
        echo "=== Contents of _build/html (if exists) ==="
        ls -la _build/html/ || echo "_build/html doesn't exist"
        
    - 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 