// runtime/state.el — In-process key/value store.
//
// Thin El wrappers over the __state_* seed primitives. The backing store is
// a process-wide hash map maintained by the El runtime (formerly el_runtime.c
// lines 4632–4721: state_set, state_get, state_del, state_keys).
//
// Keys and values are Strings. Values are persistent across request boundaries
// within the same process instance (they survive individual request lifetimes).
// Concurrent access is serialized by the runtime; these wrappers are lock-free
// from El's perspective.
//
// Seed primitives consumed:
//   __state_set(key: String, val: String)
//   __state_get(key: String) -> String
//   __state_del(key: String)
//   __state_keys()            -> String   (JSON array of key strings)

// ---------------------------------------------------------------------------
// Core — set / get / del / keys
// ---------------------------------------------------------------------------

// state_set — store val under key. Overwrites any existing value.
fn state_set(key: String, val: String) {
    __state_set(key, val)
}

// state_get — retrieve the value for key. Returns "" if key is absent.
fn state_get(key: String) -> String {
    return __state_get(key)
}

// state_del — remove key from the store. No-op if key does not exist.
fn state_del(key: String) {
    __state_del(key)
}

// state_keys — return a JSON array string of all current keys.
// e.g. ["foo","bar","baz"]
// Matches legacy state_keys() which returns an ElList (here serialized as JSON).
fn state_keys() -> String {
    return __state_keys()
}

// ---------------------------------------------------------------------------
// Convenience helpers
// ---------------------------------------------------------------------------

// state_has — true if key is present (value is non-empty string).
// Note: a key set to "" is indistinguishable from absent via state_get alone.
fn state_has(key: String) -> Bool {
    let v: String = state_get(key)
    if str_eq(v, "") { return false }
    return true
}

// state_get_or — return val for key, or default_val if key is absent.
fn state_get_or(key: String, default_val: String) -> String {
    let v: String = state_get(key)
    if str_eq(v, "") { return default_val }
    return v
}
