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

el_val_t sem_get(el_val_t json, el_val_t key);
el_val_t generate_frame(el_val_t frame);
el_val_t generate_frame_lang(el_val_t frame, el_val_t lang_code);
el_val_t build_form_from_json(el_val_t semantic_form_json, el_val_t lang_code);
el_val_t generate(el_val_t semantic_form_json);
el_val_t generate_lang(el_val_t semantic_form_json, el_val_t lang_code);
el_val_t tier_working(void);
el_val_t tier_episodic(void);
el_val_t tier_canonical(void);
el_val_t mem_store(el_val_t content, el_val_t label, el_val_t tags);
el_val_t mem_remember(el_val_t content, el_val_t tags);
el_val_t mem_recall(el_val_t query, el_val_t depth);
el_val_t mem_search(el_val_t query, el_val_t limit);
el_val_t mem_strengthen(el_val_t node_id);
el_val_t mem_forget(el_val_t node_id);
el_val_t mem_consolidate(void);
el_val_t mem_save(el_val_t path);
el_val_t mem_load(el_val_t path);
el_val_t mem_boot_count_get(void);
el_val_t mem_boot_count_inc(void);
el_val_t mem_emit_state_event(el_val_t trigger, el_val_t kind, el_val_t content);
el_val_t chat_default_model(void);
el_val_t engram_numeric_valid(el_val_t s);
el_val_t parse_float_x100(el_val_t s);
el_val_t engram_score_node(el_val_t node_json);
el_val_t engram_render_node(el_val_t node_json);
el_val_t engram_render_nodes(el_val_t nodes_json);
el_val_t engram_dedup_nodes(el_val_t nodes_json);
el_val_t engram_compile_ranked(el_val_t nodes_json, el_val_t max_nodes);
el_val_t engram_split_topics(el_val_t message);
el_val_t engram_extract_entities(el_val_t message);
el_val_t engram_detect_recall_intent(el_val_t message);
el_val_t engram_is_continuation(el_val_t message, el_val_t hist_len);
el_val_t engram_compile_multi(el_val_t topic);
el_val_t engram_nodes_merge(el_val_t a, el_val_t b);
el_val_t id_in_seen(el_val_t node_id, el_val_t seen);
el_val_t add_to_seen(el_val_t seen, el_val_t node_id);
el_val_t engram_extract_ids(el_val_t nodes_json);
el_val_t engram_compile(el_val_t intent);
el_val_t distill_transcript(el_val_t transcript);
el_val_t json_safe(el_val_t s);
el_val_t current_engine_note(el_val_t model);
el_val_t build_system_prompt(el_val_t ctx, el_val_t chat_mode);
el_val_t hist_append(el_val_t hist, el_val_t role, el_val_t content);
el_val_t hist_trim(el_val_t hist);
el_val_t hist_trim_with_bell_guard(el_val_t hist);
el_val_t clean_llm_response(el_val_t s);
el_val_t conv_history_persist(el_val_t hist);
el_val_t conv_history_load(void);
el_val_t session_preload_bullets(el_val_t nodes, el_val_t max_bullets, el_val_t snip_len);
el_val_t affective_context_prefix(void);
el_val_t handle_chat(el_val_t body);
el_val_t handle_see(el_val_t body);
el_val_t studio_tools_json(void);
el_val_t agentic_api_key(void);
el_val_t llm_base_url(void);
el_val_t llm_wire_format(void);
el_val_t json_escape(el_val_t s);
el_val_t openai_chat_complete(el_val_t model, el_val_t base_url, el_val_t api_key, el_val_t safe_sys, el_val_t messages_json);
el_val_t agentic_tools_literal(void);
el_val_t agentic_tools_with_web(void);
el_val_t connector_tools_json(void);
el_val_t agentic_tools_all(void);
el_val_t call_mcp_bridge(el_val_t tool_name, el_val_t tool_input);
el_val_t tool_auto_approved(el_val_t tool_name);
el_val_t call_neuron_mcp(el_val_t tool_name, el_val_t args);
el_val_t agent_workspace_root(void);
el_val_t path_within_root(el_val_t path, el_val_t root);
el_val_t resolve_in_root(el_val_t path, el_val_t root);
el_val_t run_command_is_readonly(el_val_t cmd);
el_val_t cmd_abs_escape_at(el_val_t cmd, el_val_t root, el_val_t needle);
el_val_t run_command_guard(el_val_t cmd, el_val_t root);
el_val_t classify_tool_risk(el_val_t tool_name, el_val_t tool_input);
el_val_t dispatch_tool(el_val_t tool_name, el_val_t tool_input);
el_val_t is_builtin_tool(el_val_t tool_name);
el_val_t next_bridge_id(void);
el_val_t handle_chat_plan(el_val_t body);
el_val_t handle_chat_agentic(el_val_t body);
el_val_t agentic_loop(el_val_t session_id, el_val_t model, el_val_t safe_sys, el_val_t tools_json, el_val_t messages_in, el_val_t h, el_val_t tools_log_in);
el_val_t bridge_save(el_val_t session_id, el_val_t model, el_val_t safe_sys, el_val_t tools_json, el_val_t messages, el_val_t tools_log, el_val_t tool_use_id);
el_val_t agentic_resume(el_val_t session_id, el_val_t tool_use_id, el_val_t content);
el_val_t handle_tool_result(el_val_t session_id, el_val_t body);
el_val_t handle_chat_as_soul(el_val_t body);
el_val_t handle_dharma_room_turn(el_val_t body);
el_val_t handle_dharma_room_turn_agentic(el_val_t body);
el_val_t session_summary_write(el_val_t summary_text);
el_val_t session_summary_write_dated(el_val_t summary_text, el_val_t label);
el_val_t session_summary_autogenerate(el_val_t hist);
el_val_t auto_persist(el_val_t req, el_val_t resp);
el_val_t strengthen_chat_nodes(el_val_t activation_nodes);
el_val_t auth_headers(el_val_t tok);
el_val_t axon_get(el_val_t path);
el_val_t axon_post(el_val_t path, el_val_t body);
el_val_t handle_conversations(el_val_t method);
el_val_t handle_config(el_val_t method, el_val_t body);
el_val_t dharma_registry(void);
el_val_t dharma_network_state(void);
el_val_t handle_dharma(el_val_t path, el_val_t method, el_val_t body);
el_val_t handle_tool(el_val_t path, el_val_t method, el_val_t body);
el_val_t handle_nlg(el_val_t path, el_val_t method, el_val_t body);
el_val_t render_studio(void);

