///|
/// JavaScript mode: `mcpbox code --js ` runs a real JavaScript program —
/// with loops, objects, string work and `try`/`catch` — against the same tools
/// the line DSL calls, instead of the line DSL itself.
///
/// The engine is QuickJS, compiled straight into the binary from the vendored
/// C sources in `justjavac/quickjs`. That is about a megabyte of executable and
/// a few seconds of build time, versus no runtime dependency and no node.
///
/// QuickJS is synchronous, so every MCP call is a host round trip: the prelude
/// turns `await call("server.tool", args)` into a queued request, this file
/// answers it with a real call and writes the answer back into the same heap.
/// Nothing but `eval`, `JSON.parse` and `JSON.stringify` crosses the boundary.
/// The only native glue is the SIGINT hook in `stub.c`, which exists because
/// QuickJS can otherwise never be told to stop.

///|
/// How many tool calls one script may make before mcpbox stops it. Ctrl-C
/// already stops a runaway loop, but a script that keeps calling tools forever
/// is also refused once it reaches this many.
let js_max_calls : Int32 = 10000

///|
/// The JavaScript prelude. It defines `console`, `call`, and the small queue
/// the host drains; `__in` carries the payload of a delivered call.
let js_prelude : String =
  #|var __out = [];
  #|var __q = [];
  #|var __res = {};
  #|var __id = 0;
  #|var __in = null;
  #|var __err = null;
  #|var __done = false;
  #|var __result = null;
  #|function __fmt(v) {
  #|  if (typeof v === "string") return v;
  #|  if (v === undefined) return "undefined";
  #|  try { return JSON.stringify(v); } catch (e) { return String(v); }
  #|}
  #|function __log() {
  #|  var parts = [];
  #|  for (var i = 0; i < arguments.length; i++) parts.push(__fmt(arguments[i]));
  #|  __out.push(parts.join(" "));
  #|}
  #|var console = { log: __log, info: __log, warn: __log, error: __log, debug: __log };
  #|function call(name, args) {
  #|  if (typeof name !== "string") {
  #|    throw new TypeError("call expects a tool name string, not " + typeof name);
  #|  }
  #|  if (args !== undefined && args !== null && typeof args !== "object") {
  #|    throw new TypeError("call arguments must be an object, not " + typeof args);
  #|  }
  #|  var arguments_ = args === undefined || args === null ? {} : args;
  #|  return new Promise(function (resolve, reject) {
  #|    var id = ++__id;
  #|    __res[id] = { resolve: resolve, reject: reject };
  #|    __q.push({ id: id, name: name, args: arguments_ });
  #|  });
  #|}
  #|function __next() { return __q.length ? JSON.stringify(__q.shift()) : ""; }
  #|function __deliver(id, ok) {
  #|  var pending = __res[id];
  #|  delete __res[id];
  #|  if (!pending) return;
  #|  if (ok) { pending.resolve(__in); return; }
  #|  var message = typeof __in === "string" ? __in : JSON.stringify(__in);
  #|  var error = new Error(message);
  #|  error.stack = "";
  #|  pending.reject(error);
  #|}
  #|function __describe(e) {
  #|  if (typeof e === "string") return e;
  #|  if (e === null || e === undefined) return String(e);
  #|  var head = (e.name || "Error") + (e.message ? ": " + e.message : "");
  #|  var stack = e.stack || "";
  #|  if (stack.indexOf(head) === 0) stack = stack.slice(head.length);
  #|  stack = stack.trim();
  #|  if (stack === "") return head;
  #|  var frames = stack.split("\n");
  #|  if (frames[0].charAt(0) !== " ") frames[0] = "    " + frames[0];
  #|  if (frames.length > 10) {
  #|    var extra = frames.length - 10;
  #|    frames = frames.slice(0, 10);
  #|    frames.push("    ... " + extra + " more frames");
  #|  }
  #|  return head + "\n" + frames.join("\n");
  #|}
  #|var __outPos = 0;
  #|function __takeOutput() {
  #|  if (__outPos >= __out.length) return null;
  #|  var line = __out[__outPos];
  #|  __out[__outPos] = undefined;
  #|  __outPos++;
  #|  if (__outPos >= 1024) { __out = __out.slice(__outPos); __outPos = 0; }
  #|  return line;
  #|}

