// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-or-later

/**
 * @file 08.Templating.ino
 * @brief Response templating with {{name}} placeholder substitution.
 *
 * send_template() streams a template, replacing each `{{name}}` token with the
 * value returned by a TemplateVar resolver (nullptr -> empty). The body is
 * walked twice (size, then write) so it is never buffered whole - memory use is
 * constant regardless of page size. Unknown / over-long / unterminated
 * placeholders are emitted literally.
 *
 * Flash, open Serial @ 115200 for the IP, then:
 *   curl http://<ip>/
 */

#include "dwserver.h"
#include "network_drivers/physical/physical.h"
#include <WiFi.h>

static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";

DetWebServer server;

static unsigned long hit_count = 0;

// Resolver: map a placeholder name to its replacement. Returned pointers must
// stay valid for the duration of the send_template() call; the resolver is
// invoked twice (sizing pass + write pass) so it must be deterministic.
static const char *resolver(const char *name)
{
    static char buf[32];
    if (strcmp(name, "title") == 0)
        return "Templating Demo";
    if (strcmp(name, "uptime") == 0)
    {
        snprintf(buf, sizeof(buf), "%lu", millis());
        return buf;
    }
    if (strcmp(name, "hits") == 0)
    {
        snprintf(buf, sizeof(buf), "%lu", hit_count);
        return buf;
    }
    if (strcmp(name, "heap") == 0)
    {
        snprintf(buf, sizeof(buf), "%u", ESP.getFreeHeap());
        return buf;
    }
    return nullptr; // unknown -> empty
}

// GET / - render an HTML page from a template.
void handle_root(uint8_t slot_id, HttpReq *req)
{
    (void)req;
    hit_count++;
    static const char page[] = "<!doctype html><html><body>"
                               "<h1>{{title}}</h1>"
                               "<p>uptime: {{uptime}} ms</p>"
                               "<p>hits: {{hits}}</p>"
                               "<p>free heap: {{heap}} bytes</p>"
                               "</body></html>";
    server.send_template(slot_id, 200, "text/html", page, resolver);
}

void setup()
{
    Serial.begin(115200);

    init_wifi_physical(SSID, PASSWORD);
    Serial.print("Connecting to WiFi");
    while (!wifi_ready())
    {
        delay(250);
        Serial.print('.');
    }
    Serial.print("\nIP: ");
    Serial.println(WiFi.localIP());

    WiFi.setSleep(false);

    server.on("/", HTTP_GET, handle_root);

    int32_t result = server.begin(80);
    if (result < 0)
    {
        Serial.printf("begin() failed (error %d)\n", result);
        return;
    }
    Serial.println("Server started on port 80");
}

void loop()
{
    server.handle();
}