el_val_t auth_headers(el_val_t tok) {
  el_val_t m = el_map_new(0);
  map_set(m, EL_STR("Content-Type"), EL_STR("application/json"));
  if (!str_eq(tok, EL_STR(""))) {
    map_set(m, EL_STR("Authorization"), el_str_concat(EL_STR("Bearer "), tok));
  }
  return m;
  return 0;
}

el_val_t axon_get(el_val_t path) {
  el_val_t base = state_get(EL_STR("soul_axon_base"));
  el_val_t tok = state_get(EL_STR("soul_token"));
  el_val_t h = auth_headers(tok);
  return http_get_with_headers(el_str_concat(base, path), h);
  return 0;
}

el_val_t axon_post(el_val_t path, el_val_t body) {
  el_val_t base = state_get(EL_STR("soul_axon_base"));
  el_val_t tok = state_get(EL_STR("soul_token"));
  el_val_t h = auth_headers(tok);
  return http_post_with_headers(el_str_concat(base, path), body, h);
  return 0;
}

el_val_t handle_conversations(el_val_t method) {
  el_val_t resp = engram_scan_nodes_json(500, 0);
  if (str_eq(resp, EL_STR(""))) {
    return EL_STR("[]");
  }
  return resp;
  return 0;
}

el_val_t handle_config(el_val_t method, el_val_t body) {
  if (str_eq(method, EL_STR("POST"))) {
    el_val_t new_model = json_get(body, EL_STR("model"));
    if (!str_eq(new_model, EL_STR(""))) {
      state_set(EL_STR("soul_model"), new_model);
    }
    el_val_t provider = json_get(body, EL_STR("provider"));
    el_val_t api_key = json_get(body, EL_STR("api_key"));
    if (!str_eq(provider, EL_STR("")) && !str_eq(api_key, EL_STR(""))) {
      state_set(el_str_concat(EL_STR("key_"), provider), api_key);
    }
  }
  el_val_t current_model = state_get(EL_STR("soul_model"));
  el_val_t display = ({ el_val_t _if_result_1 = 0; if (str_eq(current_model, EL_STR(""))) { _if_result_1 = (EL_STR("claude-opus-4-8")); } else { _if_result_1 = (current_model); } _if_result_1; });
  return el_str_concat(el_str_concat(EL_STR("{\"model\":\""), display), EL_STR("\",\"ok\":true}"));
  return 0;
}

