///|
/// Code Mode: instead of one tool call per command, a small script composes
/// calls and only what it prints comes back. The model (or the shell) writes
/// code against the tool API, intermediate results stay inside mcpbox, and the
/// final value is all that reaches the caller.
///
/// The script language is deliberately tiny and line-oriented:
///
///     libs = context7.resolve-library-id query="react hooks" libraryName=react
///     $libs[0].id
///     docs = context7.query-docs libraryId=$libs[0].id query="useEffect"
///     $docs.content[0].text
///
/// A variable holds the unwrapped MCP result: `structuredContent` when the
/// server sent it, otherwise a single JSON text block, otherwise the joined
/// text. `$name` followed by `.field` and `[index]` reads into it, so one call
/// can feed the next without the value traveling through a model's context.

///|
/// One step of a code-mode reference: a field read or an array index.
priv enum CodePath {
  Field(String)
  Index(Int32)
}

///|
/// One line of a code-mode script.
priv enum CodeStepKind {
  /// `name = server.tool key=value ...`, or the same without `name =`.
  Call(String?, String, String, Array[String])
  /// `$name.path...`, printed where it appears.
  Show(String)
  /// `for name in $list` — repeats the lines up to its `end`, binding one item
  /// at a time so the body can reference `$name`.
  For(String, String)
  /// `end` — closes the innermost `for`.
  End
}

///|
/// A script line plus its source line, for error messages.
priv struct CodeStep {
  line : Int32
  kind : CodeStepKind
}

///|
/// Whether a character may appear in a variable name. `-` is not one: a
/// reference is usually embedded in text (`"$x-$y"`), so a dash after a name
/// belongs to the text, not to the name.
fn is_code_var_char(c : Char) -> Bool {
  (c >= 'a' && c <= 'z') ||
  (c >= 'A' && c <= 'Z') ||
  (c >= '0' && c <= '9') ||
  c == '_'
}

///|
/// Whether a character may appear in a field name after a dot. Server results
/// routinely use `-` in keys (`library-id`), so a field may contain one.
fn is_code_field_char(c : Char) -> Bool {
  is_code_var_char(c) || c == '-'
}

///|
/// Scan `$name.path[0]` starting at the `$` in `chars[start]`. Returns the
/// variable name, its path, and the index just past the reference, so one
/// scanner serves both a whole-value reference and a `$ref` embedded in a
/// longer string.
fn scan_code_path(
  chars : Array[Char],
  start : Int32,
  text : String,
) -> (String, Array[CodePath], Int32) raise McpError {
  let name = StringBuilder()
  let mut i = start + 1
  while i < chars.length() && is_code_var_char(chars[i]) {
    name.write_char(chars[i])
    i += 1
  }
  if name.to_string().length() == 0 {
    raise fail("'" + text + "' does not name a variable")
  }
  let paths : Array[CodePath] = []
  let mut done = false
  while i < chars.length() && !done {
    if chars[i] == '.' {
      i += 1
      let field = StringBuilder()
      while i < chars.length() && is_code_field_char(chars[i]) {
        field.write_char(chars[i])
        i += 1
      }
      if field.to_string().length() == 0 {
        raise fail("'" + text + "' has an empty field after '.'")
      }
      paths.push(Field(field.to_string()))
    } else if chars[i] == '[' {
      i += 1
      let mut index = 0
      let mut digits = 0
      while i < chars.length() && chars[i] >= '0' && chars[i] <= '9' {
        index = index * 10 + (chars[i].to_int() - '0'.to_int())
        digits += 1
        i += 1
      }
      if digits == 0 || i >= chars.length() || chars[i] != ']' {
        raise fail("'" + text + "' has a malformed [index]")
      }
      i += 1
      // A ten-digit index no longer fits in the Int32 `Index` carries, and a
      // wrapped negative would index the array out of bounds.
      if digits > 9 {
        raise fail("'" + text + "' has an index that is too large")
      }
      paths.push(Index(index))
    } else {
      // Not part of the reference: a caller embedding `$ref` in a longer
      // string continues from here.
      done = true
    }
  }
  (name.to_string(), paths, i)
}

