# MDBook Documentation Module - Unified Documentation System
# ===========================================================

# MDBook directory
mdbook_dir := provisioning_root / "docs"
mdbook_build := mdbook_dir / "book"
mdbook_src := mdbook_dir / "src"

# ============================================================================
# MDBook Module Help
# ============================================================================

# Show mdbook help
@book-help:
    echo "📖 MDBOOK MODULE HELP"
    echo "====================="
    echo ""
    echo "This module manages the unified mdbook documentation system"
    echo ""
    echo "SETUP:"
    echo "  book-check        Check if mdbook is installed"
    echo "  book-install      Install mdbook and useful plugins"
    echo "  book-init         Initialize new mdbook project"
    echo ""
    echo "BUILD & SERVE:"
    echo "  book-build        Build documentation"
    echo "  book-serve        Serve with live reload (default port: 3000)"
    echo "  book-watch        Watch and rebuild on changes"
    echo "  book-open         Open built docs in browser"
    echo ""
    echo "TESTING & VALIDATION:"
    echo "  book-test         Validate structure and links"
    echo "  book-stats        Show documentation statistics"
    echo ""
    echo "DEPLOYMENT:"
    echo "  book-deploy       Prepare for deployment"
    echo "  book-clean        Clean build artifacts"
    echo ""
    echo "WORKFLOWS:"
    echo "  book-all          Complete build, test, and stats workflow"
    echo ""
    echo "EXAMPLES:"
    echo "  just book-serve                  # Serve on default port 3000"
    echo "  just book-serve 8080             # Serve on custom port"
    echo "  just book-build && book-open     # Build and open in browser"
    echo ""
    echo "LOCATION:"
    echo "  Source:  {{mdbook_src}}"
    echo "  Build:   {{mdbook_build}}"
    echo ""
    echo "💡 Quick start: just book-init && just book-serve"

# ============================================================================
# Setup & Installation
# ============================================================================

# Check if mdbook is installed
@book-check:
    #!/usr/bin/env bash
    if command -v mdbook >/dev/null 2>&1; then
        echo "✅ mdbook is installed: $(mdbook --version)"
    else
        echo "❌ mdbook is not installed"
        echo ""
        echo "Install with:"
        echo "  cargo install mdbook"
        echo "  cargo install mdbook-toc        # Table of contents preprocessor"
        echo "  cargo install mdbook-mermaid    # Mermaid diagrams support"
        echo "  cargo install mdbook-linkcheck  # Link validation"
        exit 1
    fi

# Initialize new mdbook project (only if doesn't exist)
@book-init:
    #!/usr/bin/env bash
    if [ ! -f "{{mdbook_dir}}/book.toml" ]; then
        echo "📚 Initializing mdbook in {{mdbook_dir}}..."
        cd {{provisioning_root}} && mdbook init docs --title "Provisioning Platform Documentation" --ignore git
        echo "✅ MDBook initialized successfully"
        echo ""
        echo "Next steps:"
        echo "  1. Edit {{mdbook_dir}}/book.toml to configure"
        echo "  2. Edit {{mdbook_dir}}/src/SUMMARY.md to structure content"
        echo "  3. Run 'just book-serve' to preview"
    else
        echo "ℹ️  MDBook already initialized in {{mdbook_dir}}"
        echo "   Use 'just book-build' or 'just book-serve'"
    fi

# Install mdbook and useful plugins
@book-install:
    #!/usr/bin/env bash
    echo "📦 Installing mdbook and plugins..."

    cargo install mdbook
    cargo install mdbook-toc
    cargo install mdbook-mermaid
    cargo install mdbook-linkcheck

    echo "✅ MDBook and plugins installed successfully"
    echo ""
    mdbook --version

# ============================================================================
# Build & Serve
# ============================================================================

# Build mdbook documentation
@book-build:
    echo "📖 Building mdbook documentation..."
    cd {{mdbook_dir}} && mdbook build
    echo "✅ MDBook built successfully"
    echo "   Output: {{mdbook_build}}/index.html"
    echo ""
    echo "💡 Open in browser: open {{mdbook_build}}/index.html"

# Serve mdbook with live reload (watch mode)
@book-serve PORT="3000":
    echo "🌐 Serving mdbook documentation on http://localhost:{{PORT}}"
    echo "📝 Watching for changes in {{mdbook_src}}..."
    echo "🔄 Auto-reload enabled - edit files and see changes live"
    echo ""
    echo "Press Ctrl+C to stop"
    cd {{mdbook_dir}} && mdbook serve --port {{PORT}} --open