el_val_t dharma_registry(void) {
  el_val_t cgi_id = state_get(EL_STR("soul_cgi_id"));
  el_val_t principal = state_get(EL_STR("soul_principal"));
  return el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"registry\":[{\"cgi\":\""), cgi_id), EL_STR("\",")), EL_STR("\"principal\":\"")), principal), EL_STR("\",")), EL_STR("\"covenant\":\"Principal Covenant v1\",")), EL_STR("\"registered\":\"2026-05-01\",\"provenance\":\"genesis\",")), EL_STR("\"entry\":1}],")), EL_STR("\"network_status\":\"initializing\",")), EL_STR("\"total_cgis\":1}"));
  return 0;
}

el_val_t dharma_network_state(void) {
  el_val_t cgi_id = state_get(EL_STR("soul_cgi_id"));
  return el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"active_members\":[{\"id\":\""), cgi_id), EL_STR("\",\"role\":\"cgi-entity\",\"status\":\"online\"}],")), EL_STR("\"pending_approvals\":[],\"recent_events\":[]}"));
  return 0;
}

el_val_t handle_dharma(el_val_t path, el_val_t method, el_val_t body) {
  if (str_eq(path, EL_STR("/api/dharma/registry"))) {
    return dharma_registry();
  }
  if (str_eq(path, EL_STR("/api/dharma/network"))) {
    return dharma_network_state();
  }
  if (str_eq(path, EL_STR("/api/dharma/submit"))) {
    el_val_t content = json_get(body, EL_STR("content"));
    el_val_t session_type = json_get(body, EL_STR("type"));
    return EL_STR("{\"ok\":true,\"submitted\":true,\"message\":\"Queued for Dharma Network\"}");
  }
  if (str_eq(path, EL_STR("/api/dharma/approve"))) {
    el_val_t cgi_id = json_get(body, EL_STR("cgi_id"));
    return EL_STR("{\"ok\":true,\"approved\":true}");
  }
  return EL_STR("{\"error\":\"unknown dharma endpoint\"}");
  return 0;
}

