// Per-chat session state and slash-command handling.
//
// Mirrors Hermes' conversation session handling: each `(platform, chat_id)`
// pair keeps a sliding history window plus the routing state needed for
// follow-up sends (`last_message_id`, `thread_id`, `context_token`). Slash
// commands (`/help`, `/reset`, `/status`, `/new`) are answered locally without
// invoking the agent.

///|
/// One conversation. `history` and `state` are reference types, so mutating a
/// session obtained from a `SessionStore` mutates the stored session.
#derive(Debug)
pub(all) struct Session {
  platform : Platform
  chat_id : String
  /// Sliding window of `(role, content)` turns.
  history : Array[(String, String)]
  /// Routing state: `last_message_id`, `thread_id`, `context_token`, `user_name`.
  state : Map[String, String]
  /// History window size.
  max_history : Int32
  /// Last activity (ms since the epoch), used for idle expiry.
  mut updated_at : Int64
}

///|
/// Session registry keyed by `platform:chat_id`.
#derive(Debug)
pub(all) struct SessionStore {
  sessions : Map[String, Session]
  max_history : Int32
}

///|
pub fn SessionStore::new(max_history~ : Int32 = 24) -> SessionStore {
  { sessions: Map([]), max_history, }
}

///|
/// Fetch (or create) the session for a chat.
pub fn SessionStore::session(
  self : SessionStore,
  platform : Platform,
  chat_id : String,
) -> Session {
  let key = "\{platform.value()}:\{chat_id}"
  match self.sessions.get(key) {
    Some(s) => s
    None => {
      let history : Array[(String, String)] = []
      let s : Session = {
        platform,
        chat_id,
        history,
        state: Map([]),
        max_history: self.max_history,
        updated_at: now_ms(),
      }
      self.sessions.set(key, s)
      s
    }
  }
}

///|
/// Number of tracked sessions.
pub fn SessionStore::len(self : SessionStore) -> Int32 {
  self.sessions.length()
}

///|
/// Append a turn, trimming the window to `max_history`.
pub fn Session::push(self : Session, role : String, content : String) -> Unit {
  self.updated_at = now_ms()
  self.history.push((role, content))
  while self.history.length() > self.max_history {
    ignore(self.history.remove(0))
  }
}

///|
/// Drop all history for this session.
pub fn Session::reset(self : Session) -> Unit {
  self.history.clear()
  self.state.clear()
}

///|
/// Record the id of the last message this gateway sent (reply target).
pub fn Session::set_last_message_id(self : Session, id : String) -> Unit {
  self.state.set("last_message_id", id)
}

///|
/// The last message id this gateway sent, if any.
pub fn Session::last_message_id(self : Session) -> String? {
  self.state.get("last_message_id")
}

///|
/// Remember a thread id for follow-up sends.
pub fn Session::set_thread_id(self : Session, id : String) -> Unit {
  self.state.set("thread_id", id)
}

///|
/// The stored thread id, if any.
pub fn Session::thread_id(self : Session) -> String? {
  self.state.get("thread_id")
}

///|
/// Remember the WeChat iLink `context_token` so replies stay in session.
pub fn Session::set_context_token(self : Session, token : String) -> Unit {
  self.state.set("context_token", token)
}

///|
/// The stored iLink `context_token`, if any.
pub fn Session::context_token(self : Session) -> String? {
  self.state.get("context_token")
}

///|
/// Render the history as an OpenAI-style `messages` array.
pub fn Session::messages_json(self : Session) -> Json {
  let items : Array[Json] = []
  for turn in self.history {
    items.push(
      json_obj([
        ("role", Json::string(turn.0)),
        ("content", Json::string(turn.1)),
      ]),
    )
  }
  Json::array(items)
}

///|
/// Parsed slash command: `(name, argument tail)`, lower-cased name and no
/// leading slash.
pub fn parse_command(text : String) -> (String, String)? {
  if !text.has_prefix("/") {
    return None
  }
  let token = match text.split_once(" ") {
    Some((head, tail)) => (head.to_owned(), tail.to_owned())
    None => (text, "")
  }
  let raw = token.0[1:].to_owned()
  let name = match raw.split_once("@") {
    Some((head, _)) => head.to_owned().to_lower()
    None => raw.to_lower()
  }
  if name.is_empty() {
    return None
  }
  Some((name, token.1.trim().to_owned()))
}

