#!/bin/bash
# Embed web interface files into C source code
# This script converts HTML, CSS, and JS files into C byte arrays

set -e

# Configuration
API_DIR="api"
OUTPUT_DIR="src"
OUTPUT_FILE="${OUTPUT_DIR}/admin_interface_embedded.h"

# Files to embed
FILES=(
    "index.html"
    "index.css"
    "index.js"
    "nostr-lite.js"
    "nostr.bundle.js"
    "text_graph.js"
)

echo "=== Embedding Web Interface Files ==="
echo "Source directory: ${API_DIR}"
echo "Output file: ${OUTPUT_FILE}"
echo ""

# Start output file
cat > "${OUTPUT_FILE}" << 'EOF'
/*
 * Embedded Web Interface Files
 * Auto-generated by scripts/embed_web_files.sh
 * DO NOT EDIT MANUALLY
 */

#ifndef ADMIN_INTERFACE_EMBEDDED_H
#define ADMIN_INTERFACE_EMBEDDED_H

#include <stddef.h>

EOF

# Process each file
for file in "${FILES[@]}"; do
    filepath="${API_DIR}/${file}"
    
    if [[ ! -f "${filepath}" ]]; then
        echo "WARNING: File not found: ${filepath}"
        continue
    fi
    
    # Create variable name from filename (replace . and - with _)
    varname=$(echo "${file}" | tr '.-' '__')
    
    echo "Embedding: ${file} -> embedded_${varname}"
    
    # Get file size
    filesize=$(stat -f%z "${filepath}" 2>/dev/null || stat -c%s "${filepath}" 2>/dev/null)
    
    # Add comment
    echo "" >> "${OUTPUT_FILE}"
    echo "// Embedded file: ${file} (${filesize} bytes)" >> "${OUTPUT_FILE}"
    
    # Convert file to C byte array
    echo "static const unsigned char embedded_${varname}[] = {" >> "${OUTPUT_FILE}"
    
    # Use xxd to convert to hex, then format as C array
    xxd -i < "${filepath}" >> "${OUTPUT_FILE}"
    
    echo "};" >> "${OUTPUT_FILE}"
    echo "static const size_t embedded_${varname}_size = sizeof(embedded_${varname});" >> "${OUTPUT_FILE}"
done

# Close header guard
cat >> "${OUTPUT_FILE}" << 'EOF'

#endif /* ADMIN_INTERFACE_EMBEDDED_H */
EOF

echo ""
echo "=== Embedding Complete ==="
echo "Generated: ${OUTPUT_FILE}"
echo "Total files embedded: ${#FILES[@]}"