///|
/// Evaluate `source` for its effect. A JavaScript exception becomes an
/// `Error` carrying the engine's message, never a dangling exception value.
fn js_eval(
  context : @quickjs.Context,
  source : String,
  filename : String,
) -> Unit raise Error {
  let value = context.eval(source, filename~)
  if value.is_exception() {
    let message = context.exception_message()
    value.destroy()
    raise fail(message)
  }
  value.destroy()
}

///|
/// Evaluate `source` and return its value as text. The prelude only produces
/// strings here, so lossy conversion is exact for the request queue and the
/// captured console output.
fn js_text(
  context : @quickjs.Context,
  source : String,
  filename : String,
) -> String raise Error {
  let value = context.eval(source, filename~)
  if value.is_exception() {
    let message = context.exception_message()
    value.destroy()
    raise fail(message)
  }
  let text = value.to_string_lossy(context)
  value.destroy()
  text
}

///|
/// The `id` of a queued request, as a JS number rendered into JSON.
fn js_request_id(request : Json) -> Int32 {
  match request {
    Object(fields) =>
      match fields.get("id") {
        Some(Number(number, ..)) => number.to_int()
        _ => 0
      }
    _ => 0
  }
}

///|
/// The `server.tool` target of a queued request.
fn js_request_name(request : Json) -> String {
  match request {
    Object(fields) =>
      match fields.get("name") {
        Some(String(name)) => name
        _ => ""
      }
    _ => ""
  }
}

///|
/// A request's arguments as the `(key, value)` pairs the MCP layer expects.
/// JavaScript already produced JSON, so nothing is coerced against the schema.
fn js_request_pairs(request : Json) -> Array[(String, Json)] {
  match request {
    Object(fields) =>
      match fields.get("args") {
        Some(Object(arguments)) => {
          let pairs : Array[(String, Json)] = []
          for key in arguments.keys() {
            pairs.push((key, arguments.get(key).unwrap_or(Json::null())))
          }
          pairs
        }
        _ => []
      }
    _ => []
  }
}

///|
/// Split `server.tool` into its two halves at the first dot. Tool names
/// routinely contain dots, server names do not.
fn js_split_target(target : String) -> (String, String)? {
  let chars = target.to_array()
  let mut i = 0
  while i < chars.length() {
    if chars[i] == '.' {
      let server = target[0:i].to_owned()
      let tool = target[i + 1:].to_owned()
      if server.length() > 0 && tool.length() > 0 {
        return Some((server, tool))
      }
      return None
    }
    i += 1
  }
  None
}

///|
/// Write `payload` into the heap as `__in` and settle the waiting promise.
fn js_deliver(
  context : @quickjs.Context,
  id : Int32,
  ok : Bool,
  payload : Json,
) -> Unit raise Error {
  let global = context.global_object()
  let value = context.parse_json(payload.stringify())
  let _ = global.set_property(context, "__in", value)
  value.destroy()
  global.destroy()
  js_eval(
    context,
    "__deliver(" + id.to_string() + ", " + (if ok { "1" } else { "0" }) + ")",
    "mcpbox:deliver",
  )
}

///|
/// One queued call, answered. Errors are handed to JavaScript rather than
/// aborting the script, so `try`/`catch` around a call behaves as it should.
async fn js_answer(
  context : @quickjs.Context,
  request : Json,
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  unavailable : Map[String, String],
  opts : Options,
) -> Unit raise Error {
  let id = js_request_id(request)
  let name = js_request_name(request)
  let outcome = js_call_outcome(
    request, name, sessions, tools_cache, unavailable, opts,
  )
  match outcome {
    Ok(value) => js_deliver(context, id, true, value)
    Err(message) => js_deliver(context, id, false, Json::string(message))
  }
}