///|
/// Answer a built-in slash command locally. Returns `None` for commands the
/// agent should handle (and for plain messages).
pub fn command_reply(
  command : (String, String),
  cfg : GatewayConfig,
  session : Session,
) -> String? {
  match command.0 {
    "help" | "commands" =>
      Some(
        "imrelay commands:\n" +
        "/help — show this message\n" +
        "/reset — clear this chat's context\n" +
        "/new — start a fresh conversation\n" +
        "/status — show the session state\n" +
        "/platforms — list configured platforms",
      )
    "reset" | "new" | "clear" => {
      session.reset()
      Some("Context cleared.")
    }
    "status" =>
      Some(
        "platform: \{session.platform.value()}\n" +
        "chat: \{session.chat_id}\n" +
        "turns: \{session.history.length()}/\{session.max_history}\n" +
        "thread: \{session.thread_id().unwrap_or("-")}",
      )
    "platforms" => {
      let sb = StringBuilder()
      sb.write_string("Configured platforms:\n")
      for p in cfg.enabled_platforms() {
        sb.write_string("- \{p.name()} (\{p.value()})\n")
      }
      Some(sb.to_string())
    }
    _ => None
  }
}

///|
/// Hermes' silence contract: a reply equal to one of these markers is
/// suppressed instead of sent (§"silent" tokens). Case-insensitive.
pub fn is_silent_reply(text : String) -> Bool {
  let t = text.trim().to_lower()
  t == "[silent]" ||
  t == "no_reply" ||
  t == "no reply" ||
  t == "[no reply]" ||
  t.is_empty()
}

///|
/// Durable poll cursors (Telegram `offset`, Matrix `next_batch`, WeChat
/// `get_updates_buf`). Without this a restart replays whatever the platform
/// still holds and answers every message again — the in-memory de-duplicator
/// does not survive either.
///
/// Persisted as a small JSON object of `key → string`. Writes go through a
/// temporary file and rename so a crash cannot leave a truncated cursor.
#derive(Debug)
pub(all) struct CursorStore {
  path : String
  values : Map[String, String]
}

///|
/// An unbacked store (nothing is read or written); used when
/// `[gateway] state_file` is unset.
pub fn CursorStore::memory() -> CursorStore {
  { path: "", values: Map([]), }
}

///|
/// Load a store from ``path``. A missing or unreadable file yields an empty
/// store, so a first run needs no setup.
pub async fn CursorStore::load(path : String) -> CursorStore {
  let values : Map[String, String] = Map([])
  if path.is_empty() {
    return { path, values, }
  }
  let text = @fs.read_file(path).text() catch { _ => "" }
  let j = @json.parse(text) catch { _ => Json::null() }
  match j {
    Object(m) =>
      for k, v in m {
        match v {
          String(s) => values.set(k, s)
          _ => ()
        }
      }
    _ => ()
  }
  { path, values, }
}

///|
pub fn CursorStore::get(self : CursorStore, key : String) -> String {
  self.values.get(key).unwrap_or("")
}

///|
/// Remember ``value`` for ``key`` and flush to disk (no-op when the store is
/// in memory or the value is unchanged).
pub async fn CursorStore::set(
  self : CursorStore,
  key : String,
  value : String,
) -> Unit {
  if value.is_empty() || self.get(key) == value {
    return
  }
  // Always update the in-memory map; only a backed store touches the disk.
  self.values.set(key, value)
  if self.path.is_empty() {
    return
  }
  let fields : Array[(String, Json)] = []
  for k, v in self.values {
    fields.push((k, Json::string(v)))
  }
  let body = Json::object(Map(fields)).stringify()
  let tmp = "\{self.path}.tmp"
  @fs.write_file(tmp, @utf8.encode(body)[:]) catch {
    _ => return
  }
  @fs.rename(tmp, self.path, replace=true) catch {
    _ => ()
  }
}

