///|
fn MCPServer::skills_are_enabled(self : MCPServer) -> Bool {
  self.resources_are_enabled() && !self.skill_entries.is_empty()
}

///|
fn valid_skill_path(path : String) -> Bool {
  lexmatch path {
    re"^([A-Za-z0-9_.\-]+/)*[.]{1,2}(/[A-Za-z0-9_.\-]+)*$" => false
    re"^[A-Za-z0-9_.\-]+(/[A-Za-z0-9_.\-]+)*$" => true
    _ => false
  }
}

///|
fn valid_skill_name(name : String) -> Bool {
  name.length() <= 64 && name =~ re"^[a-z0-9]+(-[a-z0-9]+)*$"
}

///|
/// Publish a static, UTF-8 skill under skill:///SKILL.md.
/// Each file tuple is (relative path, MIME type, text). The caller supplies
/// the complete parsed SKILL.md YAML frontmatter as JSON, unchanged.
/// The exact UTF-8 bytes served by resources/read are hashed for the manifest.
/// Optional relative directories declare empty directories as well.
pub fn MCPServer::with_skill(
  self : MCPServer,
  skill_path : String,
  frontmatter : Json,
  files : Array[(String, String, String)],
  directories~ : Array[String] = [],
) -> MCPServer raise @types.MCPError {
  guard frontmatter
    is { "name": String(name), "description": String(description), .. } else {
    raise @types.InvalidParams(
      "Skill frontmatter requires name and description",
    )
  }
  if !valid_skill_name(name) ||
    description == "" ||
    description.length() > 1024 ||
    !valid_skill_path(skill_path) ||
    !(skill_path == name || skill_path.has_suffix("/" + name)) {
    raise @types.InvalidParams("Invalid skill name, path or description")
  }
  if files.length() > 512 || directories.length() > 512 {
    raise @types.InvalidParams("Skill exceeds 512 files")
  }
  let root = "skill://" + skill_path + "/"
  let uri = root + "SKILL.md"
  if self.skill_entries.contains(uri) {
    raise @types.InvalidParams("Skill already registered: " + uri)
  }
  let directory_defs : Map[String, @types.ResourceDefinition] = Map([])
  collect_skill_directories(skill_path[:], "skill://", directory_defs)
  for path in directories {
    guard valid_skill_path(path) else {
      raise @types.InvalidParams("Invalid skill directory: " + path)
    }
    collect_skill_directories(path[:], root, directory_defs)
  }
  let manifest : Array[Json] = []
  let seen : Map[String, Unit] = Map([])
  let mut total = 0
  for (path, mime_type, text) in files {
    let file_uri = root + path
    if !valid_skill_path(path) ||
      seen.contains(path) ||
      self.resource_registry.resources.contains(file_uri) {
      raise @types.InvalidParams("Invalid or duplicate skill file: " + path)
    }
    guard mime_type != "inode/directory" else {
      raise @types.InvalidParams("Skill file cannot have directory MIME type")
    }
    lexmatch path {
      (re"/[^/]+$", before=parent) =>
        collect_skill_directories(parent, root, directory_defs)
      _ => ()
    }
    seen.set(path, ())
    let bytes = @utf8.encode(text)
    if bytes.length() > 16777216 - total {
      raise @types.InvalidParams("Skill exceeds 16 MiB")
    }
    total = total + bytes.length()
    manifest.push(@types.SkillResource::from_bytes(file_uri, bytes).to_json())
  }
  if !seen.contains("SKILL.md") {
    raise @types.InvalidParams("Skill requires SKILL.md")
  }
  // A file and a directory cannot occupy the same URI.
  for (path, _, _) in files {
    guard !directory_defs.contains(root + path) else {
      raise @types.InvalidParams("File conflicts with skill directory: " + path)
    }
  }
  for directory_uri, _ in directory_defs {
    match self.resource_registry.resources.get(directory_uri) {
      Some(existing) if existing.definition.mime_type != Some("inode/directory") =>
        raise @types.InvalidParams(
          "Directory conflicts with existing resource: " + directory_uri,
        )
      _ => ()
    }
  }
  let entry = @types.Skill::from_json({
    "uri": uri,
    "frontmatter": frontmatter,
    "resources": Json::array(manifest),
  })
  // Validate the entire tree before mutating either registry.
  for directory_uri, definition in directory_defs {
    if !self.resource_registry.resources.contains(directory_uri) {
      ignore(
        self.resource_definition(definition, (_context, _params) => {
          Err(
            @types.InvalidParams(
              "Use resources/directory/read for " + directory_uri,
            ),
          )
        }),
      )
    }
  }
  for (path, mime_type, text) in files {
    let file_uri = root + path
    let file_name = if path == "SKILL.md" { name } else { path }
    let file_description = if path == "SKILL.md" { description } else { "" }
    let mime_type = if path == "SKILL.md" { "text/markdown" } else { mime_type }
    ignore(
      self.resource(file_uri, file_name, file_description, mime_type, _context => {
        Ok(@types.ResourceReadResult::text(text, uri=file_uri, mime_type~))
      }),
    )
  }
  self.skill_entries.set(uri, entry)
  self
}

///|
fn handle_skills_list(
  server : MCPServer,
  id : @types.RequestId,
  params : Json,
) -> String {
  guard params is Object(fields) else {
    return jsonrpc_error_str(id, -32602, "Expected object params")
  }
  // The static registry returns the entire catalog in one page.
  if fields.contains("cursor") {
    return jsonrpc_error_str(id, -32602, "Invalid skills/list cursor")
  }
  let entries = server.skill_entries.to_array()
  entries.sort_by(fn(a, b) { a.0.compare(b.0) })
  jsonrpc_cacheable_success_str(
    server,
    id,
    { "skills": Json::array(entries.map(fn(entry) { entry.1.to_json() })) },
    60000,
    "public",
  )
}

///|
fn handle_skills_get(
  server : MCPServer,
  id : @types.RequestId,
  params : Json,
) -> String {
  guard extract_json_string(params, "uri") is Some(uri) else {
    return jsonrpc_error_str(id, -32602, "Missing 'uri' parameter")
  }
  match server.skill_entries.get(uri) {
    Some(skill) =>
      jsonrpc_cacheable_success_str(
        server,
        id,
        { "skill": skill.to_json() },
        60000,
        "public",
      )
    None => jsonrpc_error_str(id, -32602, "No skill is served at " + uri)
  }
}