///|
/// Parse `$name.path[0].field` into the variable name and its path. The whole
/// text must be the reference; trailing characters are an error, not a silent
/// truncation.
fn parse_code_path(text : String) -> (String, Array[CodePath]) raise McpError {
  guard text.has_prefix("$") && text.length() > 1 else {
    raise fail(
      "'" +
      text +
      "' is not a $variable reference (write $name or $name[0].field)",
    )
  }
  let chars = text.to_array()
  let (name, paths, next) = scan_code_path(chars, 0, text)
  if next < chars.length() {
    raise fail(
      "'" + text + "' has an unexpected character; use .field or [index]",
    )
  }
  (name, paths)
}

///|
/// Read a parsed path out of a variable's value.
fn resolve_code_path(
  vars : Map[String, Json],
  name : String,
  paths : Array[CodePath],
) -> Json raise McpError {
  let mut value = match vars.get(name) {
    Some(value) => value
    None => raise fail("unknown variable '$" + name + "'")
  }
  for path in paths {
    match path {
      Field(field) =>
        match value {
          Object(fields) =>
            value = match fields.get(field) {
              Some(found) => found
              None => raise fail("'$" + name + "' has no field '" + field + "'")
            }
          _ => raise fail("'$" + name + "' is not an object")
        }
      Index(index) =>
        match value {
          Array(items) =>
            if index >= items.length() {
              raise fail(
                "'$" +
                name +
                "' has no index " +
                index.to_string() +
                " (it has " +
                items.length().to_string() +
                " items)",
              )
            } else {
              value = items[index]
            }
          _ => raise fail("'$" + name + "' is not an array")
        }
    }
  }
  value
}

///|
/// Read a `$name.path[0]` reference out of the script's variables.
fn resolve_code_ref(
  vars : Map[String, Json],
  text : String,
) -> Json raise McpError {
  let (name, paths) = parse_code_path(text)
  resolve_code_path(vars, name, paths)
}

///|
/// Whether `text` is one whole reference, `$name.path` and nothing else. Such a
/// value keeps its JSON type; anything longer is interpolated as text.
fn is_code_whole_ref(text : String) -> Bool raise McpError {
  // `$$name` is the escaped, literal spelling, and a `$` that is not followed
  // by a name, as in `price=$`, is text rather than a broken reference.
  if !text.has_prefix("$") || text.has_prefix("$$") || text.length() == 1 {
    return false
  }
  let chars = text.to_array()
  if !is_code_var_char(chars[1]) {
    return false
  }
  let (_, _, next) = scan_code_path(chars, 0, text)
  next == chars.length()
}

///|
/// Replace every `$name.path` in `text` with its value, and `$$` with a literal
/// `$`. A `$` that does not start a name, as in `US$ 5`, is left alone, so only
/// a reference needs escaping.
fn interpolate_code_value(
  vars : Map[String, Json],
  text : String,
) -> String raise McpError {
  let chars = text.to_array()
  let out = StringBuilder()
  let mut i = 0
  while i < chars.length() {
    if chars[i] == '$' && i + 1 < chars.length() && chars[i + 1] == '$' {
      out.write_char('$')
      i += 2
    } else if chars[i] == '$' &&
      i + 1 < chars.length() &&
      is_code_var_char(chars[i + 1]) {
      let (name, paths, next) = scan_code_path(chars, i, text)
      out.write_string(render_code_value(resolve_code_path(vars, name, paths)))
      i = next
    } else {
      out.write_char(chars[i])
      i += 1
    }
  }
  out.to_string()
}

///|
/// A quoted value loses its enclosing quotes, the way a shell would remove
/// them. Quotes inside a value (a JSON argument, say) are left alone.
fn strip_code_quotes(raw : String) -> String {
  if raw.length() >= 2 {
    let quoted = (raw.has_prefix("\"") && raw.has_suffix("\"")) ||
      (raw.has_prefix("'") && raw.has_suffix("'"))
    if quoted {
      return raw.exact_view(start=1, end=raw.length() - 1).to_owned()
    }
  }
  raw
}