// --- Session persistence ---------------------------------------------------

///|
/// Serialize every tracked session so the agent keeps its context across a
/// restart. Shape: `{":": {"updated_at": ms, "state": {…},
/// "history": [["user", "…"], …]}}`.
pub fn SessionStore::to_json(self : SessionStore) -> Json {
  let entries : Map[String, Json] = Map([])
  for key, s in self.sessions {
    let turns : Array[Json] = []
    for turn in s.history {
      turns.push(Json::array([Json::string(turn.0), Json::string(turn.1)]))
    }
    let state_items : Array[(String, Json)] = []
    for k, v in s.state {
      state_items.push((k, Json::string(v)))
    }
    entries.set(
      key,
      json_obj([
        ("updated_at", Json::number(s.updated_at.to_double())),
        ("state", Json::object(Map(state_items))),
        ("history", Json::array(turns)),
      ]),
    )
  }
  Json::object(entries)
}

///|
/// Restore a store from ``path``, dropping sessions idle for longer than
/// ``ttl_ms`` (`0` keeps everything) and trimming each history window to
/// ``max_history``.
pub async fn SessionStore::load(
  path : String,
  max_history~ : Int32 = 24,
  ttl_ms~ : Int64 = 0L,
) -> SessionStore {
  let store = SessionStore::new(max_history~)
  if path.is_empty() {
    return store
  }
  let text = @fs.read_file(path).text() catch { _ => "" }
  let j = @json.parse(text) catch { _ => Json::null() }
  let now = now_ms()
  match j {
    Object(m) =>
      for key, entry in m {
        match key.split_once(":") {
          Some((platform_name, chat_id)) =>
            match Platform::of_value(platform_name.to_owned()) {
              Some(platform) => {
                let updated_at = json_field_int64(entry, "updated_at").unwrap_or(
                  0L,
                )
                if ttl_ms > 0L && updated_at > 0L && now - updated_at > ttl_ms {
                  continue
                }
                let s = Session::{
                  platform,
                  chat_id: chat_id.to_owned(),
                  history: [],
                  state: Map([]),
                  max_history,
                  updated_at,
                }
                for turn in json_field_array(entry, "history").unwrap_or([]) {
                  match turn {
                    Array(items) =>
                      if items.length() == 2 {
                        let role = json_to_plain(items[0])
                        let content = json_to_plain(items[1])
                        if !role.is_empty() && !content.is_empty() {
                          s.history.push((role, content))
                        }
                      }
                    _ => ()
                  }
                }
                while s.history.length() > max_history {
                  ignore(s.history.remove(0))
                }
                match json_field_obj(entry, "state") {
                  Some(Object(sm)) =>
                    for k, v in sm {
                      match v {
                        String(sv) => s.state.set(k, sv)
                        _ => ()
                      }
                    }
                  _ => ()
                }
                store.sessions.set(key, s)
              }
              None => ()
            }
          None => ()
        }
      }
    _ => ()
  }
  store
}

///|
/// Flush the store to ``path`` (temp file + rename). No-op for an empty path.
pub async fn SessionStore::save(self : SessionStore, path : String) -> Unit {
  if path.is_empty() {
    return
  }
  let tmp = "\{path}.tmp"
  @fs.write_file(tmp, @utf8.encode(self.to_json().stringify())[:]) catch {
    _ => return
  }
  @fs.rename(tmp, path, replace=true) catch {
    _ => ()
  }
}

///|
/// Drop sessions idle for longer than ``ttl_ms`` (`0` disables pruning).
pub fn SessionStore::prune(
  self : SessionStore,
  ttl_ms : Int64,
  now : Int64,
) -> Int32 {
  if ttl_ms <= 0L {
    return 0
  }
  let stale : Array[String] = []
  for key, s in self.sessions {
    if s.updated_at > 0L && now - s.updated_at > ttl_ms {
      stale.push(key)
    }
  }
  for key in stale {
    self.sessions.remove(key)
  }
  stale.length()
}