///|
#derive(Eq, Debug)
pub(all) enum Caller {
  Renderer
  Agent
}

///|
pub(all) struct EvaluationContext {
  surface_id : String?
  catalog_id : String
  scope : String
  index : Int32?
  caller : Caller
  user_activation : Bool
  imperative : Bool
  allow_remote : Bool
  operation_id : String?
}

///|
pub fn EvaluationContext::root(
  surface_id : String,
  catalog_id~ : String = basic_catalog_id,
  user_activation~ : Bool = false,
) -> EvaluationContext {
  {
    surface_id: Some(surface_id),
    catalog_id,
    scope: "/",
    index: None,
    caller: Renderer,
    user_activation,
    imperative: false,
    allow_remote: true,
    operation_id: None,
  }
}

///|
pub struct Runtime {
  priv store : SurfaceStore
  priv catalogs : CatalogRegistry
  priv functions : Map[
    (String, String),
    (Json, EvaluationContext) -> Json raise,
  ]
  priv calls : Map[String, PendingCall]
  priv settled : Map[String, FunctionResponse]
  priv cache : Map[String, String]
  priv outgoing : Array[RendererMessage]
  priv mut next_call : Int32
  priv watches : Map[Int32, ComponentWatch]
  priv mut next_watch : Int32
  priv continuations : Map[String, Array[ActionExecution]]
}

///|
pub fn Runtime::new(catalogs? : CatalogRegistry) -> Runtime raise ProtocolError {
  let catalogs = match catalogs {
    Some(c) => c
    None => CatalogRegistry::basic()
  }
  {
    store: SurfaceStore::new(catalogs~),
    catalogs,
    functions: Map([]),
    calls: Map([]),
    settled: Map([]),
    cache: Map([]),
    outgoing: [],
    next_call: 0,
    watches: Map([]),
    next_watch: 0,
    continuations: Map([]),
  }
}

///|
pub fn Runtime::apply(
  self : Runtime,
  message : Message,
) -> Unit raise ProtocolError {
  self.store.apply(message)
  if message.kind() == "deleteSurface" {
    self.forget_surface(message.surface_id())
  }
  self.update_watches(message.surface_id())
}

///|
pub fn Runtime::snapshot(self : Runtime, surface_id : String) -> Json? {
  self.store.snapshot(surface_id)
}

///|
pub fn Runtime::validate_complete(
  self : Runtime,
  surface_id : String,
) -> Unit raise ProtocolError {
  self.store.validate_complete(surface_id)
}

///|
pub fn Runtime::register_function(
  self : Runtime,
  catalog_id : String,
  name : String,
  handler : (Json, EvaluationContext) -> Json raise,
) -> Unit raise ProtocolError {
  ignore(self.catalogs.get(catalog_id))
  guard identifier(name) else {
    raise Invalid(path="/@call", reason="invalid function identifier")
  }
  guard !self.functions.contains((catalog_id, name)) else {
    raise StateError("function already registered: " + name)
  }
  self.functions[(catalog_id, name)] = handler
}

///|
pub fn coerce_boolean(value : Json) -> Bool {
  match value {
    True => true
    False | Null => false
    { "valid": True, .. } => true
    { "valid": False, .. } => false
    String(text) => text.to_lower() == "true"
    Number(number, ..) => number != 0.0
    _ => false
  }
}

///|
fn value_string(value : Json) -> String {
  match value {
    Null => ""
    String(text) => text
    _ => value.stringify()
  }
}

///|
fn scoped_path(scope : String, path : String) -> String raise ProtocolError {
  let absolute = if path.has_prefix("/") {
    path
  } else if path.is_empty() {
    scope
  } else if scope == "/" {
    "/" + path
  } else {
    scope + "/" + path
  }
  ignore(pointer_parts(absolute))
  absolute
}

///|
pub fn Runtime::write_binding(
  self : Runtime,
  context : EvaluationContext,
  binding : Json,
  value : Json,
) -> Unit raise ProtocolError {
  guard binding is { "@path": String(path), .. } else {
    raise Invalid(path="/@path", reason="input requires a data binding")
  }
  guard context.surface_id is Some(id) else {
    raise StateError("cannot write data without a surface")
  }
  self.apply(
    Message::update_data(id, value, path=scoped_path(context.scope, path)),
  )
}

