///|
priv struct PendingCall {
  surface_id : String?
  catalog_id : String
  return_type : Json
  expects_agent : Bool
  operation_id : String?
}

///|
pub(all) enum Evaluation {
  Ready(Json)
  Pending(String)
  Failed(code~ : String, message~ : String)
}

///|
pub fn Runtime::resolve(
  self : Runtime,
  value : Json,
  context : EvaluationContext,
) -> Evaluation {
  Ready(self.evaluate(value, context)) catch {
    RuntimeError(code="PENDING", reason~) => Pending(reason)
    CallFailed(id~, message~, ..) => {
      let error = RendererError::new(
        "EXPRESSION_ERROR",
        message,
        function_call_id=id,
      ) catch {
        _ => abort("valid expression error")
      }
      self.outgoing.push(Error(error))
      Failed(code="EXPRESSION_ERROR", message~)
    }
    RuntimeError(code~, reason~) => Failed(code~, message=reason)
    error =>
      Failed(code="EXPRESSION_ERROR", message=(error : Error).to_string())
  }
}

///|
pub fn Runtime::drain_messages(self : Runtime) -> Array[RendererMessage] {
  let messages = self.outgoing.copy()
  self.outgoing.clear()
  messages
}

///|
fn Runtime::remote_value(
  self : Runtime,
  fields : Map[String, Json],
  catalog_id : String,
  name : String,
  args : Json,
  definition : Map[String, Json],
  context : EvaluationContext,
) -> Json raise ProtocolError {
  guard context.allow_remote && context.caller == Renderer else {
    raise RuntimeError(
      code="EXPRESSION_ERROR",
      reason="function cannot be routed in this context: " + name,
    )
  }
  guard context.surface_id is Some(surface_id) else {
    raise RuntimeError(
      code="EXPRESSION_ERROR",
      reason="agent function requires a surface",
    )
  }
  let wire_fields = fields.copy()
  wire_fields["catalogId"] = Json::string(catalog_id)
  if fields.contains("args") || args != Json::empty_object() {
    wire_fields["args"] = args
  }
  let call = Json::object(wire_fields)
  let key = Json::array([
    Json::string(surface_id),
    Json::string(catalog_id),
    Json::string(name),
    args,
    if context.imperative {
      match context.operation_id {
        Some(id) => Json::string(id)
        None => Json::null()
      }
    } else {
      Json::null()
    },
  ]).stringify()
  if (!context.imperative || context.operation_id is Some(_)) &&
    self.cache.get(key) is Some(id) {
    if self.settled.get(id) is Some(response) {
      if response.value() is Some(value) {
        return value
      }
      guard response.error()
        is Some({ "code": String(code), "message": String(message), .. }) else {
        abort("validated function failure")
      }
      raise CallFailed(id~, code~, message~)
    }
    raise RuntimeError(code="PENDING", reason=id)
  }
  self.next_call += 1
  let id = "moon-a2ui-" + self.next_call.to_string()
  self.calls[id] = {
    surface_id: Some(surface_id),
    catalog_id,
    return_type: definition.get("returnType").unwrap_or(Json::string("any")),
    expects_agent: true,
    operation_id: context.operation_id,
  }
  if !context.imperative || context.operation_id is Some(_) {
    self.cache[key] = id
  }
  self.outgoing.push(RendererMessage::call_agent(id, surface_id, call))
  raise RuntimeError(code="PENDING", reason=id)
}

///|
fn argument_defaults(value : Json, properties : Json) -> Json {
  guard properties is { "args": schema, .. } else { return value }
  apply_defaults(value, schema)
}

///|
fn apply_defaults(value : Json, schema : Json) -> Json {
  match value {
    Object(fields) => {
      let result = fields.copy()
      if schema is { "properties": Object(properties), .. } {
        for key, child_schema in properties {
          if result.get(key) is Some(item) {
            result[key] = apply_defaults(item, child_schema)
          } else if child_schema is { "default": default, .. } {
            result[key] = copy_json(default)
          }
        }
      }
      Json::object(result)
    }
    Array(items) =>
      if schema is { "items": item_schema, .. } {
        Json::array(items.map(item => apply_defaults(item, item_schema)))
      } else {
        value
      }
    _ => value
  }
}

