///|
/// An owned catalog definition and its compiled component/function validators.
pub struct Catalog {
  id : String
  priv definition : Json
  priv component_schemas : Map[String, @schema.Schema]
  priv function_schemas : Map[String, @schema.Schema]
  priv resources : Map[String, Json]
}

///|
pub fn Catalog::basic() -> Catalog raise ProtocolError {
  let definition = @json.parse(basic_catalog_schema) catch {
    err => raise Invalid(path="/catalog", reason=err.to_string())
  }
  Catalog::from_json(definition)
}

///|
pub fn Catalog::from_json(value : Json) -> Catalog raise ProtocolError {
  try {
    let fields = object(value, "/catalog")
    let id = string_field(fields, "catalogId", "/catalog")
    if fields.get("protocolVersion") is Some(version) &&
      version != Json::string("1.0") {
      raise Invalid(
        path="/catalog/protocolVersion",
        reason="catalog targets a different protocol version",
      )
    }
    check_catalog_rules(value)
    let definition = copy_json(value)
    let resources = base_resources(definition)
    let validator = compile_schema(
      { "$ref": Json::string(schema_base + "catalog_definition.json") },
      resources,
    )
    check_schema(validator, definition)
    let component_schemas = Map([])
    let function_schemas = Map([])
    for
      (group, destination) in [
        ("components", component_schemas),
        ("functions", function_schemas),
      ] {
      if fields.get(group) is Some(Object(entries)) {
        for name, entry in entries {
          guard identifier(name) &&
            !(group == "components" && name == "Surface") else {
            raise Invalid(
              path="/catalog/" + group + "/" + name,
              reason="invalid catalog entity name",
            )
          }
          let reference = if definition is { "$id": String(uri), .. } {
            uri
          } else {
            schema_base + "catalog.json"
          }
          let common = if group == "components" {
            "ComponentCommon"
          } else {
            "FunctionCommon"
          }
          let schema : Json = {
            "allOf": [
              {
                "$ref": Json::string(
                  schema_base + "common_types.json#/$defs/" + common,
                ),
              },
              { "$ref": Json::string(reference + "#/" + group + "/" + name) },
            ],
            "unevaluatedProperties": false,
          }
          destination[name] = compile_schema(schema, resources)
          if group == "functions" {
            guard entry
              is {
                "properties": { "@call": { "const": String(declared), .. }, .. },
                ..
              } &&
              declared == name else {
              raise Invalid(
                path="/catalog/functions/" + name,
                reason="function name and discriminator differ",
              )
            }
          }
        }
      }
    }
    { id, definition, component_schemas, function_schemas, resources, }
  } catch {
    error => raise Invalid(path="/catalog", reason=(error : Error).to_string())
  }
}

///|
pub fn Catalog::to_json(self : Catalog) -> Json {
  copy_json(self.definition)
}

///|
pub struct CatalogRegistry {
  priv catalogs : Map[String, Catalog]
}

///|
pub fn CatalogRegistry::new(
  catalogs : Array[Catalog],
) -> CatalogRegistry raise ProtocolError {
  let registered = Map([])
  for catalog in catalogs {
    guard !registered.contains(catalog.id) else {
      raise StateError("duplicate catalog: " + catalog.id)
    }
    registered[catalog.id] = catalog
  }
  { catalogs: registered, }
}

///|
pub fn CatalogRegistry::basic() -> CatalogRegistry raise ProtocolError {
  CatalogRegistry::new([Catalog::basic()])
}

///|
pub fn CatalogRegistry::add(
  self : CatalogRegistry,
  catalog : Catalog,
) -> Unit raise ProtocolError {
  guard !self.catalogs.contains(catalog.id) else {
    raise StateError("duplicate catalog: " + catalog.id)
  }
  self.catalogs[catalog.id] = catalog
}

///|
fn CatalogRegistry::get(
  self : CatalogRegistry,
  id : String,
) -> Catalog raise ProtocolError {
  self.catalogs
  .get(id)
  .unwrap_or_else(() => raise StateError("unknown catalog: " + id))
}

///|
pub fn CatalogRegistry::validate_component(
  self : CatalogRegistry,
  component : Component,
  catalog_id~ : String,
) -> Unit raise ProtocolError {
  let fields = object(component.wire, "/component")
  let id = if fields.get("@catalogId") is Some(String(id)) {
    id
  } else {
    catalog_id
  }
  let catalog = self.get(id)
  let name = string_field(fields, "component", "/component")
  guard catalog.component_schemas.get(name) is Some(schema) else {
    raise Invalid(
      path="/component/component",
      reason="unknown component: " + name,
    )
  }
  check_schema(schema, component.wire)
  self.validate_expressions(component.wire, id)
}

///|
fn CatalogRegistry::validate_expressions(
  self : CatalogRegistry,
  value : Json,
  catalog_id : String,
) -> Unit raise ProtocolError {
  match value {
    { "@call": String(name), .. } => {
      if name == "@index" {
        let index_schema = compile_schema(
          {
            "$ref": Json::string(
              schema_base + "common_types.json#/$defs/IndexSystemFunction",
            ),
          },
          self.get(catalog_id).resources,
        )
        check_schema(index_schema, value)
      } else {
        self.validate_call(value, catalog_id~)
      }
      let nested_catalog = if value is { "catalogId": String(id), .. } {
        id
      } else {
        catalog_id
      }
      if value is { "args": args, .. } {
        self.validate_expressions(args, nested_catalog)
      }
    }
    Object(fields) =>
      for _, item in fields {
        self.validate_expressions(item, catalog_id)
      }
    Array(items) =>
      for item in items {
        self.validate_expressions(item, catalog_id)
      }
    _ => ()
  }
}

///|
pub fn CatalogRegistry::validate_call(
  self : CatalogRegistry,
  call : Json,
  catalog_id~ : String,
  caller~ : Caller = Renderer,
) -> Unit raise ProtocolError {
  let fields = object(call, "/callFunction")
  let id = if fields.get("catalogId") is Some(String(id)) {
    id
  } else {
    catalog_id
  }
  let name = string_field(fields, "@call", "/callFunction")
  guard identifier(name) else {
    raise Invalid(path="/@call", reason="invalid function identifier")
  }
  let catalog = self.get(id)
  if catalog.function_schemas.get(name) is Some(schema) {
    check_schema(schema, call)
  } else {
    // Only renderer-originated calls may use the undeclared-function fallback.
    guard caller == Renderer else {
      raise Invalid(
        path="/@call",
        reason="function is not declared in the renderer catalog",
      )
    }
    allowed_fields(fields, ["@call", "catalogId", "args"], "/callFunction")
    if fields.get("args") is Some(args) {
      ignore(object(args, "/callFunction/args"))
    }
  }
}

///|
fn Catalog::function_definition(self : Catalog, name : String) -> Json {
  if self.definition is { "functions": Object(functions), .. } &&
    functions.get(name) is Some(definition) {
    return definition
  }
  // Undeclared agent functions have the protocol default boundary and no return restriction.
  { "returnType": "any", "allowedCallers": "rendererOnly" }
}

///|
pub fn CatalogRegistry::capabilities(
  self : CatalogRegistry,
  inline_catalogs~ : Bool = false,
) -> Json {
  let body : Map[String, Json] = {
    "supportedCatalogIds": Json::array(
      self.catalogs.keys().map(Json::string).collect(),
    ),
  }
  if inline_catalogs {
    body["inlineCatalogs"] = Json::array(
      self.catalogs.values().map(c => c.to_json()).collect(),
    )
  }
  Json::object({ "1.0": Json::object(body) })
}