// Admin interface handler - serves embedded web UI files
#include <stdio.h>
#include <string.h>
#include "ginxsom.h"
#include "admin_interface_embedded.h"

/**
 * Serve embedded file with appropriate content type
 */
static void serve_embedded_file(const unsigned char* data, size_t size, const char* content_type) {
    printf("Status: 200 OK\r\n");
    printf("Content-Type: %s\r\n", content_type);
    printf("Content-Length: %lu\r\n", (unsigned long)size);
    printf("Cache-Control: public, max-age=3600\r\n");
    printf("\r\n");
    fwrite((void*)data, 1, size, stdout);
    fflush(stdout);
}

/**
 * Handle admin interface requests
 * Serves embedded web UI files from /api path (consistent with c-relay)
 */
void handle_admin_interface_request(const char* path) {
    // Normalize path - remove trailing slash
    char normalized_path[256];
    strncpy(normalized_path, path, sizeof(normalized_path) - 1);
    normalized_path[sizeof(normalized_path) - 1] = '\0';
    
    size_t len = strlen(normalized_path);
    if (len > 1 && normalized_path[len - 1] == '/') {
        normalized_path[len - 1] = '\0';
    }
    
    // Route to appropriate embedded file
    // All paths use /api/ prefix for consistency with c-relay
    if (strcmp(normalized_path, "/api") == 0 || strcmp(normalized_path, "/api/index.html") == 0) {
        serve_embedded_file(embedded_index_html, embedded_index_html_size, "text/html; charset=utf-8");
    }
    else if (strcmp(normalized_path, "/api/index.css") == 0) {
        serve_embedded_file(embedded_index_css, embedded_index_css_size, "text/css; charset=utf-8");
    }
    else if (strcmp(normalized_path, "/api/index.js") == 0) {
        serve_embedded_file(embedded_index_js, embedded_index_js_size, "application/javascript; charset=utf-8");
    }
    else if (strcmp(normalized_path, "/api/nostr-lite.js") == 0) {
        serve_embedded_file(embedded_nostr_lite_js, embedded_nostr_lite_js_size, "application/javascript; charset=utf-8");
    }
    else if (strcmp(normalized_path, "/api/nostr.bundle.js") == 0) {
        serve_embedded_file(embedded_nostr_bundle_js, embedded_nostr_bundle_js_size, "application/javascript; charset=utf-8");
    }
    else if (strcmp(normalized_path, "/api/text_graph.js") == 0) {
        serve_embedded_file(embedded_text_graph_js, embedded_text_graph_js_size, "application/javascript; charset=utf-8");
    }
    else {
        // 404 Not Found
        printf("Status: 404 Not Found\r\n");
        printf("Content-Type: text/html; charset=utf-8\r\n");
        printf("\r\n");
        printf("<html><body><h1>404 Not Found</h1><p>File not found: %s</p></body></html>\n", normalized_path);
    }
}