///|
/// Perform one queued call, turning every failure into a message JavaScript can
/// catch. Nothing here raises, so the script keeps its own error handling.
async fn js_call_outcome(
  request : Json,
  name : String,
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  unavailable : Map[String, String],
  opts : Options,
) -> Result[Json, String] {
  let (server_name, tool_name) = match js_split_target(name) {
    None => return Err("call expects '.', not '" + name + "'")
    Some(target) => target
  }
  match unavailable.get(server_name) {
    Some(reason) =>
      return Err("server '" + server_name + "' is unavailable: " + reason)
    None => ()
  }
  if !sessions.contains(server_name) {
    return Err("no server named '" + server_name + "'")
  }
  let pairs = js_request_pairs(request)
  let value = code_js_call(
    server_name, tool_name, pairs, sessions, tools_cache, opts,
  ) catch {
    error => return Err(error_text(error))
  }
  Ok(value)
}

///|
/// Take the next console line, or `None` when the buffer is empty. Lines come
/// back as strings rather than as JSON: a lone surrogate in the output would
/// make a JSON round trip fail, and losing every line is worse than losing the
/// half of a surrogate pair.
fn js_next_line(context : @quickjs.Context) -> String? raise Error {
  let value = context.eval("__takeOutput()", filename="mcpbox:output")
  if value.is_exception() {
    let message = context.exception_message()
    value.destroy()
    raise fail(message)
  }
  if value.is_null() {
    value.destroy()
    return None
  }
  let text = value.to_string_lossy(context)
  value.destroy()
  Some(text)
}

///|
/// Drain the console buffer, printing each line (or collecting it for `--json`).
async fn js_flush_output(
  context : @quickjs.Context,
  opts : Options,
  prints : Array[Json],
) -> Unit raise Error {
  let mut more = true
  while more {
    match js_next_line(context) {
      Some(line) =>
        if opts.json {
          prints.push(Json::string(line))
        } else {
          print_line(line)
        }
      None => more = false
    }
  }
}

///|
/// Run the script and every call it makes. The loop alternates three things:
/// settle the promise jobs the last answer woke up, hand out the console text
/// they produced, and answer the next queued call. When a pass finds no queued
/// call and no pending job, the script is either done or stuck forever.
async fn js_loop(
  context : @quickjs.Context,
  runtime : @quickjs.Runtime,
  script : String,
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  unavailable : Map[String, String],
  opts : Options,
  prints : Array[Json],
) -> Result[Json, String] {
  // The script sits on its own line inside the wrapper, or a trailing `//`
  // comment would comment out the closing braces.
  let wrapper = "(async function(){ try { __result = await (async function(){" +
    script +
    "\n})(); } catch (e) { __err = __describe(e); } __done = true; })()"
  js_eval(context, js_prelude, "mcpbox:prelude") catch {
    error => return Err(error_text(error))
  }
  js_eval(context, wrapper, "script") catch {
    error =>
      return Err(
        if mcpbox_js_interrupted() != 0 {
          "interrupted"
        } else {
          error_text(error)
        },
      )
  }
  let mut calls = 0
  let mut finished = false
  while !finished {
    if mcpbox_js_interrupted() != 0 {
      return Err("interrupted")
    }
    // A delivered call wakes promise jobs; settle them before asking for more.
    // A job that throws comes back as an exception rather than a return value,
    // so an uncaught `throw` inside `.then()` is reported instead of vanishing.
    while runtime.is_job_pending() {
      if runtime.execute_pending_job() < 0 {
        let message = context.exception_message()
        return Err(
          if mcpbox_js_interrupted() != 0 {
            "interrupted"
          } else {
            message
          },
        )
      }
    }
    js_flush_output(context, opts, prints) catch {
      error => return Err(error_text(error))
    }
    let request = js_text(context, "__next()", "mcpbox:queue") catch {
      error => return Err(error_text(error))
    }
    if request.length() == 0 {
      finished = true
      continue
    }
    calls += 1
    if calls > js_max_calls {
      return Err(
        "the script made more than " +
        js_max_calls.to_string() +
        " tool calls; mcpbox stopped it there",
      )
    }
    let parsed = @json.parse(request) catch {
      _ =>
        return Err("the engine produced a request that is not JSON: " + request)
    }
    js_answer(context, parsed, sessions, tools_cache, unavailable, opts) catch {
      error => return Err(error_text(error))
    }
  }
  let failure = js_text(
    context, "__err === null ? \"\" : __err", "mcpbox:error",
  ) catch {
    error => return Err(error_text(error))
  }
  if failure.length() > 0 {
    return Err(failure)
  }
  let done = js_text(context, "__done ? \"1\" : \"\"", "mcpbox:done") catch {
    error => return Err(error_text(error))
  }
  if done.length() == 0 {
    return Err("the script never finished: it is still waiting on a call")
  }
  let result = js_text(
    context, "JSON.stringify(__result === undefined ? null : __result)", "mcpbox:result",
  ) catch {
    error => return Err(error_text(error))
  }
  Ok(@json.parse(result) catch { _ => (null : Json) })
}

