/* Internal Bio-Digital runtime contracts. */
#ifndef BIO_INTERNAL_H_
#define BIO_INTERNAL_H_

#include <stdbool.h>
#include <stdio.h>

#include "bio/bio.h"
#include "bio/bio_gguf.h"
#include "bio/bio_opcode.h"
#include "bio_kernel.h"

#define BIO_PULSE_SCRATCH_BYTES (BIO_ROUTE_MAX_BLOCKS * BIO_ROUTE_DEFAULT_BLOCK_BYTES)
#define BIO_DELTA_LATTICE_BYTES BIO_PULSE_SCRATCH_BYTES
#define BIO_KV_CACHE_BYTES 65536u
#define BIO_CHAT_MAX_TOKENS 256u

typedef struct bio_cache_arena {
    uint8_t kv[BIO_KV_CACHE_BYTES];
    uint64_t requested_kv_bytes;
    uint64_t requested_route_bytes;
    uint64_t requested_delta_bytes;
    size_t kv_used;
} bio_cache_arena;

typedef struct bio_learn_state {
    int8_t delta[BIO_DELTA_LATTICE_BYTES];
    uint8_t active;
    uint64_t steps;
    uint64_t committed_dry_runs;
    int8_t clamp;
} bio_learn_state;

typedef struct bio_chat_state {
    uint64_t prompt_hash;
    uint64_t generated_tokens;
    uint32_t last_token;
} bio_chat_state;

typedef struct bio_context {
    FILE *event_sink;
    uint64_t dispatched_ops;
    bio_gguf_model model;
    bio_sparse_masks masks;
    bio_cache_arena arenas;
    bio_learn_state learn;
    bio_chat_state chat;
    uint8_t pulse_state[BIO_PULSE_SCRATCH_BYTES];
    uint8_t pulse_initialized;
    bool model_loaded;
    bool halted;
} bio_context;

typedef bio_v1_status (*bio_op_fn)(bio_context *ctx, const bio_operands *ops);

typedef struct bio_dispatch_entry {
    bio_opcode opcode;
    const char *name;
    bio_op_fn fn;
} bio_dispatch_entry;

extern const bio_dispatch_entry g_bio_dispatch[BIO_OPCODE_COUNT];

bio_v1_status bio_run_file_with_context(bio_context *ctx, const char *path);
const char *bio_operand_value(const bio_operands *ops, const char *key);
void bio_context_close(bio_context *ctx);

bio_v1_status bio_op_absorb_gguf(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_manifold_addr(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_pulse(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_prune(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_zpm_skip(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_omega_route(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_learn_cycle(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_infer_chat(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_delta_commit(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_cache_bind(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_sync_fence(bio_context *ctx, const bio_operands *ops);
bio_v1_status bio_op_halt(bio_context *ctx, const bio_operands *ops);

#endif /* BIO_INTERNAL_H_ */