///|
pub fn Runtime::evaluate(
  self : Runtime,
  value : Json,
  context : EvaluationContext,
) -> Json raise ProtocolError {
  self.evaluate_at(value, context, 0)
}

///|
fn Runtime::evaluate_at(
  self : Runtime,
  value : Json,
  context : EvaluationContext,
  depth : Int32,
) -> Json raise ProtocolError {
  guard depth < 100 else {
    raise RuntimeError(
      code="EXPRESSION_ERROR",
      reason="expression nesting exceeds 100",
    )
  }
  match value {
    { "@path": String(path), .. } => {
      guard object(value, "/@path").length() == 1 else {
        raise RuntimeError(
          code="EXPRESSION_ERROR",
          reason="binding has unknown fields",
        )
      }
      if context.surface_id is Some(id) {
        self.store
        .data_at(id, scoped_path(context.scope, path))
        .unwrap_or(Json::null())
      } else {
        Json::null()
      }
    }
    { "@call": String(name), .. } =>
      self.evaluate_call(value, name, context, depth + 1)
    Object(fields) => {
      let resolved = Map([])
      for key, item in fields {
        guard !key.has_prefix("@") || key.has_prefix("@@") else {
          raise RuntimeError(
            code="EXPRESSION_ERROR",
            reason="unrecognized directive: " + key,
          )
        }
        let key = if key.has_prefix("@@") { key[1:].to_owned() } else { key }
        resolved[key] = self.evaluate_at(item, context, depth + 1)
      }
      Json::object(resolved)
    }
    Array(items) =>
      Json::array(items.map(item => self.evaluate_at(item, context, depth + 1)))
    _ => value
  }
}

///|
fn Runtime::evaluate_call(
  self : Runtime,
  call : Json,
  name : String,
  context : EvaluationContext,
  depth : Int32,
) -> Json raise ProtocolError {
  let fields = object(call, "/callFunction")
  if name == "@index" {
    guard !fields.contains("catalogId") else {
      raise RuntimeError(
        code="EXPRESSION_ERROR",
        reason="@index is catalogless",
      )
    }
    allowed_fields(fields, ["@call", "args"], "/@index")
    guard context.index is Some(index) && index >= 0 else {
      raise RuntimeError(
        code="EXPRESSION_ERROR",
        reason="@index requires a collection scope",
      )
    }
    let offset = if fields.get("args") is Some(args) {
      let args = object(args, "/args")
      allowed_fields(args, ["offset"], "/args")
      self.evaluate_at(args.get("offset").unwrap_or(0), context, depth + 1)
    } else {
      (0 : Json)
    }
    guard offset is Number(offset, ..) else {
      raise RuntimeError(
        code="EXPRESSION_ERROR",
        reason="@index offset must be numeric",
      )
    }
    return Json::number(index.to_double() + offset)
  }
  let id = if fields.get("catalogId") is Some(String(id)) {
    id
  } else {
    context.catalog_id
  }
  self.catalogs.validate_call(call, catalog_id=id, caller=context.caller)
  let catalog = self.catalogs.get(id)
  let definition = object(catalog.function_definition(name), "/function")
  let allowed = if definition.get("allowedCallers") is Some(String(allowed)) {
    allowed
  } else {
    "rendererOnly"
  }
  guard (context.caller == Renderer && allowed != "agentOnly") ||
    (context.caller == Agent && allowed != "rendererOnly") else {
    raise RuntimeError(
      code="UNAUTHORIZED",
      reason="caller is not permitted for " + name,
    )
  }
  if definition.get("requiresUserActivation") == Some(Json::boolean(true)) &&
    !context.user_activation {
    raise RuntimeError(
      code="UNAUTHORIZED",
      reason="function requires user activation",
    )
  }
  let context = { ..context, catalog_id: id, }
  let resolved = self.evaluate_at(
    fields.get("args").unwrap_or(Json::empty_object()),
    context,
    depth + 1,
  )
  let arg_schema = match definition.get("properties") {
    Some({ "args": schema, .. }) => schema
    _ => Json::empty_object()
  }
  let resolved = coerce_dynamic(
    apply_defaults(resolved, arg_schema),
    arg_schema,
    catalog.definition,
    0,
  )
  self.catalogs.validate_resolved(fields, resolved, id, context.caller)
  let result = if self.functions.get((id, name)) is Some(handler) {
    handler(resolved, context) catch {
      error =>
        raise RuntimeError(code="EXPRESSION_ERROR", reason=error.to_string())
    }
  } else if id == basic_catalog_id &&
    catalog.function_schemas.contains(name) &&
    name != "openUrl" {
    self.basic_function(name, resolved, context, depth)
  } else {
    self.remote_value(fields, id, name, resolved, definition, context)
  }
  check_return_type(
    result,
    definition.get("returnType").unwrap_or(Json::string("any")),
    catalog.resources,
  )
  result
}

