/*
 * kiran_ensemble_stdio.c
 *
 * C stdio bridge for the Kiran v0.7.0 ensemble inference engine.
 * Runs as a persistent process, reading 106 CSV features from stdin
 * and writing JSON results to stdout.
 *
 * Compiles with:
 *   gcc -O2 -o kiran_ensemble_stdio kiran_ensemble_stdio.c \
 *       kiran_ensemble_v070.c kiran_ensemble_v070_data.c -lm
 */

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

#include "kiran_ensemble_v070.h"

#define MAX_LINE 8192
#define MAX_FIELDS 256

static void json_escape(const char *s, char *out, size_t out_size) {
    size_t j = 0;
    for (size_t i = 0; s[i] != '\0' && j < out_size - 1; i++) {
        if (s[i] == '"' || s[i] == '\\') {
            if (j + 2 >= out_size) break;
            out[j++] = '\\';
            out[j++] = s[i];
        } else {
            out[j++] = s[i];
        }
    }
    out[j] = '\0';
}

int main(void) {
    KiranRollingBuffer buf;
    kiran_rolling_buffer_init(&buf);

    char line[MAX_LINE];

    while (1) {
        /* Read one line from stdin (blocking) */
        if (fgets(line, sizeof(line), stdin) == NULL) {
            /* EOF or read error */
            break;
        }

        /* Strip trailing newline/carriage return */
        size_t len = strlen(line);
        while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
            line[--len] = '\0';
        }

        /* Skip empty lines */
        if (len == 0) {
            continue;
        }

        /* Parse comma-separated float values */
        float features[KIRAN_N_BASE_FEATURES];
        for (int i = 0; i < KIRAN_N_BASE_FEATURES; i++) {
            features[i] = 0.0f;
        }

        char *saveptr = NULL;
        char *token = strtok_r(line, ",", &saveptr);
        int field_count = 0;

        while (token != NULL && field_count < MAX_FIELDS) {
            /* Skip whitespace */
            while (*token == ' ' || *token == '\t') token++;

            if (*token == '\0') {
                /* Empty field between commas -- treat as 0.0 */
                if (field_count < KIRAN_N_BASE_FEATURES) {
                    features[field_count] = 0.0f;
                }
                field_count++;
            } else {
                char *endptr = NULL;
                double val = strtod(token, &endptr);
                if (endptr != token && field_count < KIRAN_N_BASE_FEATURES) {
                    features[field_count] = (float)val;
                }
                field_count++;
            }

            token = strtok_r(NULL, ",", &saveptr);
        }

        /* If fewer than 106 values, remaining are already 0.0f (initialized above) */

        /* Call the ensemble predictor */
        KiranResult result = kiran_ensemble_predict(features, &buf);

        /* Write JSON result to stdout */
        printf(
            "{\"p_short\":%.4f,\"p_medium\":%.4f,\"p_long\":%.4f,"
            "\"p_ensemble\":%.4f,\"prediction\":%d}\n",
            result.p_short,
            result.p_medium,
            result.p_long,
            result.p_ensemble,
            result.prediction
        );

        /* Flush stdout after each response */
        fflush(stdout);
    }

    /* Clean exit on EOF or error */
    return 0;
}
