#include <stdint.h>
#include <stdlib.h>
#include "el_runtime.h"

el_val_t imprint_current(void);
el_val_t imprint_load(el_val_t imprint_id);
el_val_t imprint_respond(el_val_t input, el_val_t imprint_id);
el_val_t imprint_surface_knowledge(el_val_t query, el_val_t imprint_id);
el_val_t imprint_surface_memory_read(el_val_t query);
el_val_t imprint_unload(void);

el_val_t imprint_current(void) {
  el_val_t id = state_get(EL_STR("active_imprint_id"));
  return ({ el_val_t _if_result_1 = 0; if (str_eq(id, EL_STR(""))) { _if_result_1 = (EL_STR("base")); } else { _if_result_1 = (id); } _if_result_1; });
  return 0;
}

el_val_t imprint_load(el_val_t imprint_id) {
  el_val_t label = el_str_concat(EL_STR("imprint:"), imprint_id);
  el_val_t results = engram_search_json(label, 1);
  if (str_eq(results, EL_STR(""))) {
    return el_str_concat(el_str_concat(EL_STR("{\"ok\":false,\"error\":\"imprint not found: "), imprint_id), EL_STR("\"}"));
  }
  if (str_eq(results, EL_STR("[]"))) {
    return el_str_concat(el_str_concat(EL_STR("{\"ok\":false,\"error\":\"imprint not found: "), imprint_id), EL_STR("\"}"));
  }
  el_val_t found_label = json_get(results, EL_STR("label"));
  if (str_eq(found_label, label)) {
    state_set(EL_STR("active_imprint_id"), imprint_id);
    return el_str_concat(el_str_concat(EL_STR("{\"ok\":true,\"id\":\""), imprint_id), EL_STR("\"}"));
  }
  return el_str_concat(el_str_concat(EL_STR("{\"ok\":false,\"error\":\"imprint not found: "), imprint_id), EL_STR("\"}"));
  return 0;
}

el_val_t imprint_respond(el_val_t input, el_val_t imprint_id) {
  if (str_eq(imprint_id, EL_STR("base"))) {
    return input;
  }
  if (str_eq(imprint_id, EL_STR(""))) {
    return input;
  }
  el_val_t current = imprint_current();
  if (str_eq(current, imprint_id)) {
    return el_str_concat(el_str_concat(el_str_concat(input, EL_STR(" [imprint:")), imprint_id), EL_STR(" active]"));
  }
  return input;
  return 0;
}

el_val_t imprint_surface_knowledge(el_val_t query, el_val_t imprint_id) {
  if (str_eq(imprint_id, EL_STR("base"))) {
    return engram_search_json(query, 10);
  }
  if (str_eq(imprint_id, EL_STR(""))) {
    return engram_search_json(query, 10);
  }
  el_val_t scoped_query = el_str_concat(el_str_concat(query, EL_STR(" domain:")), imprint_id);
  return engram_search_json(scoped_query, 10);
  return 0;
}

el_val_t imprint_surface_memory_read(el_val_t query) {
  return engram_search_json(query, 10);
  return 0;
}

el_val_t imprint_unload(void) {
  state_set(EL_STR("active_imprint_id"), EL_STR(""));
  return 0;
}