# Watch and rebuild on changes (alternative to serve)
@book-watch:
    echo "👁️  Watching mdbook source for changes..."
    echo "📝 Files: {{mdbook_src}}/"
    echo ""
    cd {{mdbook_dir}} && mdbook watch

# Open mdbook in browser
@book-open:
    #!/usr/bin/env bash
    if [ -f "{{mdbook_build}}/index.html" ]; then
        echo "🌐 Opening mdbook in browser..."
        open {{mdbook_build}}/index.html || xdg-open {{mdbook_build}}/index.html
    else
        echo "❌ Build not found. Run 'just book-build' first."
        exit 1
    fi

# ============================================================================
# Testing & Validation
# ============================================================================

# Test mdbook (validate links and structure)
@book-test:
    #!/usr/bin/env bash
    echo "🧪 Testing mdbook documentation..."

    # Test build
    echo "1️⃣  Testing build..."
    cd {{mdbook_dir}} && mdbook build

    # Validate links if mdbook-linkcheck is installed
    if command -v mdbook-linkcheck >/dev/null 2>&1; then
        echo "2️⃣  Validating internal links..."
        cd {{mdbook_dir}} && mdbook test
    else
        echo "⚠️  mdbook-linkcheck not installed, skipping link validation"
        echo "   Install with: cargo install mdbook-linkcheck"
    fi

    # Check SUMMARY.md structure
    echo "3️⃣  Checking SUMMARY.md structure..."
    if [ -f "{{mdbook_src}}/SUMMARY.md" ]; then
        echo "   ✅ SUMMARY.md exists"
    else
        echo "   ❌ SUMMARY.md not found"
        exit 1
    fi

    echo "✅ MDBook tests passed"

# Show mdbook statistics
@book-stats:
    #!/usr/bin/env bash
    echo "📊 MDBook Statistics"
    echo "===================="

    if [ -d "{{mdbook_src}}" ]; then
        echo "Source directory: {{mdbook_src}}"
        echo ""
        echo "Content:"
        echo "  Markdown files: $(find {{mdbook_src}} -name "*.md" | wc -l | xargs)"
        echo "  Images: $(find {{mdbook_src}} -name "*.png" -o -name "*.jpg" -o -name "*.svg" | wc -l | xargs)"
        echo "  Total size: $(du -sh {{mdbook_src}} | cut -f1)"
        echo ""

        if [ -d "{{mdbook_build}}" ]; then
            echo "Built documentation:"
            echo "  HTML files: $(find {{mdbook_build}} -name "*.html" | wc -l | xargs)"
            echo "  Build size: $(du -sh {{mdbook_build}} | cut -f1)"
        else
            echo "⚠️  No build found. Run 'just book-build' first."
        fi
    else
        echo "⚠️  MDBook not initialized. Run 'just book-init' first."
    fi

# ============================================================================
# Deployment & Cleanup
# ============================================================================

# Deploy mdbook (prepare for GitHub Pages or hosting)
@book-deploy:
    #!/usr/bin/env bash
    echo "🚀 Preparing mdbook for deployment..."

    # Clean and build
    just book-clean
    just book-build

    # Create deployment directory
    DEPLOY_DIR="{{dist_dir}}/mdbook-deploy"
    mkdir -p "$DEPLOY_DIR"

    # Copy built book
    cp -r {{mdbook_build}}/* "$DEPLOY_DIR/"

    # Create .nojekyll for GitHub Pages
    touch "$DEPLOY_DIR/.nojekyll"

    # Create CNAME if needed (uncomment and set your domain)
    # echo "docs.yourproject.com" > "$DEPLOY_DIR/CNAME"

    echo "✅ MDBook deployment prepared in $DEPLOY_DIR"
    echo ""
    echo "📋 Deployment options:"
    echo "  • GitHub Pages: Push $DEPLOY_DIR/* to gh-pages branch"
    echo "  • Netlify: Drag $DEPLOY_DIR folder to netlify.com/drop"
    echo "  • Custom server: rsync $DEPLOY_DIR/* to your server"

# Clean mdbook build artifacts
@book-clean:
    echo "🧹 Cleaning mdbook build artifacts..."
    rm -rf {{mdbook_build}}
    echo "✅ MDBook artifacts cleaned"

# ============================================================================
# Workflows
# ============================================================================

# Complete mdbook workflow (build, test, stats)
@book-all: book-build book-test book-stats
    echo "✅ Complete mdbook workflow finished"
