///|
fn CatalogRegistry::validate_resolved(
  self : CatalogRegistry,
  fields : Map[String, Json],
  args : Json,
  catalog_id : String,
  caller : Caller,
) -> Unit raise ProtocolError {
  let call = fields.copy()
  if fields.contains("args") || args != Json::empty_object() {
    call["args"] = literal_wire(args)
  }
  self.validate_call(Json::object(call), catalog_id~, caller~)
}

///|
fn literal_wire(value : Json) -> Json {
  match value {
    Object(fields) => {
      let escaped = Map([])
      for key, item in fields {
        escaped[if key.has_prefix("@") { "@" + key } else { key }] = literal_wire(
          item,
        )
      }
      Json::object(escaped)
    }
    Array(items) => Json::array(items.map(literal_wire))
    _ => copy_json(value)
  }
}

///|
fn coerce_dynamic(
  value : Json,
  schema : Json,
  catalog : Json,
  depth : Int32,
) -> Json raise ProtocolError {
  guard depth < 100 else {
    raise RuntimeError(
      code="EXPRESSION_ERROR",
      reason="argument schema depth exceeded",
    )
  }
  if schema is { "$ref": String(reference), .. } {
    if reference.has_suffix("#/$defs/DynamicBoolean") {
      return Json::boolean(coerce_boolean(value))
    }
    if schema_pointer(catalog, reference) is Some(target) {
      return coerce_dynamic(value, target, catalog, depth + 1)
    }
  }
  if value is Object(fields) &&
    schema is { "properties": Object(properties), .. } {
    let result = fields.copy()
    for name, child in fields {
      if properties.get(name) is Some(child_schema) {
        result[name] = coerce_dynamic(child, child_schema, catalog, depth + 1)
      }
    }
    return Json::object(result)
  }
  if value is Array(items) && schema is { "items": child_schema, .. } {
    return Json::array(
      items.map(item => coerce_dynamic(item, child_schema, catalog, depth + 1)),
    )
  }
  value
}

///|
pub fn Runtime::component_properties(
  self : Runtime,
  surface_id : String,
  component_id : String,
  scope~ : String = "/",
  index? : Int32,
) -> Json raise ProtocolError {
  guard self.store.surfaces.get(surface_id) is Some(surface) &&
    surface.components.get(component_id) is Some(component) else {
    raise StateError("unknown component")
  }
  let (catalog, definition) = self.catalogs.component_definition(
    component,
    surface.catalog_id,
  )
  let (properties, _) = component_shape(definition, "/component")
  let context = {
    ..EvaluationContext::root(surface_id, catalog_id=catalog.id),
    scope,
    index,
  }
  let resolved = Map([])
  for key, value in object(component, "/component") {
    if ["id", "component", "@catalogId", "@metadata", "@checks", "action"].contains(
        key,
      ) {
      continue
    }
    let result = self.evaluate(value, context)
    resolved[key] = if properties.get(key) is Some(schema) {
      coerce_dynamic(result, schema, catalog.definition, 0)
    } else {
      result
    }
  }
  Json::object(resolved)
}

///|
priv struct ComponentWatch {
  surface_id : String
  component_id : String
  scope : String
  index : Int32?
  callback : (Json?) -> Unit
  mut previous : Json?
}

///|
/// Calls the observer only when resolved properties change; None means deletion.
pub fn Runtime::watch_component(
  self : Runtime,
  surface_id : String,
  component_id : String,
  callback : (Json?) -> Unit,
  scope~ : String = "/",
  index? : Int32,
) -> Int32 raise ProtocolError {
  guard self.store.surfaces.get(surface_id) is Some(surface) &&
    surface.components.contains(component_id) else {
    raise StateError("unknown component")
  }
  self.next_watch += 1
  let id = self.next_watch
  self.watches[id] = {
    surface_id,
    component_id,
    scope,
    index,
    callback,
    previous: None,
  }
  self.update_watches(surface_id)
  id
}

///|
pub fn Runtime::unwatch(self : Runtime, id : Int32) -> Unit {
  self.watches.remove(id)
}

///|
fn Runtime::update_watches(self : Runtime, surface_id : String) -> Unit {
  let watches = self.watches.iter().collect()
  for (id, watch) in watches {
    if watch.surface_id != surface_id {
      continue
    }
    if !self.store.surfaces.contains(surface_id) {
      self.watches.remove(id)
      (watch.callback)(None)
      continue
    }
    try {
      let index = watch.index
      let next = self.component_properties(
        surface_id,
        watch.component_id,
        scope=watch.scope,
        index?,
      )
      if watch.previous != Some(next) {
        watch.previous = Some(copy_json(next))
        (watch.callback)(Some(copy_json(next)))
      }
    } catch {
      RuntimeError(code="PENDING", ..) => ()
      CallFailed(id~, message~, ..) => {
        let error = RendererError::new(
          "EXPRESSION_ERROR",
          message,
          function_call_id=id,
        ) catch {
          _ => abort("valid error")
        }
        self.outgoing.push(Error(error))
      }
      error => {
        let error = RendererError::new(
          "EXPRESSION_ERROR",
          (error : Error).to_string(),
          surface_id~,
        ) catch {
          _ => abort("valid error")
        }
        self.outgoing.push(Error(error))
      }
    }
  }
}