///|
/// Rewrite the arguments of one call. A value that is exactly `$ref` becomes
/// `key:=` so the schema-aware builder receives the value itself; a value
/// that merely contains `$ref` is interpolated as text, so a reference can sit
/// inside a sentence. Raw JSON (`key:=...`) is never rewritten.
fn resolve_code_pairs(
  vars : Map[String, Json],
  pairs : Array[String],
) -> Array[String] raise McpError {
  let out : Array[String] = []
  for pair in pairs {
    let (key, raw, is_json) = split_argument(pair)
    if is_json {
      out.push(pair)
    } else {
      let text = strip_code_quotes(raw)
      if is_code_whole_ref(text) {
        let value = resolve_code_ref(vars, text)
        out.push(key + ":=" + value.stringify())
      } else if text.contains("$") {
        out.push(key + "=" + interpolate_code_value(vars, text))
      } else {
        out.push(key + "=" + text)
      }
    }
  }
  out
}

///|
/// Split `server.tool`. A code-mode script always names its server: there is
/// no ambient ad-hoc server to fall back on.
fn code_target(text : String) -> (String, String) raise McpError {
  match text.find(".") {
    Some(index) =>
      if index == 0 || index + 1 >= text.length() {
        raise fail("'" + text + "' must be .")
      } else {
        (
          text.exact_view(end=index).to_owned(),
          text.exact_view(start=index + 1).to_owned(),
        )
      }
    None => raise fail("'" + text + "' must be .")
  }
}

///|
/// Split a script line on unquoted whitespace. Unlike `--stdio` splitting, a
/// quote is kept in the token so a JSON argument such as `meta:={"k":"a b"}`
/// survives; `strip_code_quotes` removes the outer quotes of a plain value.
/// A quote that is never closed is an error: otherwise `name="a b` would be
/// sent with the quote as part of the value.
///
/// Inside a `key:=` value, whitespace does not split the token while a
/// bracket is open, so the natural spelling `meta:={"a": 1}` works.
fn code_tokens(line : String) -> Array[String] raise McpError {
  let tokens : Array[String] = []
  let current = StringBuilder()
  let chars = line.to_array()
  let mut i = 0
  let mut in_quote = false
  let mut quote_char : Char = '"'
  let mut has_content = false
  let mut previous : Char = '\u{0}'
  let mut raw_json = false
  let mut depth = 0
  while i < chars.length() {
    let c = chars[i]
    if in_quote {
      current.write_char(c)
      if c == quote_char {
        in_quote = false
      }
    } else if c == '"' || c == '\'' {
      current.write_char(c)
      in_quote = true
      quote_char = c
      has_content = true
    } else if (c == ' ' || c == '\t') && !(raw_json && depth > 0) {
      if has_content {
        tokens.push(current.to_string())
        current.reset()
        has_content = false
        raw_json = false
        depth = 0
      }
    } else {
      current.write_char(c)
      has_content = true
      if c == '=' && previous == ':' {
        raw_json = true
      } else if raw_json && (c == '{' || c == '[') {
        depth += 1
      } else if raw_json && (c == '}' || c == ']') && depth > 0 {
        depth -= 1
      }
    }
    previous = c
    i += 1
  }
  if in_quote {
    raise fail(
      "unclosed " + quote_char.to_string() + " quote; close it to end the value",
    )
  }
  if has_content {
    tokens.push(current.to_string())
  }
  tokens
}

///|
/// Whether `text` is a plain variable name, as used before ` = `. A name starts
/// with a letter or `_`; a leading `-` or digit would read as a flag or a
/// number rather than a binding.
fn is_code_name(text : String) -> Bool {
  if text.length() == 0 {
    return false
  }
  let chars = text.to_array()
  let head = chars[0]
  if !((head >= 'a' && head <= 'z') ||
    (head >= 'A' && head <= 'Z') ||
    head == '_') {
    return false
  }
  for c in chars {
    if !is_code_var_char(c) {
      return false
    }
  }
  true
}

