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

#include "bio_internal.h"

static int g_bio_initialized = 0;

bio_v1_status bio_v1_init(void) {
    bio_runtime_detect_features();
    bio_runtime_bind_kernels();
    g_bio_initialized = 1;
    return BIO_OK;
}

const char *bio_v1_version(void) {
    return BIO_VERSION_STRING;
}

const char *bio_v1_active_variant(const char *kernel_name) {
    if (kernel_name == NULL) {
        return "unknown";
    }
    if (strcmp(kernel_name, "opcode_dispatch") == 0) {
        return "direct_function_pointer";
    }
    if (strcmp(kernel_name, "pulse") == 0) {
        return g_bio_kernels.pulse_variant;
    }
    if (strcmp(kernel_name, "gguf") == 0) {
        return "native_mmap";
    }
    if (strcmp(kernel_name, "learn") == 0) {
        return "sidecar_delta_phase4";
    }
    if (strcmp(kernel_name, "chat") == 0) {
        return "native_control_loop_phase4";
    }
    return "native_stub";
}

bio_v1_status bio_v1_absorb_gguf(const char *path) {
    bio_gguf_model model;
    const bio_v1_status rc = bio_gguf_open(path, &model);
    if (rc == BIO_OK) {
        bio_gguf_close(&model);
    }
    return rc;
}

bio_v1_status bio_v1_run_file(const char *path) {
    bio_context *ctx = NULL;
    bio_v1_status rc = BIO_OK;
    if (!g_bio_initialized) {
        rc = bio_v1_init();
        if (rc != BIO_OK) {
            return rc;
        }
    }

    ctx = (bio_context *)calloc(1u, sizeof(*ctx));
    if (ctx == NULL) {
        return BIO_ERR_INTERNAL;
    }
    rc = bio_run_file_with_context(ctx, path);
    bio_context_close(ctx);
    free(ctx);
    return rc;
}
