/* Common C reference declarations; concatenated before the page extension. */
#include <maelys/datalog.h>
#include <maelys/datalog_builders.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

/* The page extension owns cleanup; no constructor is hidden in the runner. */
static void cleanup_context(void);
static int cleanup_failed = 0;

static void check_status(maelys_datalog_status_t status) {
    if (status != MAELYS_DATALOG_STATUS_OK) {
        fprintf(stderr, "API call failed: %s\n", maelys_datalog_status_name(status));
        exit(EXIT_FAILURE);
    }
}

/* Label each output line without changing the text buffer. */
static void print_text_lines(const char *label, const char *text) {
    while (*text != '\0') {
        const char *end = strchr(text, '\n');
        printf("%s: ", label);
        fwrite(text, 1, end ? (size_t)(end - text) : strlen(text), stdout);
        putchar('\n');
        if (end == NULL) break;
        text = end + 1;
    }
}

/* Cleanup failures must not recursively invoke check_status. */
static void cleanup_status(maelys_datalog_status_t status) {
    if (status != MAELYS_DATALOG_STATUS_OK) {
        cleanup_failed = 1;
        fprintf(stderr, "Context cleanup failed: %s\n", maelys_datalog_status_name(status));
    }
}
