name: mdBook Build & Deploy

on:
  push:
    branches:
      - main
    paths:
      - 'docs/**'
      - '.github/workflows/mdbook-build-deploy.yml'
  pull_request:
    branches:
      - main
    paths:
      - 'docs/**'

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

concurrency:
  group: mdbook-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build:
    name: Build mdBook
    runs-on: ubuntu-latest
    outputs:
      artifact-name: ${{ steps.upload.outputs.artifact-name }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install mdBook
        run: cargo install mdbook
        shell: bash

      - name: Build mdBook
        working-directory: docs
        run: |
          echo "Building mdBook documentation..."
          mdbook build
          echo "Build output size:"
          du -sh book/
        shell: bash

      - name: Validate HTML output
        working-directory: docs/book
        run: |
          echo "Validating generated HTML..."
          [ -f "index.html" ] && echo "✓ index.html exists" || exit 1
          [ -f "print.html" ] && echo "✓ print.html exists" || exit 1
          [ -f "css/general.css" ] && echo "✓ CSS files exist" || exit 1
          [ -f "js/book.js" ] && echo "✓ JavaScript files exist" || exit 1
          echo "✓ All essential files present"
        shell: bash

      - name: Count generated pages
        working-directory: docs/book
        run: |
          page_count=$(find . -name "*.html" -type f | wc -l)
          echo "Total HTML pages generated: $page_count"
        shell: bash

      - name: Upload artifact
        id: upload
        uses: actions/upload-artifact@v4
        with:
          name: mdbook-site-${{ github.sha }}
          path: docs/book/
          retention-days: 30
          if-no-files-found: error

      - name: Artifact summary
        run: |
          echo "## mdBook Build Artifact" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Artifact Name:** mdbook-site-${{ github.sha }}" >> $GITHUB_STEP_SUMMARY
          echo "**Commit:** ${{ github.sha }}" >> $GITHUB_STEP_SUMMARY
          echo "**Branch:** ${{ github.ref_name }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "✅ mdBook documentation built successfully" >> $GITHUB_STEP_SUMMARY

  quality-check:
    name: Documentation Quality Check
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: mdbook-site-${{ github.sha }}
          path: docs/book/

      - name: Check for broken links (basic)
        working-directory: docs/book
        run: |
          echo "Checking for common issues..."

          # Check if index.html contains expected content
          if grep -q "VAPORA" index.html; then
            echo "✓ Content verification passed"
          else
            echo "⚠ Content verification warning"
          fi

          # Check for empty files
          empty_files=$(find . -type f -size 0 | wc -l)
          if [ "$empty_files" -eq 0 ]; then
            echo "✓ No empty files found"
          else
            echo "⚠ Warning: Found $empty_files empty files"
          fi

          # Check CSS files
          if [ -d "css" ] && [ $(ls css/*.css 2>/dev/null | wc -l) -gt 0 ]; then
            echo "✓ CSS files present"
          else
            echo "❌ CSS files missing"
            exit 1
          fi
        shell: bash

      - name: Generate quality report
        working-directory: docs/book
        run: |
          echo "## Documentation Quality Report" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### File Statistics" >> $GITHUB_STEP_SUMMARY
          echo "- Total files: $(find . -type f | wc -l)" >> $GITHUB_STEP_SUMMARY
          echo "- HTML files: $(find . -name '*.html' | wc -l)" >> $GITHUB_STEP_SUMMARY
          echo "- CSS files: $(find css -name '*.css' 2>/dev/null | wc -l)" >> $GITHUB_STEP_SUMMARY
          echo "- JavaScript files: $(find js -name '*.js' 2>/dev/null | wc -l)" >> $GITHUB_STEP_SUMMARY
          echo "- Total size: $(du -sh . | cut -f1)" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### Status" >> $GITHUB_STEP_SUMMARY
          echo "✅ Quality checks passed" >> $GITHUB_STEP_SUMMARY

  deploy-to-pages:
    name: Deploy to GitHub Pages
    runs-on: ubuntu-latest
    needs: [build, quality-check]
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: mdbook-site-${{ github.sha }}
          path: docs/book/

      - name: Setup Pages
        uses: actions/configure-pages@v4

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

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

      - name: Pages deployment summary
        run: |
          echo "## GitHub Pages Deployment" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          if [ "${{ job.status }}" == "success" ]; then
            echo "✅ Successfully deployed to GitHub Pages" >> $GITHUB_STEP_SUMMARY
            echo "📖 Documentation URL: ${{ steps.deployment.outputs.page_url }}" >> $GITHUB_STEP_SUMMARY
          else
            echo "⚠ GitHub Pages deployment skipped or unavailable" >> $GITHUB_STEP_SUMMARY
            echo "This is expected if not using GitHub.com or Pages not configured" >> $GITHUB_STEP_SUMMARY
          fi
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Build artifact retained for 30 days**" >> $GITHUB_STEP_SUMMARY

  notify:
    name: Notification
    runs-on: ubuntu-latest
    needs: [build, quality-check]
    if: always()
    steps:
      - name: Build Status
        run: |
          if [ "${{ needs.build.result }}" == "success" ] && [ "${{ needs.quality-check.result }}" == "success" ]; then
            echo "✅ mdBook documentation build successful"
            echo "## Build Summary" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "| Component | Status |" >> $GITHUB_STEP_SUMMARY
            echo "|-----------|--------|" >> $GITHUB_STEP_SUMMARY
            echo "| Build | ✅ Success |" >> $GITHUB_STEP_SUMMARY
            echo "| Quality Checks | ✅ Passed |" >> $GITHUB_STEP_SUMMARY
            echo "| Artifact | ✅ Uploaded |" >> $GITHUB_STEP_SUMMARY
            exit 0
          else
            echo "❌ mdBook documentation build failed"
            echo "## Build Summary" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "| Component | Status |" >> $GITHUB_STEP_SUMMARY
            echo "|-----------|--------|" >> $GITHUB_STEP_SUMMARY
            echo "| Build | ${{ needs.build.result }} |" >> $GITHUB_STEP_SUMMARY
            echo "| Quality Checks | ${{ needs.quality-check.result }} |" >> $GITHUB_STEP_SUMMARY
            exit 1
          fi
