///|
let schema_base : String = "https://a2ui.org/specification/v1_0/"

///|
pub let basic_catalog_id : String = "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json"

///|
fn identifier(name : String) -> Bool {
  let chars = name.iter().collect()
  !chars.is_empty() &&
  (chars[0] == '_' || @xid.is_xid_start(chars[0])) &&
  chars[1:].iter().all(@xid.is_xid_continue)
}

///|
// Preserve the official XID property-name constraint at its schema position.
// The private assertion uses Unicode tables rather than unsupported regex properties.
fn schema_resource(source : String) -> Json raise {
  let value = @json.parse(source)
  if value is { "$defs": Object(defs), .. } && defs.get("Extensions") is Some(_) {
    defs["Extensions"] = {
      "type": "object",
      "propertyNames": { "x-a2ui-assert-format": "a2ui-identifier" },
      "additionalProperties": true,
    }
    // Function definitions belong to the selected catalog, possibly an override.
    // CatalogRegistry validates each invocation against that catalog after this envelope.
    defs["FunctionCall"] = {
      "oneOf": [
        { "$ref": "#/$defs/IndexSystemFunction" },
        {
          "type": "object",
          "properties": {
            "@call": { "type": "string", "not": { "pattern": "^@" } },
            "catalogId": { "type": "string" },
            "args": { "type": "object" },
          },
          "required": ["@call"],
          "additionalProperties": false,
        },
      ],
    }
  }
  value
}

///|
fn bind_schema_refs(
  value : Json,
  catalog_uri : String,
  schema_map~ : Bool = false,
) -> Json {
  match value {
    Object(fields) => {
      let result = fields.map((key, item) => {
        if schema_map {
          return bind_schema_refs(item, catalog_uri)
        }
        if [
            "properties", "patternProperties", "$defs", "dependentSchemas", "components",
            "functions",
          ].contains(key) {
          return bind_schema_refs(item, catalog_uri, schema_map=true)
        }
        if (key == "$ref" || key == "$dynamicRef") && item is String(reference) {
          if reference.has_prefix("common_types.json") {
            return Json::string(schema_base + reference)
          }
          if reference.has_prefix("catalog.json") {
            return Json::string(catalog_uri + reference[12:].to_owned())
          }
        }
        if ["const", "enum", "default", "examples", "metadata", "description"].contains(
            key,
          ) {
          item
        } else {
          bind_schema_refs(item, catalog_uri)
        }
      })
      if !schema_map && fields.get("format") is Some(String(format)) {
        result["x-a2ui-assert-format"] = Json::string(format)
      }
      Json::object(result)
    }
    Array(items) =>
      Json::array(items.map(item => bind_schema_refs(item, catalog_uri)))
    _ => value
  }
}

///|
fn base_resources(catalog : Json) -> Map[String, Json] raise {
  let catalog_uri = if catalog is { "$id": String(id), .. } {
    id
  } else {
    schema_base + "catalog.json"
  }
  let resources : Map[String, Json] = Map([])
  let sources = [
    ("common_types.json", common_schema),
    ("agent_to_renderer.json", agent_schema),
    ("renderer_to_agent.json", renderer_schema),
    ("catalog_definition.json", catalog_schema),
    ("agent_capabilities.json", agent_capabilities_schema),
    ("renderer_capabilities.json", renderer_capabilities_schema),
    ("renderer_data_model.json", renderer_data_schema),
  ]
  for (name, source) in sources {
    resources[schema_base + name] = bind_schema_refs(
      schema_resource(source),
      catalog_uri,
    )
  }
  guard !resources.contains(catalog_uri) else {
    raise Invalid(
      path="/$id",
      reason="catalog cannot replace a built-in protocol schema",
    )
  }
  resources[catalog_uri] = bind_schema_refs(catalog, catalog_uri)
  resources
}

///|
fn compile_schema(
  document : Json,
  resources : Map[String, Json],
) -> @schema.Schema raise ProtocolError {
  @schema.Schema::compile(
    document,
    base_uri=schema_base + "validator.json",
    resources~,
    max_depth=256,
  ) catch {
    error => raise Invalid(path="/schema", reason="\{Repr(error)}")
  }
}

///|
fn check_schema(
  schema : @schema.Schema,
  value : Json,
) -> Unit raise ProtocolError {
  try {
    if !schema.valid(value, max_depth=256) {
      let errors = schema.faults(value, max_depth=256)
      raise Invalid(path=errors[0].instance_path, reason=errors[0].message)
    }
  } catch {
    Invalid(path~, reason~) => raise Invalid(path~, reason~)
    error => raise Invalid(path="", reason=(error : Error).to_string())
  }
}

///|
priv struct WireSchemas {
  agent : @schema.Schema
  renderer : @schema.Schema
  resources : Map[String, Json]
}

///|
let wire_schemas : Ref[WireSchemas?] = Ref(None)

///|
fn schemas() -> WireSchemas raise ProtocolError {
  if wire_schemas.val is Some(s) {
    return s
  }
  try {
    let catalog : Json = {
      "$defs": {
        "anyComponent": { "type": "object", "additionalProperties": true },
        "anyFunction": { "type": "object", "additionalProperties": true },
      },
    }
    let resources = base_resources(catalog)
    let s = {
      agent: compile_schema(
        { "$ref": Json::string(schema_base + "agent_to_renderer.json") },
        resources,
      ),
      renderer: compile_schema(
        { "$ref": Json::string(schema_base + "renderer_to_agent.json") },
        resources,
      ),
      resources,
    }
    wire_schemas.val = Some(s)
    s
  } catch {
    error => raise Invalid(path="/schema", reason=(error : Error).to_string())
  }
}