name: Deploy Documentation to GitHub Pages

on:
  # Trigger whenever there is a push to the default branch
  push:
    branches:
      - master
  # Allow manual workflow dispatch
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: true

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: Install mdbook
        run: |
          cargo install mdbook --no-default-features --features search

      - name: Validate registry index
        run: |
          # Check JSON syntax
          python3 -m json.tool docs/src/registry/index.json > /dev/null
          echo "✅ Registry index JSON is valid"

          # Check required fields
          python3 -c "
          import json
          with open('docs/src/registry/index.json') as f:
              data = json.load(f)

          # Validate structure
          assert 'updated' in data, 'Missing updated field'
          assert 'packs' in data, 'Missing packs field'

          for pack_id, pack in data['packs'].items():
              assert 'id' in pack, f'Pack {pack_id} missing id'
              assert 'latest_version' in pack, f'Pack {pack_id} missing latest_version'
              assert 'versions' in pack, f'Pack {pack_id} missing versions'
              
              for version, version_data in pack['versions'].items():
                  assert 'git_url' in version_data, f'Version {version} missing git_url'
                  assert 'git_rev' in version_data, f'Version {version} missing git_rev'
                  assert 'sha256' in version_data, f'Version {version} missing sha256'

          print('✅ Registry structure validation passed')
          "

      - name: Build documentation
        run: |
          mdbook build docs
          echo "✅ Documentation built successfully"

      - name: Validate HTML output
        run: |
          # Check that main pages exist
          test -f docs/book/index.html || (echo "❌ Missing index.html" && exit 1)
          test -f docs/book/marketplace.html || (echo "❌ Missing marketplace.html" && exit 1)
          test -f docs/book/registry/index.html || (echo "❌ Missing registry/index.html" && exit 1)
          echo "✅ HTML validation passed"

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v4
        with:
          path: docs/book

      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