///|
fn check_return_type(
  value : Json,
  return_type : Json,
  resources : Map[String, Json],
) -> Unit raise ProtocolError {
  let schema : Json = match return_type {
    String("any") => true
    String("void") => { "type": "null" }
    String("validationResult") =>
      {
        "$ref": Json::string(
          schema_base + "catalog_definition.json#/$defs/ValidationResult",
        ),
      }
    String(kind) => { "type": Json::string(kind) }
    _ =>
      raise RuntimeError(code="EXPRESSION_ERROR", reason="invalid return type")
  }
  check_schema(compile_schema(schema, resources), value)
}

///|
pub fn Runtime::check(
  self : Runtime,
  rules : Array[Json],
  context : EvaluationContext,
) -> Array[Json] raise ProtocolError {
  let context = {
    ..context,
    user_activation: false,
    imperative: false,
    operation_id: None,
  }
  rules.map(rule => {
    guard rule is { "condition": condition, .. } else {
      raise Invalid(path="/condition", reason="check requires condition")
    }
    let result = self.evaluate(condition, context) catch {
      RuntimeError(code="PENDING", reason~) =>
        raise RuntimeError(code="PENDING", reason~)
      CallFailed(id~, message~, ..) => {
        self.outgoing.push(
          Error(
            RendererError::new("EXPRESSION_ERROR", message, function_call_id=id),
          ),
        )
        ({ "valid": false, "message": Json::string(message) } : Json)
      }
      error =>
        (
          {
            "valid": false,
            "message": Json::string((error : Error).to_string()),
          } : Json)
    }
    let fields = match result {
      True => return ({ "valid": true } : Json)
      False => ({ "valid": Json::boolean(false) } : Map[String, Json])
      Object(fields) if fields.get("valid") is Some(True | False) =>
        fields.copy()
      _ =>
        raise RuntimeError(
          code="EXPRESSION_ERROR",
          reason="check did not produce boolean or ValidationResult",
        )
    }
    if fields.get("valid") == Some(Json::boolean(false)) {
      if !fields.contains("message") &&
        rule is { "message": String(message), .. } {
        fields["message"] = Json::string(message)
      }
      if !fields.contains("severity") {
        fields["severity"] = Json::string("error")
      }
    }
    Json::object(fields)
  })
}

///|
pub fn Runtime::template_contexts(
  self : Runtime,
  context : EvaluationContext,
  path : String,
) -> Array[EvaluationContext] raise ProtocolError {
  let scope = scoped_path(context.scope, path)
  let value = self.evaluate({ "@path": Json::string(scope) }, context)
  match value {
    Array(items) =>
      items.mapi((index, _) => {
        ..context,
        scope: scope + "/" + index.to_string(),
        index: Some(index),
      })
    Object(fields) =>
      fields
      .keys()
      .collect()
      .mapi((index, key) => {
        ..context,
        scope: scope +
        "/" +
        key
        .split("~")
        .map(s => s.to_owned())
        .collect()
        .join("~0")
        .split("/")
        .map(s => s.to_owned())
        .collect()
        .join("~1"),
        index: Some(index),
      })
    _ =>
      raise RuntimeError(
        code="EXPRESSION_ERROR",
        reason="collection binding is not an array or object",
      )
  }
}