#include "cgi.h"
#include "form.h"
#include "html.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_ITEMS 32
#define MAX_POST 8192

static char *local_strdup(const char *s) {
    size_t len = strlen(s);
    char *copy = malloc(len + 1);
    if (copy == NULL) {
        return NULL;
    }
    memcpy(copy, s, len + 1);
    return copy;
}

int main(void) {
    FormItem items[MAX_ITEMS];
    char *input = NULL;
    char *owned = NULL;
    int count = 0;
    const char *method = getenv("REQUEST_METHOD");

    if (method != NULL && strcmp(method, "POST") == 0) {
        if (!cgi_read_post_body(&owned, MAX_POST)) {
            cgi_status_header("400 Bad Request", "text/plain");
            printf("invalid post body\n");
            return 0;
        }
        input = owned;
    } else {
        const char *query = getenv("QUERY_STRING");
        owned = query != NULL ? local_strdup(query) : local_strdup("");
        if (owned == NULL) {
            cgi_status_header("500 Internal Server Error", "text/plain");
            return 1;
        }
        input = owned;
    }

    count = form_parse(input, items, MAX_ITEMS);

    cgi_header("text/html");
    printf("<!DOCTYPE html><html lang=\"ja\"><body>\n");
    printf("<h1>Form Echo</h1>\n");
    printf("<dl>\n");
    for (int i = 0; i < count; i++) {
        printf("<dt>");
        html_escape_print(stdout, items[i].key);
        printf("</dt><dd>");
        html_escape_print(stdout, items[i].value);
        printf("</dd>\n");
    }
    printf("</dl>\n");
    printf("</body></html>\n");

    form_free(items, count);
    free(owned);
    return 0;
}
