#!/bin/bash

# Script to inject navigation into HTML reports
# Usage: ./inject_navigation.sh <html_file> <spacemake_dir>

HTML_FILE="$1"
SPACEMAKE_DIR="$2"

if [ ! -f "$HTML_FILE" ]; then
    echo "Error: HTML file not found: $HTML_FILE"
    exit 1
fi

if [ ! -d "$SPACEMAKE_DIR" ]; then
    echo "Error: Spacemake directory not found: $SPACEMAKE_DIR"
    exit 1
fi

CSS_FILE="$SPACEMAKE_DIR/report/static/navigation.css"
JS_FILE="$SPACEMAKE_DIR/report/static/navigation.js"

if [ ! -f "$CSS_FILE" ]; then
    echo "Error: CSS file not found: $CSS_FILE"
    exit 1
fi

if [ ! -f "$JS_FILE" ]; then
    echo "Error: JavaScript file not found: $JS_FILE"
    exit 1
fi

# Create backup
cp "$HTML_FILE" "$HTML_FILE.backup"

# Create temporary output file
TEMP_OUTPUT=$(mktemp)

# Use Python to safely inject the content
python3 -c "
import sys

# Read the HTML file
with open('$HTML_FILE', 'r', encoding='utf-8') as f:
    html_content = f.read()

# Read CSS file
with open('$CSS_FILE', 'r', encoding='utf-8') as f:
    css_content = f.read()

# Read JS file
with open('$JS_FILE', 'r', encoding='utf-8') as f:
    js_content = f.read()

# Create the navigation HTML
nav_html = '''<button class=\"mobile-nav-toggle\" onclick=\"toggleSidebar()\">☰</button>

<div class=\"nav-sidebar\" id=\"navSidebar\">
    <h4>Navigation</h4>
    <div id=\"navItems\">
        <!-- Navigation items will be generated by JavaScript -->
    </div>
</div>

<script>
''' + js_content + '''
</script>'''

# Inject CSS before </head>
css_injection = '<style>' + chr(10) + css_content + chr(10) + '</style>'
html_content = html_content.replace('</head>', css_injection + chr(10) + '</head>')

# Inject navigation HTML and JS before </body>
html_content = html_content.replace('</body>', nav_html + chr(10) + '</body>')

# Write the result
with open('$TEMP_OUTPUT', 'w', encoding='utf-8') as f:
    f.write(html_content)
"

# Check if Python script succeeded
if [ $? -eq 0 ]; then
    mv "$TEMP_OUTPUT" "$HTML_FILE"
    rm -f "$HTML_FILE.backup"
    echo "Navigation injected successfully into $HTML_FILE"
else
    echo "Error: Failed to inject navigation. Restoring backup."
    mv "$HTML_FILE.backup" "$HTML_FILE"
    rm -f "$TEMP_OUTPUT"
    exit 1
fi