///|
/// Parse one non-empty, non-comment line.
fn parse_code_line(line : String) -> CodeStepKind raise McpError {
  if line == "end" {
    return End
  }
  if line == "for" || line.has_prefix("for ") || line.has_prefix("for\t") {
    let tokens = code_tokens(line)
    if tokens.length() != 4 || tokens[0] != "for" || tokens[2] != "in" {
      raise fail("write a loop as 'for name in $list' and close it with 'end'")
    }
    if !is_code_name(tokens[1]) {
      raise fail("'" + tokens[1] + "' is not a valid loop variable name")
    }
    ignore(parse_code_path(tokens[3]))
    return For(tokens[1], tokens[3])
  }
  if line.has_prefix("$") {
    ignore(parse_code_path(line))
    return Show(line)
  }
  let tokens = code_tokens(line)
  if tokens.length() == 0 {
    raise fail("empty line")
  }
  let mut binding : String? = None
  let mut start = 0
  if tokens.length() >= 2 && tokens[1] != "=" && tokens[0].contains("=") {
    raise fail(
      "write a binding as 'name = server.tool ...', with spaces around '='",
    )
  }
  if tokens.length() >= 3 && tokens[1] == "=" {
    if !is_code_name(tokens[0]) {
      raise fail("'" + tokens[0] + "' is not a valid variable name")
    }
    binding = Some(tokens[0])
    start = 2
  }
  let (server_name, tool_name) = code_target(tokens[start])
  let pairs : Array[String] = []
  let first_pair = start + 1
  for i in first_pair.. Array[CodeStep] raise McpError {
  let steps : Array[CodeStep] = []
  let mut line_number = 0
  for raw in text.split("\n") {
    line_number += 1
    let line = raw.trim().to_owned()
    if line.length() == 0 || line.has_prefix("#") {
      continue
    }
    let kind = parse_code_line(line) catch {
      error => raise fail("line \{line_number}: \{error_text(error)}")
    }
    steps.push({ line: line_number, kind, })
  }
  check_code_blocks(steps)
  steps
}

///|
/// Match every `for` with an `end`. The body of a loop is the run of lines
/// between the two, so an unclosed `for` would otherwise silently swallow the
/// rest of the script.
fn check_code_blocks(steps : Array[CodeStep]) -> Unit raise McpError {
  let open : Array[Int32] = []
  for i in 0.. open.push(i)
      End =>
        if open.is_empty() {
          raise fail("line \{steps[i].line}: 'end' without a 'for' to close")
        } else {
          ignore(open.pop())
        }
      _ => ()
    }
  }
  match open.pop() {
    Some(index) =>
      raise fail(
        "line \{steps[index].line}: this 'for' is never closed; add 'end'",
      )
    None => ()
  }
}

///|
/// The value a call contributes to the script: structured content first, then
/// a single JSON text block, then the joined text.
fn code_result_value(result : CallResult) -> Json {
  match result.structured {
    Some(value) => value
    None => {
      let texts : Array[String] = []
      for block in result.content {
        match block {
          Text(text) => texts.push(text)
          _ => ()
        }
      }
      if texts.length() == 1 {
        @json.parse(texts[0]) catch {
          _ => Json::string(texts[0])
        }
      } else if texts.length() > 1 {
        Json::string(texts.join("\n"))
      } else {
        Json::null()
      }
    }
  }
}

///|
/// What a script prints: bare text for strings, JSON for everything else.
fn render_code_value(value : Json) -> String {
  match value {
    String(text) => text
    _ => value.stringify()
  }
}

