#include "WebServer.hpp"
#include "../SdCard.hpp"
#include "esp_log.h"
#include <cstring>

static const char* TAG = "WebServer";

esp_err_t WebServer::rootHandler(httpd_req_t* req) {
    if (!SdCard::instance().isMounted()) {
        httpd_resp_set_type(req, "text/html; charset=utf-8");
        const char* errorPage = "<!DOCTYPE html><html><body><h1>SD Card Error</h1>"
            "<p>SD card not mounted. Please insert SD card with /webseite/index.html</p>"
            "<p><a href=\"/files\">Open File Manager</a></p></body></html>";
        httpd_resp_send(req, errorPage, strlen(errorPage));
        return ESP_OK;
    }

    return sendFile(req, "/sdcard/webseite/index.html");
}

esp_err_t WebServer::staticFileHandler(httpd_req_t* req) {
    char filepath[CONFIG_HTTPD_MAX_URI_LEN + 8];
    snprintf(filepath, sizeof(filepath), "/sdcard%.*s",
             (int)(sizeof(filepath) - 8), req->uri);

    return sendFile(req, filepath);
}

esp_err_t WebServer::imagesHandler(httpd_req_t* req) {
    char filepath[CONFIG_HTTPD_MAX_URI_LEN + 8];
    snprintf(filepath, sizeof(filepath), "/sdcard%.*s",
             (int)(sizeof(filepath) - 8), req->uri);

    // Try lowercase first
    esp_err_t result = sendFile(req, filepath);
    if (result != ESP_OK) {
        // Try uppercase IMAGES folder as fallback
        char altpath[CONFIG_HTTPD_MAX_URI_LEN + 8];
        snprintf(altpath, sizeof(altpath), "/sdcard/IMAGES%s",
                 req->uri + 7);  // Skip "/images"
        result = sendFile(req, altpath);
    }
    return result;
}