///|
fn Runtime::forget_surface(self : Runtime, surface_id : String) -> Unit {
  let cancelled = self.calls
    .iter()
    .filter_map(entry => {
      if entry.1.surface_id == Some(surface_id) {
        Some(entry.0)
      } else {
        None
      }
    })
    .collect()
  for id in cancelled {
    self.calls.remove(id)
    self.settled.remove(id)
    self.continuations.remove(id)
  }
  let keys = self.cache
    .iter()
    .filter_map(entry => {
      if cancelled.contains(entry.1) {
        Some(entry.0)
      } else {
        None
      }
    })
    .collect()
  for key in keys {
    self.cache.remove(key)
  }
}

///|
pub fn Runtime::take_response(self : Runtime, id : String) -> FunctionResponse? {
  let response = self.settled.get(id)
  if response is Some(_) {
    self.settled.remove(id)
    self.calls.remove(id)
    let keys = self.cache
      .iter()
      .filter_map(entry => if entry.1 == id { Some(entry.0) } else { None })
      .collect()
    for key in keys {
      self.cache.remove(key)
    }
  }
  response
}

///|
pub fn Runtime::receive_agent(
  self : Runtime,
  message : AgentMessage,
) -> Array[RendererMessage] raise ProtocolError {
  match message {
    SurfaceUpdate(update) => {
      self.apply(update)
      self.drain_messages()
    }
    AgentFunctionResponse(response) => {
      self.accept_response(response, expects_agent=true)
      self.drain_messages()
    }
    CallRenderer(call) => {
      let response = self.execute_remote(call, Agent)
      self.outgoing.push(RendererFunctionResponse(response))
      self.drain_messages()
    }
  }
}

///|
fn Runtime::accept_response(
  self : Runtime,
  response : FunctionResponse,
  expects_agent~ : Bool,
) -> Unit raise ProtocolError {
  guard !self.settled.contains(response.id) &&
    self.calls.get(response.id) is Some(pending) else {
    raise StateError("unknown or completed function call: " + response.id)
  }
  guard pending.expects_agent == expects_agent else {
    raise StateError("function response has wrong direction")
  }
  if pending.surface_id is Some(id) && !self.store.surfaces.contains(id) {
    raise StateError("function surface was deleted")
  }
  if response.value() is Some(value) {
    check_return_type(
      value,
      pending.return_type,
      self.catalogs.get(pending.catalog_id).resources,
    )
  }
  self.settled[response.id] = response
  if pending.surface_id is Some(id) {
    self.update_watches(id)
  }
  if self.continuations.get(response.id) is Some(waiting) {
    self.continuations.remove(response.id)
    for execution in waiting {
      if self.run_action(execution) is Some(message) {
        self.outgoing.push(message)
      }
    }
  }
}

///|
pub fn Runtime::response(self : Runtime, call_id : String) -> FunctionResponse? {
  self.settled.get(call_id)
}

///|
pub fn Runtime::cancel_call(
  self : Runtime,
  call_id : String,
  reason : String,
) -> Unit raise ProtocolError {
  guard self.calls.contains(call_id) && !self.settled.contains(call_id) else {
    raise StateError("unknown call: " + call_id)
  }
  self.accept_response(
    FunctionResponse::failure(call_id, "CANCELLED", reason),
    expects_agent=self.calls[call_id].expects_agent,
  )
}