///|
/// The servers a script touches, in first-use order. Every target is checked
/// against the configured set before anything is started.
fn code_servers(
  steps : Array[CodeStep],
  servers : Array[Server],
) -> Array[Server] raise McpError {
  let used : Array[Server] = []
  for step in steps {
    match step.kind {
      Call(_, server_name, _, _) =>
        match find_server(servers, server_name) {
          Some(server) => {
            let mut seen = false
            for existing in used {
              if existing.name == server.name {
                seen = true
              }
            }
            if !seen {
              used.push(server)
            }
          }
          None =>
            raise fail(
              "line \{step.line}: no server named '" +
              server_name +
              "'" +
              available_names(servers),
            )
        }
      Show(_) | For(_, _) | End => ()
    }
  }
  used
}

///|
/// The index of the `end` that closes the `for` at `index`. The parser has
/// already checked that every `for` has one, so the scan always finds it.
fn code_block_end(steps : Array[CodeStep], index : Int32) -> Int32 {
  let mut depth = 0
  let mut i = index
  while i < steps.length() {
    match steps[i].kind {
      For(_, _) => depth += 1
      End => {
        depth -= 1
        if depth == 0 {
          return i
        }
      }
      _ => ()
    }
    i += 1
  }
  steps.length()
}

///|
/// Open a session for each server the script uses, then run the steps. The
/// sessions stay alive for the whole script, so a server sees one initialized
/// conversation instead of one per line.
async fn with_code_sessions(
  servers : Array[Server],
  index : Int32,
  timeout_ms : Int32,
  sessions : Map[String, Session],
  f : async (Map[String, Session]) -> Unit raise Error,
) -> Unit raise Error {
  if index >= servers.length() {
    f(sessions)
    return
  }
  let server = servers[index]
  with_server(server, timeout_ms, session => {
    sessions[server.name] = session
    with_code_sessions(servers, index + 1, timeout_ms, sessions, f)
  })
}

///|
/// Run the steps in order. `last_result` has one slot: the value of the most
/// recent call, which is what a script prints when it ends in a call.
async fn run_code_steps(
  steps : Array[CodeStep],
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  vars : Map[String, Json],
  opts : Options,
  last_result : Array[Json],
  prints : Array[Json],
) -> Unit raise Error {
  run_code_range(
    steps,
    0,
    steps.length(),
    sessions,
    tools_cache,
    vars,
    opts,
    last_result,
    prints,
  )
}

///|
/// Run `steps[start.. Unit raise Error {
  let mut i = start
  while i < stop {
    let step = steps[i]
    if step.kind is For(name, reference) {
      let value = resolve_code_ref(vars, reference) catch {
        error => raise fail("line \{step.line}: \{error_text(error)}")
      }
      let items = match value {
        Array(items) => items
        _ =>
          raise fail(
            "line \{step.line}: 'for' needs an array, and '" +
            reference +
            "' is " +
            value.stringify() +
            "",
          )
      }
      let block_end = code_block_end(steps, i)
      let saved = vars.get(name)
      for item in items {
        vars[name] = item
        run_code_range(
          steps,
          i + 1,
          block_end,
          sessions,
          tools_cache,
          vars,
          opts,
          last_result,
          prints,
        )
      }
      match saved {
        Some(value) => vars[name] = value
        None => vars.remove(name)
      }
      i = block_end + 1
      continue
    }
    match step.kind {
      For(_, _) | End => ()
      Show(reference) => {
        let value = resolve_code_ref(vars, reference) catch {
          error => raise fail("line \{step.line}: \{error_text(error)}")
        }
        prints.push(value)
        if !opts.json {
          print_line(render_code_value(value))
        }
      }
      Call(binding, server_name, tool_name, pairs) => {
        let resolved = resolve_code_pairs(vars, pairs) catch {
          error => raise fail("line \{step.line}: \{error_text(error)}")
        }
        let (session, tool) = code_find_tool(
          server_name, tool_name, sessions, tools_cache, opts,
        ) catch {
          error => raise fail("line \{step.line}: \{error_text(error)}")
        }
        let arguments = build_arguments(resolved, tool.input_schema) catch {
          error => raise fail("line \{step.line}: \{error_text(error)}")
        }
        let value = code_call_tool(
          session, server_name, tool_name, arguments, opts,
        ) catch {
          error => raise fail("line \{step.line}: \{error_text(error)}")
        }
        match binding {
          Some(name) => vars[name] = value
          None => ()
        }
        last_result[0] = value
      }
    }
    i += 1
  }
}

