#include "crow.h"
#include "routes.h"
#include <fstream>
#include <sstream>

namespace routes {

namespace {

std::string read_file(const std::string& path) {
    std::ifstream ifs(path);
    if (!ifs.is_open()) return "";
    std::ostringstream ss;
    ss << ifs.rdbuf();
    return ss.str();
}

} // anonymous namespace

void register_pages(crow::SimpleApp& app) {

    // Home page — serves static HTML
    CROW_ROUTE(app, "/")
    ([]() {
        std::string html = read_file("static/index.html");
        if (html.empty()) {
            return crow::response(500, "index.html not found");
        }
        auto resp = crow::response(html);
        resp.add_header("Content-Type", "text/html; charset=utf-8");
        return resp;
    });

    // Static file serving for CSS, JS, images
    CROW_ROUTE(app, "/static/<path>")
    ([](const std::string& path) {
        std::string full_path = "static/" + path;
        std::string content = read_file(full_path);
        if (content.empty()) {
            return crow::response(404);
        }

        auto resp = crow::response(content);

        // Set content type based on extension
        if (path.ends_with(".css"))       resp.add_header("Content-Type", "text/css");
        else if (path.ends_with(".js"))   resp.add_header("Content-Type", "application/javascript");
        else if (path.ends_with(".html")) resp.add_header("Content-Type", "text/html");
        else if (path.ends_with(".json")) resp.add_header("Content-Type", "application/json");
        else if (path.ends_with(".png"))  resp.add_header("Content-Type", "image/png");
        else if (path.ends_with(".svg"))  resp.add_header("Content-Type", "image/svg+xml");
        else                              resp.add_header("Content-Type", "application/octet-stream");

        return resp;
    });
}

} // namespace routes