///|
fn Runtime::execute_remote(
  self : Runtime,
  call : FunctionCall,
  caller : Caller,
) -> FunctionResponse raise ProtocolError {
  try {
    let expression = call.expression()
    let id = match expression {
      { "catalogId": String(id), .. } => id
      _ => {
        guard caller == Renderer &&
          call.surface_id is Some(surface_id) &&
          self.store.surfaces.get(surface_id) is Some(surface) &&
          surface.catalog_id is String(id) else {
          raise RuntimeError(
            code="INVALID_FUNCTION_CALL",
            reason="catalogId is required without a known surface catalog",
          )
        }
        id
      }
    }
    if caller == Agent &&
      call.surface_id is Some(surface_id) &&
      !self.store.surfaces.contains(surface_id) {
      raise StateError("unknown surface: " + surface_id)
    }
    guard expression is { "@call": String(name), .. } else {
      abort("validated function name")
    }
    let catalog = self.catalogs.get(id)
    if !self.functions.contains((id, name)) &&
      !(id == basic_catalog_id &&
      catalog.function_schemas.contains(name) &&
      name != "openUrl") {
      raise RuntimeError(
        code="UNKNOWN_FUNCTION",
        reason="no implementation: " + name,
      )
    }
    let context = {
      surface_id: call.surface_id,
      catalog_id: id,
      scope: "/",
      index: None,
      caller,
      user_activation: false,
      imperative: true,
      allow_remote: false,
      operation_id: None,
    }
    let value = if caller == Renderer {
      let definition = object(catalog.function_definition(name), "/function")
      let boundary = if definition.get("allowedCallers")
        is Some(String(boundary)) {
        boundary
      } else {
        "rendererOnly"
      }
      guard boundary != "agentOnly" else {
        raise RuntimeError(
          code="UNAUTHORIZED",
          reason="renderer is not allowed to invoke function",
        )
      }
      guard definition.get("requiresUserActivation") !=
        Some(Json::boolean(true)) else {
        raise RuntimeError(
          code="UNAUTHORIZED",
          reason="remote call has no trusted user activation",
        )
      }
      let fields = object(expression, "/callFunction")
      let args = argument_defaults(
        fields.get("args").unwrap_or(Json::empty_object()),
        definition.get("properties").unwrap_or(Json::empty_object()),
      )
      self.catalogs.validate_resolved(fields, args, id, Renderer)
      let result = if self.functions.get((id, name)) is Some(handler) {
        handler(args, context) catch {
          error =>
            raise RuntimeError(code="EXECUTION_ERROR", reason=error.to_string())
        }
      } else {
        self.basic_function(name, args, context, 0)
      }
      check_return_type(result, definition["returnType"], catalog.resources)
      result
    } else {
      self.evaluate(expression, context)
    }
    FunctionResponse::success(call.id, value)
  } catch {
    RuntimeError(code="NOT_IMPLEMENTED", reason~) =>
      FunctionResponse::failure(call.id, "UNKNOWN_FUNCTION", reason)
    RuntimeError(code~, reason~) =>
      FunctionResponse::failure(call.id, code, reason)
    error =>
      FunctionResponse::failure(
        call.id,
        "INVALID_FUNCTION_CALL",
        (error : Error).to_string(),
      )
  }
}

///|
/// Executes a renderer-originated RPC on an agent host with registered handlers.
pub fn Runtime::handle_agent_call(
  self : Runtime,
  message : RendererMessage,
) -> AgentMessage raise ProtocolError {
  guard message is CallAgent(call) else {
    raise StateError("expected callAgentFunction")
  }
  AgentFunctionResponse(self.execute_remote(call, Renderer))
}

///|
pub fn Runtime::begin_renderer_call(
  self : Runtime,
  id : String,
  call : Json,
  surface_id? : String,
) -> AgentMessage raise ProtocolError {
  guard !self.calls.contains(id) && !self.settled.contains(id) else {
    raise StateError("duplicate function call ID: " + id)
  }
  let message = AgentMessage::call_renderer(id, call, surface_id?)
  guard call is { "catalogId": String(catalog_id), "@call": String(name), .. } else {
    abort("validated renderer call")
  }
  let definition = object(
    self.catalogs.get(catalog_id).function_definition(name),
    "/function",
  )
  self.calls[id] = {
    surface_id,
    catalog_id,
    return_type: definition.get("returnType").unwrap_or(Json::string("any")),
    expects_agent: false,
    operation_id: None,
  }
  message
}

///|
pub fn Runtime::receive_renderer_response(
  self : Runtime,
  message : RendererMessage,
) -> Unit raise ProtocolError {
  guard message is RendererFunctionResponse(response) else {
    raise StateError("expected rendererFunctionResponse")
  }
  self.accept_response(response, expects_agent=false)
}