#!/bin/bash

# Documentation Enhancement Script for Rustelo
# This script adds logos and branding to cargo doc output

exit
# TODO: Requir fix positioning in pages and ensure proper alignment

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
LOGO_DIR="logos"
DOC_DIR="target/doc"
LOGO_FILE="rustelo-imag.svg"
LOGO_HORIZONTAL="rustelo_dev-logo-h.svg"

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if cargo doc has been run
check_doc_exists() {
    if [ ! -d "$DOC_DIR" ]; then
        print_error "Documentation directory not found. Run 'cargo doc' first."
        exit 1
    fi
}

# Check if logos exist
check_logos_exist() {
    if [ ! -f "$LOGO_DIR/$LOGO_FILE" ]; then
        print_error "Logo file not found: $LOGO_DIR/$LOGO_FILE"
        exit 1
    fi

    if [ ! -f "$LOGO_DIR/$LOGO_HORIZONTAL" ]; then
        print_error "Horizontal logo file not found: $LOGO_DIR/$LOGO_HORIZONTAL"
        exit 1
    fi
}

# Copy logos to doc directory
copy_logos_to_doc() {
    print_status "Copying logos to documentation directory..."

    # Create logos directory in doc
    mkdir -p "$DOC_DIR/logos"

    # Copy all logo files
    cp "$LOGO_DIR"/*.svg "$DOC_DIR/logos/"

    print_status "Logos copied successfully"
}

# Add logo to main crate page
enhance_main_page() {
    local crate_name="$1"
    local index_file="$DOC_DIR/$crate_name/index.html"

    if [ ! -f "$index_file" ]; then
        print_warning "Index file not found for crate: $crate_name"
        return
    fi

    print_status "Enhancing main page for crate: $crate_name"

    # Create a backup
    cp "$index_file" "$index_file.backup"

    # Add logo to the main heading
    sed -i.tmp 's|<h1>Crate <span>'"$crate_name"'</span>|<div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;"><img src="../logos/'"$LOGO_FILE"'" alt="RUSTELO" style="height: 2rem; width: auto;"/><h1>Crate <span>'"$crate_name"'</span></h1></div>|g' "$index_file"

    # Create temporary CSS file
    cat > "/tmp/rustelo-css.tmp" << 'EOF'
<style>
.rustelo-logo { height: 2rem; width: auto; margin-right: 0.5rem; }
.rustelo-brand { display: flex; align-items: center; gap: 0.5rem; }
.main-heading { margin-bottom: 2rem; }
.rustelo-footer {
    margin-top: 2rem;
    padding-top: 1rem;
    border-top: 1px solid #ddd;
    text-align: center;
    color: #666;
    font-size: 0.9rem;
}
</style></head>
EOF

    # Add custom CSS for logo styling
    sed -i.tmp -e '/^[[:space:]]*<\/head>/{
        r /tmp/rustelo-css.tmp
        d
    }' "$index_file"

    # Create temporary footer file
    cat > "/tmp/rustelo-footer.tmp" << 'EOF'
<div class="rustelo-footer">
        <p>Generated with <strong>RUSTELO</strong> - Modular Rust Web Application Template</p>
        <p><a href="https://github.com/yourusername/rustelo" target="_blank">Documentation</a> | <a href="https://rustelo.dev" target="_blank">Website</a></p>
    </div></main>
EOF

    # Add footer with branding
    sed -i.tmp -e '/^[[:space:]]*<\/main>/{
        r /tmp/rustelo-footer.tmp
        d
    }' "$index_file"

    # Clean up temporary files
    rm -f "/tmp/rustelo-css.tmp" "/tmp/rustelo-footer.tmp"

    # Clean up temporary files
    rm -f "$index_file.tmp"

    print_status "Enhanced main page for: $crate_name"
}

# Add logo to all module pages
enhance_module_pages() {
    local crate_name="$1"
    local crate_dir="$DOC_DIR/$crate_name"

    if [ ! -d "$crate_dir" ]; then
        print_warning "Crate directory not found: $crate_name"
        return
    fi

    print_status "Enhancing module pages for crate: $crate_name"

    # Find all HTML files in the crate directory
    find "$crate_dir" -name "*.html" -type f | while read -r html_file; do
        # Skip if it's the main index file (already processed)
        if [[ "$html_file" == "$crate_dir/index.html" ]]; then
            continue
        fi

        # Create backup
        cp "$html_file" "$html_file.backup"

        # Add logo to sidebar
        sed -i.tmp 's|<div class="sidebar-crate">|<div class="sidebar-crate"><div class="rustelo-brand" style="margin-bottom: 0.5rem;"><img src="../logos/'"$LOGO_FILE"'" alt="RUSTELO" class="rustelo-logo"/></div>|g' "$html_file"

        # Add custom CSS if not already present
        if ! grep -q "rustelo-logo" "$html_file"; then
            # Create temporary CSS file
            cat > "/tmp/rustelo-module-css.tmp" << 'EOF'
<style>
.rustelo-logo { height: 1.5rem; width: auto; }
.rustelo-brand { display: flex; align-items: center; gap: 0.5rem; }
</style></head>
EOF

            # Add CSS using file replacement
            sed -i.tmp -e '/^[[:space:]]*<\/head>/{
                r /tmp/rustelo-module-css.tmp
                d
            }' "$html_file"

            # Clean up temporary file
            rm -f "/tmp/rustelo-module-css.tmp"
        fi

        # Clean up temporary files
        rm -f "$html_file.tmp"
    done

    print_status "Enhanced module pages for: $crate_name"
}

# Add logo to the main documentation index
enhance_doc_index() {
    local doc_index="$DOC_DIR/index.html"

    if [ ! -f "$doc_index" ]; then
        print_warning "Main documentation index not found"
        return
    fi

    print_status "Enhancing main documentation index"

    # Create backup
    cp "$doc_index" "$doc_index.backup"

    # Add logo to the main page
    sed -i.tmp 's|<body|<body style="background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);"' "$doc_index"

    # Create temporary header file
    cat > "/tmp/rustelo-header.tmp" << 'EOF'
<div style="text-align: center; padding: 2rem; background: white; margin: 2rem; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);"><img src="logos/LOGO_HORIZONTAL_PLACEHOLDER" alt="RUSTELO" style="max-width: 300px; height: auto; margin-bottom: 1rem;"/><h1 style="color: #333; margin-bottom: 0.5rem;">RUSTELO Documentation</h1><p style="color: #666; font-size: 1.1rem;">Modular Rust Web Application Template</p></div>
EOF

    # Replace placeholder with actual logo file
    sed -i.tmp 's|LOGO_HORIZONTAL_PLACEHOLDER|'"$LOGO_HORIZONTAL"'|g' "/tmp/rustelo-header.tmp"

    # Add header with logo after body tag
    sed -i.tmp -e '/<body[^>]*>/{
        r /tmp/rustelo-header.tmp
    }' "$doc_index"

    # Clean up temporary file
    rm -f "/tmp/rustelo-header.tmp"

    # Clean up temporary files
    rm -f "$doc_index.tmp"

    print_status "Enhanced main documentation index"
}

# Create a custom CSS file for documentation
create_custom_css() {
    local css_file="$DOC_DIR/rustelo-custom.css"

    print_status "Creating custom CSS for documentation"

    cat > "$css_file" << 'EOF'
/* Rustelo Documentation Custom Styles */

:root {
    --rustelo-primary: #e53e3e;
    --rustelo-secondary: #3182ce;
    --rustelo-accent: #38a169;
    --rustelo-dark: #2d3748;
    --rustelo-light: #f7fafc;
}

.rustelo-logo {
    height: 1.5rem;
    width: auto;
    vertical-align: middle;
}

.rustelo-brand {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.rustelo-header {
    text-align: center;
    padding: 2rem;
    background: linear-gradient(135deg, var(--rustelo-primary), var(--rustelo-secondary));
    color: white;
    margin-bottom: 2rem;
    border-radius: 8px;
}

.rustelo-header img {
    max-width: 300px;
    height: auto;
    margin-bottom: 1rem;
    filter: brightness(0) invert(1);
}

.rustelo-footer {
    margin-top: 2rem;
    padding-top: 1rem;
    border-top: 1px solid #ddd;
    text-align: center;
    color: #666;
    font-size: 0.9rem;
}

.rustelo-footer a {
    color: var(--rustelo-primary);
    text-decoration: none;
}

.rustelo-footer a:hover {
    text-decoration: underline;
}

/* Improve code blocks */
.rustdoc .example-wrap {
    border-left: 4px solid var(--rustelo-primary);
}

/* Style the main heading */
.main-heading {
    border-bottom: 2px solid var(--rustelo-primary);
    padding-bottom: 1rem;
    margin-bottom: 2rem;
}

/* Enhance navigation */
.sidebar-crate h2 a {
    color: var(--rustelo-primary);
}

/* Responsive design */
@media (max-width: 768px) {
    .rustelo-header {
        padding: 1rem;
    }

    .rustelo-header img {
        max-width: 200px;
    }

    .rustelo-logo {
        height: 1rem;
    }
}
EOF

    print_status "Created custom CSS file"
}

# Main function
main() {
    print_status "Starting documentation enhancement for Rustelo"

    # Check prerequisites
    check_doc_exists
    check_logos_exist

    # Copy logos to documentation directory
    copy_logos_to_doc

    # Create custom CSS
    create_custom_css

    # Enhance main documentation index if it exists
    enhance_doc_index

    # Enhance individual crate documentation
    for crate_dir in "$DOC_DIR"/*; do
        if [ -d "$crate_dir" ] && [ -f "$crate_dir/index.html" ]; then
            crate_name=$(basename "$crate_dir")

            # Skip common directories that aren't crates
            if [[ "$crate_name" == "static.files" || "$crate_name" == "src" || "$crate_name" == "logos" ]]; then
                continue
            fi

            enhance_main_page "$crate_name"
            enhance_module_pages "$crate_name"
        fi
    done

    print_status "Documentation enhancement completed successfully!"
    print_status "You can now view the enhanced documentation by opening: $DOC_DIR/index.html"
}

# Help function
show_help() {
    cat << EOF
Documentation Enhancement Script for Rustelo

USAGE:
    $0 [OPTIONS]

OPTIONS:
    -h, --help     Show this help message
    --clean        Clean up backup files
    --restore      Restore from backup files

EXAMPLES:
    $0              # Enhance documentation with logos
    $0 --clean      # Clean up backup files
    $0 --restore    # Restore original documentation

PREREQUISITES:
    - Run 'cargo doc' first to generate documentation
    - Ensure logo files exist in the 'logos' directory

DESCRIPTION:
    This script enhances the cargo doc output by adding Rustelo branding:
    - Adds logos to main pages and sidebars
    - Includes custom CSS for better styling
    - Adds footer with project links
    - Creates branded documentation index

EOF
}

# Clean up backup files
clean_backups() {
    print_status "Cleaning up backup files..."
    find "$DOC_DIR" -name "*.backup" -type f -delete
    print_status "Backup files cleaned up"
}

# Restore from backup files
restore_from_backup() {
    print_status "Restoring from backup files..."
    find "$DOC_DIR" -name "*.backup" -type f | while read -r backup_file; do
        original_file="${backup_file%.backup}"
        mv "$backup_file" "$original_file"
        print_status "Restored: $original_file"
    done
    print_status "Restoration completed"
}

# Parse command line arguments
case "${1:-}" in
    -h|--help)
        show_help
        exit 0
        ;;
    --clean)
        clean_backups
        exit 0
        ;;
    --restore)
        restore_from_backup
        exit 0
        ;;
    "")
        main
        ;;
    *)
        print_error "Unknown option: $1"
        show_help
        exit 1
        ;;
esac