el_val_t handle_tool(el_val_t path, el_val_t method, el_val_t body) {
  if (str_eq(path, EL_STR("/api/tools/file/read"))) {
    el_val_t file_path = json_get(body, EL_STR("path"));
    if (str_eq(file_path, EL_STR(""))) {
      return EL_STR("{\"error\":\"path required\"}");
    }
    el_val_t content = fs_read(file_path);
    el_val_t s1 = str_replace(content, EL_STR("\\"), EL_STR("\\\\"));
    el_val_t s2 = str_replace(s1, EL_STR("\""), EL_STR("\\\""));
    el_val_t s3 = str_replace(s2, EL_STR("\n"), EL_STR("\\n"));
    el_val_t s4 = str_replace(s3, EL_STR("\r"), EL_STR("\\r"));
    return el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"content\":\""), s4), EL_STR("\",\"path\":\"")), file_path), EL_STR("\"}"));
  }
  if (str_eq(path, EL_STR("/api/tools/file/write"))) {
    el_val_t file_path = json_get(body, EL_STR("path"));
    el_val_t content = json_get(body, EL_STR("content"));
    if (str_eq(file_path, EL_STR(""))) {
      return EL_STR("{\"error\":\"path required\"}");
    }
    fs_write(file_path, content);
    return el_str_concat(el_str_concat(EL_STR("{\"ok\":true,\"path\":\""), file_path), EL_STR("\"}"));
  }
  if (str_eq(path, EL_STR("/api/tools/file/list"))) {
    el_val_t dir_path = json_get(body, EL_STR("path"));
    if (str_eq(dir_path, EL_STR(""))) {
      return EL_STR("{\"error\":\"path required\"}");
    }
    el_val_t entries = fs_list(dir_path);
    return el_str_concat(el_str_concat(EL_STR("{\"entries\":"), json_stringify(entries)), EL_STR("}"));
  }
  if (str_eq(path, EL_STR("/api/tools/web/get"))) {
    el_val_t url = json_get(body, EL_STR("url"));
    if (str_eq(url, EL_STR(""))) {
      return EL_STR("{\"error\":\"url required\"}");
    }
    el_val_t result = http_get(url);
    el_val_t s1 = str_replace(result, EL_STR("\\"), EL_STR("\\\\"));
    el_val_t s2 = str_replace(s1, EL_STR("\""), EL_STR("\\\""));
    el_val_t s3 = str_replace(s2, EL_STR("\n"), EL_STR("\\n"));
    el_val_t s4 = str_replace(s3, EL_STR("\r"), EL_STR("\\r"));
    return el_str_concat(el_str_concat(EL_STR("{\"result\":\""), s4), EL_STR("\"}"));
  }
  if (str_eq(path, EL_STR("/api/tools/web/post"))) {
    el_val_t url = json_get(body, EL_STR("url"));
    el_val_t post_body = json_get(body, EL_STR("body"));
    if (str_eq(url, EL_STR(""))) {
      return EL_STR("{\"error\":\"url required\"}");
    }
    el_val_t result = http_post(url, post_body);
    el_val_t s1 = str_replace(result, EL_STR("\\"), EL_STR("\\\\"));
    el_val_t s2 = str_replace(s1, EL_STR("\""), EL_STR("\\\""));
    el_val_t s3 = str_replace(s2, EL_STR("\n"), EL_STR("\\n"));
    el_val_t s4 = str_replace(s3, EL_STR("\r"), EL_STR("\\r"));
    return el_str_concat(el_str_concat(EL_STR("{\"result\":\""), s4), EL_STR("\"}"));
  }
  return el_str_concat(el_str_concat(EL_STR("{\"error\":\"unknown tool\",\"path\":\""), path), EL_STR("\"}"));
  return 0;
}

el_val_t handle_nlg(el_val_t path, el_val_t method, el_val_t body) {
  if (str_eq(path, EL_STR("/api/nlg/generate"))) {
    if (!str_eq(method, EL_STR("POST"))) {
      return EL_STR("{\"error\":\"POST required\"}");
    }
    el_val_t lang_req = json_get(body, EL_STR("lang"));
    el_val_t lang_code = ({ el_val_t _if_result_2 = 0; if (str_eq(lang_req, EL_STR(""))) { _if_result_2 = (EL_STR("en")); } else { _if_result_2 = (lang_req); } _if_result_2; });
    el_val_t text = generate_lang(body, lang_code);
    el_val_t safe = str_replace(text, EL_STR("\""), EL_STR("'"));
    return el_str_concat(el_str_concat(el_str_concat(el_str_concat(EL_STR("{\"text\":\""), safe), EL_STR("\",\"lang\":\"")), lang_code), EL_STR("\",\"ok\":true}"));
  }
  if (str_eq(path, EL_STR("/api/nlg/languages"))) {
    return EL_STR("{\"languages\":[\"en\",\"es\",\"fr\",\"de\",\"ru\",\"ja\",\"fi\",\"ar\",\"hi\",\"sw\",\"la\",\"he\",\"grc\",\"ang\",\"sa\",\"got\",\"non\",\"enm\",\"pi\",\"fro\",\"goh\",\"sga\",\"txb\",\"peo\",\"akk\",\"uga\",\"egy\",\"sux\",\"gez\",\"cop\",\"zh\"],\"count\":31}");
  }
  return EL_STR("{\"error\":\"unknown nlg path\"}");
  return 0;
}

el_val_t render_studio(void) {
  el_val_t studio_dir = state_get(EL_STR("soul_studio_dir"));
  el_val_t html = fs_read(el_str_concat(studio_dir, EL_STR("/index.html")));
  if (str_eq(html, EL_STR(""))) {
    return el_str_concat(el_str_concat(EL_STR("<html><body style='background:#080810;color:#e8e0cf;font-family:monospace;padding:2rem'>Studio not found at "), studio_dir), EL_STR("</body></html>"));
  }
  return html;
  return 0;
}