///|
/// Run a JavaScript script against the open sessions, returning the value the
/// script `return`s (or `null`). The engine is torn down on both paths.
async fn run_js_script(
  script : String,
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  unavailable : Map[String, String],
  opts : Options,
  prints : Array[Json],
) -> Json raise Error {
  let runtime = @quickjs.Runtime::new()
  runtime.set_memory_limit(268435456UL)
  runtime.set_max_stack_size(1048576UL)
  let context = @quickjs.Context::new(runtime)
  // Ctrl-C has to reach the engine, or a script in a loop runs forever.
  mcpbox_js_watch(runtime)
  let outcome = js_loop(
    context, runtime, script, sessions, tools_cache, unavailable, opts, prints,
  ) catch {
    error => Err(error_text(error))
  }
  mcpbox_js_unwatch(runtime)
  context.destroy()
  runtime.destroy()
  match outcome {
    Ok(value) => value
    Err(message) => raise fail(message)
  }
}

///|
/// Open a session for every configured server, remembering the ones that fail
/// instead of aborting: a JavaScript script picks its servers at run time, so a
/// broken neighbour must not stop it. A call to a failed server then reports
/// why that server is unavailable.
async fn with_js_sessions(
  servers : Array[Server],
  index : Int32,
  timeout_ms : Int32,
  sessions : Map[String, Session],
  unavailable : Map[String, String],
  started : Array[Bool],
  f : async () -> Unit raise Error,
) -> Unit raise Error {
  if index >= servers.length() {
    started[0] = true
    f()
    return
  }
  let server = servers[index]
  with_server(server, timeout_ms, session => {
    sessions[server.name] = session
    with_js_sessions(
      servers,
      index + 1,
      timeout_ms,
      sessions,
      unavailable,
      started,
      f,
    )
  }) catch {
    error => {
      // Once the script has started, an error is the script's, not a failed
      // connection; letting it through unchanged keeps the message honest.
      if started[0] {
        raise error
      }
      unavailable[server.name] = error_text(error)
      with_js_sessions(
        servers,
        index + 1,
        timeout_ms,
        sessions,
        unavailable,
        started,
        f,
      )
    }
  }
}

///|
/// `mcpbox code --js `: the JavaScript side of code mode.
async fn cmd_code_js(
  opts : Options,
  script : String,
  servers : Array[Server],
) -> Unit raise Error {
  if script.trim().length() == 0 {
    raise fail("the JavaScript script is empty")
  }
  let sessions : Map[String, Session] = Map([])
  let tools_cache : Map[String, Array[Tool]] = Map([])
  let unavailable : Map[String, String] = Map([])
  let prints : Array[Json] = []
  let result : Array[Json] = [Json::null()]
  startup_progress(opts, "running a JavaScript script…")
  let started : Array[Bool] = [false]
  with_js_sessions(
    servers,
    0,
    opts.timeout_ms,
    sessions,
    unavailable,
    started,
    () => {
      let value = run_js_script(
        script, sessions, tools_cache, unavailable, opts, prints,
      )
      result[0] = value
    },
  )
  if opts.json {
    let fields : Map[String, Json] = {
      "result": result[0],
      "prints": Json::array(prints),
    }
    print_line(Json::object(fields).stringify(indent=2))
  } else if result[0] != Json::null() {
    print_line(render_code_value(result[0]))
  }
}