///|
/// Find a tool on an open session, listing the server's tools once and caching
/// them. Shared by the line DSL and JavaScript mode, so both report the same
/// failures; callers add their own context (a line number, or a target name).
async fn code_find_tool(
  server_name : String,
  tool_name : String,
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  opts : Options,
) -> (Session, Tool) raise Error {
  let session = match sessions.get(server_name) {
    Some(session) => session
    None => raise fail("no session for server '" + server_name + "'")
  }
  let tools = match tools_cache.get(server_name) {
    Some(tools) => tools
    None => {
      let tools = session.list_tools(opts.timeout_ms) catch {
        error =>
          raise fail(
            "cannot list tools of '" + server_name + "': " + error_text(error),
          )
      }
      tools_cache[server_name] = tools
      tools
    }
  }
  let tool = match find_tool(tools, tool_name) {
    Some(tool) => tool
    None =>
      raise fail(
        "'" +
        server_name +
        "' has no tool named '" +
        tool_name +
        "'" +
        available_tools(tools),
      )
  }
  (session, tool)
}

///|
/// Call an already-resolved tool and unwrap its result.
async fn code_call_tool(
  session : Session,
  server_name : String,
  tool_name : String,
  arguments : Json,
  opts : Options,
) -> Json raise Error {
  let result = session.call_tool(tool_name, arguments, opts.timeout_ms) catch {
    error =>
      raise fail(
        server_name + "." + tool_name + " failed: " + error_text(error),
      )
  }
  if result.is_error {
    raise fail(
      server_name +
      "." +
      tool_name +
      " reported an error: " +
      render_call_result(result),
    )
  }
  code_result_value(result)
}

///|
/// Answer one queued JavaScript call. The arguments already are JSON, so they
/// are passed through as-is rather than coerced against the tool's schema.
async fn code_js_call(
  server_name : String,
  tool_name : String,
  pairs : Array[(String, Json)],
  sessions : Map[String, Session],
  tools_cache : Map[String, Array[Tool]],
  opts : Options,
) -> Json raise Error {
  let (session, _tool) = code_find_tool(
    server_name, tool_name, sessions, tools_cache, opts,
  )
  let fields : Map[String, Json] = Map([])
  for pair in pairs {
    fields[pair.0] = pair.1
  }
  code_call_tool(session, server_name, tool_name, Json::object(fields), opts)
}

///|
/// The JSON Schema type of a property, as a TypeScript type.
fn code_ts_type(schema : Json) -> String {
  match schema_type(schema) {
    "string" => "string"
    "integer" | "number" => "number"
    "boolean" => "boolean"
    "array" => "Json[]"
    "object" => "Record"
    _ => "Json"
  }
}

///|
/// A tool's arguments as a TypeScript object type, with optional properties
/// marked `?`. Sorted for stable output.
fn code_ts_params(schema : Json) -> String {
  let properties = schema_properties(schema)
  if properties.is_empty() {
    return "{}"
  }
  let required = required_names(schema)
  let names = Array::from_iter(properties.keys())
  names.sort_by((a, b) => a.lexical_compare(b))
  let parts : Array[String] = []
  for name in names {
    let optional = !required.contains(name)
    let type_name = code_ts_type(properties.get(name).unwrap_or(Json::null()))
    parts.push(name + (if optional { "?" } else { "" }) + ": " + type_name)
  }
  "{ " + parts.join("; ") + " }"
}

///|
/// The generated API: one TypeScript interface entry per tool, plus the docs
/// mcpbox already renders. This is the piece a Code Mode agent loads instead
/// of every tool's JSON schema.
fn render_code_api(reports : Array[ServerReport]) -> String {
  let out = StringBuilder()
  out.write_string(
    "// mcpbox " +
    version +
    " code mode API — call each entry as `.`.\n",
  )
  out.write_string(
    "// Script:    mcpbox code    or   mcpbox code -e '