///|
#derive(Debug, Eq)
pub(all) struct McpFilter {
  prefix : String?
  tags : Array[String]
  exclude_paths : Array[String]
  include_streaming : Bool
}

///|
pub fn McpFilter::McpFilter(
  prefix? : String,
  tags~ : Array[String] = [],
  exclude_paths~ : Array[String] = ["/mcp", "/healthz", "/readyz", "/metrics"],
  include_streaming~ : Bool = false,
) -> McpFilter {
  { prefix, tags, exclude_paths, include_streaming, }
}

///|
#derive(Debug, Eq)
pub(all) struct McpTool {
  name : String
  title : String?
  description : String
  input_schema : Json
  output_schema : Json?
  annotations : ToolAnnotations?
  icons : Array[McpIcon]
  meta : Map[String, Json]?
  meth : @http.Method
  path : String
  param_names : Array[String]
  query_names : Array[String]
  body_is_wrapped : Bool
  body_fields : Array[String]
  bearer_auth : Bool
  is_streaming : Bool
}

///|
/// Validates an MCP tool name against SEP-986 (`^[A-Za-z0-9._-]{1,128}$`).
/// Returns a list of human-readable issues (empty means strictly compliant).
pub fn validate_tool_name(name : String) -> Array[String] {
  let issues : Array[String] = []
  if name.is_empty() {
    issues.push("Tool name must not be empty")
    return issues
  }
  if name.length() > 128 {
    issues.push("Tool name exceeds maximum length of 128 characters")
  }
  let mut has_invalid_char = false
  for ch in name {
    let ok = (ch >= 'a' && ch <= 'z') ||
      (ch >= 'A' && ch <= 'Z') ||
      (ch >= '0' && ch <= '9') ||
      ch == '_' ||
      ch == '-' ||
      ch == '.'
    if !ok {
      has_invalid_char = true
      break
    }
  }
  if has_invalid_char {
    issues.push(
      "Tool name should only contain ASCII letters, digits, '_', '-', and '.'",
    )
  }
  if name.has_prefix(".") || name.has_suffix(".") {
    issues.push("Tool name should not start or end with '.'")
  }
  issues
}

///|
pub fn McpTool::to_mcp_json(self : McpTool) -> Json {
  let m : Map[String, Json] = Map([
    ("name", Json::string(self.name)),
    ("description", Json::string(self.description)),
    ("inputSchema", self.input_schema),
  ])
  match self.title {
    Some(t) => m["title"] = Json::string(t)
    None => ()
  }
  match self.output_schema {
    Some(os) => m["outputSchema"] = os
    None => ()
  }
  match self.annotations {
    Some(a) => m["annotations"] = a.to_json()
    None => ()
  }
  if !self.icons.is_empty() {
    m["icons"] = Json::array(self.icons.map(i => i.to_json()))
  }
  match self.meta {
    Some(mt) => m["_meta"] = Json::object(mt)
    None => ()
  }
  Json::object(m)
}

///|
pub fn McpTool::to_openai_function_json(self : McpTool) -> Json {
  Json::object(
    Map([
      ("type", Json::string("function")),
      (
        "function",
        Json::object(
          Map([
            ("name", Json::string(self.name)),
            ("description", Json::string(self.description)),
            ("parameters", self.input_schema),
          ]),
        ),
      ),
    ]),
  )
}

///|
pub fn McpTool::to_anthropic_tool_json(self : McpTool) -> Json {
  Json::object(
    Map([
      ("name", Json::string(self.name)),
      ("description", Json::string(self.description)),
      ("input_schema", self.input_schema),
    ]),
  )
}

///|
fn default_tool_name(op : @openapi.OperationSpec) -> String {
  match op.operation_id {
    Some(id) if !id.is_empty() => id
    _ => {
      let sb = StringBuilder()
      sb.write_string(op.meth.as_str().to_lower())
      for seg in op.path.split("/") {
        let s = seg.to_owned()
        if s.is_empty() {
          continue
        }
        sb.write_char('_')
        if s.has_prefix(":") || s.has_prefix("*") {
          sb.write_string("by_")
          sb.write_string(s[1:].to_owned())
        } else {
          for ch in s {
            if (ch >= 'a' && ch <= 'z') ||
              (ch >= 'A' && ch <= 'Z') ||
              (ch >= '0' && ch <= '9') {
              sb.write_char(ch)
            } else {
              sb.write_char('_')
            }
          }
        }
      }
      sb.to_string()
    }
  }
}

///|
fn extract_path_params(path : String) -> Array[String] {
  let out : Array[String] = []
  for seg in path.split("/") {
    let s = seg.to_owned()
    if (s.has_prefix(":") || s.has_prefix("*")) && s.length() > 1 {
      out.push(s[1:].to_owned())
    }
  }
  out
}

///|
fn resolve_schema_node(node : @schema.SchemaNode) -> @schema.SchemaNode {
  match node {
    @schema.SchemaNode::Ref(r) => r.resolve()
    other => other
  }
}

///|
fn is_streaming_operation(op : @openapi.OperationSpec) -> Bool {
  for r in op.responses {
    match r.kind {
      @openapi.ResponseKind::Sse(..) | @openapi.ResponseKind::Ndjson(..) =>
        return true
      _ => ()
    }
  }
  false
}

///|
fn matches_filter(op : @openapi.OperationSpec, filter : McpFilter) -> Bool {
  for ex in filter.exclude_paths {
    if op.path == ex {
      return false
    }
  }
  // Skip unbounded GET SSE/NDJSON event streams by default to avoid hanging LLM calls
  if !filter.include_streaming &&
    op.meth == @http.Method::Get &&
    is_streaming_operation(op) {
    return false
  }
  match filter.prefix {
    Some(pfx) => if !op.path.has_prefix(pfx) { return false }
    None => ()
  }
  if !filter.tags.is_empty() {
    let mut matched = false
    for want in filter.tags {
      for have in op.tags {
        if want == have {
          matched = true
          break
        }
      }
      if matched {
        break
      }
    }
    if !matched {
      return false
    }
  }
  true
}

///|
fn apply_mcp_schema_meta(
  obj : Map[String, Json],
  meta : @schema.SchemaMeta,
) -> Unit {
  match meta.description {
    Some(d) => obj["description"] = Json::string(d)
    None => ()
  }
  match meta.format {
    Some(f) => obj["format"] = Json::string(f)
    None => ()
  }
  match meta.pattern {
    Some(p) => obj["pattern"] = Json::string(p)
    None => ()
  }
  match meta.default {
    Some(def) => obj["default"] = def
    None => ()
  }
  if meta.deprecated {
    obj["deprecated"] = Json::boolean(true)
  }
}

///|
/// Converts a `SchemaNode` into self-contained JSON Schema suitable for MCP tools:
/// non-recursive `SchemaNode::Ref` nodes are inlined directly, while recursive
/// `SchemaNode::Ref` cycles are hoisted into `defs` and referenced via `#/$defs/`.
fn export_mcp_schema_node(
  node : @schema.SchemaNode,
  defs : Map[String, Json],
  visiting : Map[String, Bool],
  used_defs : Map[String, Bool],
) -> Json {
  match node {
    @schema.SchemaNode::Ref(r) => {
      if visiting.contains(r.id) {
        used_defs[r.id] = true
        return Json::object(Map([("$ref", Json::string("#/$defs/\{r.id}"))]))
      }
      match defs.get(r.id) {
        Some(_) =>
          return Json::object(Map([("$ref", Json::string("#/$defs/\{r.id}"))]))
        None => ()
      }
      visiting[r.id] = true
      let resolved = export_mcp_schema_node(
        r.resolve(),
        defs,
        visiting,
        used_defs,
      )
      visiting.remove(r.id)
      if used_defs.contains(r.id) {
        defs[r.id] = resolved
        Json::object(Map([("$ref", Json::string("#/$defs/\{r.id}"))]))
      } else {
        resolved
      }
    }
    @schema.SchemaNode::Array(items~, min_items~, max_items~, meta~) => {
      let obj : Map[String, Json] = Map([
        ("type", Json::string("array")),
        ("items", export_mcp_schema_node(items, defs, visiting, used_defs)),
      ])
      match min_items {
        Some(v) => obj["minItems"] = Json::number(v.to_double())
        None => ()
      }
      match max_items {
        Some(v) => obj["maxItems"] = Json::number(v.to_double())
        None => ()
      }
      apply_mcp_schema_meta(obj, meta)
      Json::object(obj)
    }
    @schema.SchemaNode::Record(value~, meta~) => {
      let obj : Map[String, Json] = Map([
        ("type", Json::string("object")),
        (
          "additionalProperties",
          export_mcp_schema_node(value, defs, visiting, used_defs),
        ),
      ])
      apply_mcp_schema_meta(obj, meta)
      Json::object(obj)
    }
    @schema.SchemaNode::Object(
      fields~,
      additional_properties~,
      schema_id~,
      meta~,
    ) => {
      let props : Map[String, Json] = Map([])
      let reqs : Array[Json] = []
      for f in fields {
        let field_json = export_mcp_schema_node(
          f.schema,
          defs,
          visiting,
          used_defs,
        )
        let final_field = match (f.description, field_json) {
          (Some(desc), Object(m)) => {
            let copied : Map[String, Json] = Map([])
            m.each((k, v) => copied[k] = v)
            copied["description"] = Json::string(desc)
            Json::object(copied)
          }
          _ => field_json
        }
        props[f.name] = final_field
        if f.required {
          reqs.push(Json::string(f.name))
        }
      }
      let obj : Map[String, Json] = Map([
        ("type", Json::string("object")),
        ("properties", Json::object(props)),
        ("additionalProperties", Json::boolean(additional_properties)),
      ])
      if !reqs.is_empty() {
        obj["required"] = Json::array(reqs)
      }
      match schema_id {
        Some(id) => obj["x-ciallo-schema-id"] = Json::string(id)
        None => ()
      }
      apply_mcp_schema_meta(obj, meta)
      Json::object(obj)
    }
    @schema.SchemaNode::Union(variants~, meta~) => {
      let obj : Map[String, Json] = Map([
        (
          "anyOf",
          Json::array(
            variants.map(v => {
              export_mcp_schema_node(v, defs, visiting, used_defs)
            }),
          ),
        ),
      ])
      apply_mcp_schema_meta(obj, meta)
      Json::object(obj)
    }
    @schema.SchemaNode::Nullable(inner) =>
      Json::object(
        Map([
          (
            "anyOf",
            Json::array([
              export_mcp_schema_node(inner, defs, visiting, used_defs),
              Json::object(Map([("type", Json::string("null"))])),
            ]),
          ),
        ]),
      )
    leaf => @openapi.schema_to_json(leaf)
  }
}

///|
fn export_standalone_schema(node : @schema.SchemaNode) -> Json {
  let defs : Map[String, Json] = Map([])
  let visiting : Map[String, Bool] = Map([])
  let used_defs : Map[String, Bool] = Map([])
  let root = export_mcp_schema_node(node, defs, visiting, used_defs)
  if defs.is_empty() {
    root
  } else {
    match root {
      Object(m) => {
        let copied : Map[String, Json] = Map([])
        m.each((k, v) => copied[k] = v)
        copied["$defs"] = Json::object(defs)
        Json::object(copied)
      }
      other => other
    }
  }
}

///|
fn extract_output_schema(op : @openapi.OperationSpec) -> Json? {
  for r in op.responses {
    if r.status >= 200 && r.status < 300 {
      match r.kind {
        @openapi.ResponseKind::Json(@schema.SchemaNode::Empty) => ()
        @openapi.ResponseKind::Json(node) =>
          return Some(export_standalone_schema(node))
        _ => ()
      }
    }
  }
  None
}

///|
fn infer_tool_annotations(op : @openapi.OperationSpec) -> ToolAnnotations {
  match op.meth {
    @http.Method::Get | @http.Method::Head | @http.Method::Options =>
      ToolAnnotations::ToolAnnotations(
        title?=op.summary,
        read_only_hint=true,
        destructive_hint=false,
        idempotent_hint=true,
      )
    @http.Method::Put =>
      ToolAnnotations::ToolAnnotations(
        title?=op.summary,
        read_only_hint=false,
        destructive_hint=false,
        idempotent_hint=true,
      )
    @http.Method::Delete =>
      ToolAnnotations::ToolAnnotations(
        title?=op.summary,
        read_only_hint=false,
        destructive_hint=true,
        idempotent_hint=true,
      )
    _ =>
      ToolAnnotations::ToolAnnotations(
        title?=op.summary,
        read_only_hint=false,
        destructive_hint=false,
        idempotent_hint=false,
      )
  }
}

///|
fn operation_to_tool(op : @openapi.OperationSpec) -> McpTool {
  let props : Map[String, Json] = Map([])
  let input_defs : Map[String, Json] = Map([])
  let input_visiting : Map[String, Bool] = Map([])
  let input_used_defs : Map[String, Bool] = Map([])
  let required : Array[String] = []
  let param_names : Array[String] = []
  let query_names : Array[String] = []
  let body_fields : Array[String] = []

  // 1. Path params (from explicit params_schema + any :param segments in path)
  let explicit_param_fields : Map[String, @schema.ObjectField] = Map([])
  match op.params_schema {
    Some(ps) =>
      match resolve_schema_node(ps) {
        @schema.SchemaNode::Object(fields~, ..) =>
          for f in fields {
            explicit_param_fields[f.name] = f
          }
        _ => ()
      }
    None => ()
  }
  for pname in extract_path_params(op.path) {
    param_names.push(pname)
    match explicit_param_fields.get(pname) {
      Some(f) =>
        props[pname] = export_mcp_schema_node(
          f.schema,
          input_defs,
          input_visiting,
          input_used_defs,
        )
      None =>
        props[pname] = export_mcp_schema_node(
          @schema.SchemaNode::string(),
          input_defs,
          input_visiting,
          input_used_defs,
        )
    }
    required.push(pname)
  }

  // 2. Query params
  match op.query_schema {
    Some(qs) =>
      match resolve_schema_node(qs) {
        @schema.SchemaNode::Object(fields~, ..) =>
          for f in fields {
            if !props.contains(f.name) {
              query_names.push(f.name)
              props[f.name] = export_mcp_schema_node(
                f.schema,
                input_defs,
                input_visiting,
                input_used_defs,
              )
              if f.required {
                required.push(f.name)
              }
            }
          }
        _ => ()
      }
    None => ()
  }

  // 3. Body schema (flatten object fields when unambiguous; wrap under "body" otherwise)
  let mut body_is_wrapped = false
  match op.body_schema {
    Some(bs) =>
      match resolve_schema_node(bs) {
        @schema.SchemaNode::Object(fields~, ..) => {
          let mut collision = false
          for f in fields {
            if props.contains(f.name) {
              collision = true
              break
            }
          }
          if collision {
            body_is_wrapped = true
            props["body"] = export_mcp_schema_node(
              bs, input_defs, input_visiting, input_used_defs,
            )
            required.push("body")
          } else {
            for f in fields {
              body_fields.push(f.name)
              props[f.name] = export_mcp_schema_node(
                f.schema,
                input_defs,
                input_visiting,
                input_used_defs,
              )
              if f.required {
                required.push(f.name)
              }
            }
          }
        }
        _ => {
          body_is_wrapped = true
          props["body"] = export_mcp_schema_node(
            bs, input_defs, input_visiting, input_used_defs,
          )
          required.push("body")
        }
      }
    None => ()
  }

  let schema_obj : Map[String, Json] = Map([
    ("type", Json::string("object")),
    ("properties", Json::object(props)),
    ("additionalProperties", Json::boolean(false)),
  ])
  if !required.is_empty() {
    schema_obj["required"] = Json::array(required.map(r => Json::string(r)))
  }
  if !input_defs.is_empty() {
    schema_obj["$defs"] = Json::object(input_defs)
  }
  let desc = match (op.summary, op.description) {
    (Some(s), Some(d)) => "\{s} - \{d}"
    (Some(s), None) => s
    (None, Some(d)) => d
    (None, None) => "\{op.meth.as_str()} \{op.path}"
  }
  {
    name: default_tool_name(op),
    title: op.summary,
    description: desc,
    input_schema: Json::object(schema_obj),
    output_schema: extract_output_schema(op),
    annotations: Some(infer_tool_annotations(op)),
    icons: [],
    meta: None,
    meth: op.meth,
    path: op.path,
    param_names,
    query_names,
    body_is_wrapped,
    body_fields,
    bearer_auth: op.bearer_auth,
    is_streaming: is_streaming_operation(op),
  }
}

///|
/// Exports MCP tools directly from a ciallo `OpenApiDocument`.
pub fn export_mcp_tools(
  doc : @openapi.OpenApiDocument,
  filter~ : McpFilter = McpFilter::McpFilter(),
) -> Array[McpTool] {
  let out : Array[McpTool] = []
  for op in doc.operations {
    if matches_filter(op, filter) {
      out.push(operation_to_tool(op))
    }
  }
  out
}

///|
/// Exports OpenAI-compatible Function Calling JSON Schema array.
pub fn export_openai_tools(
  doc : @openapi.OpenApiDocument,
  filter~ : McpFilter = McpFilter::McpFilter(),
) -> Json {
  Json::array(
    export_mcp_tools(doc, filter~).map(t => t.to_openai_function_json()),
  )
}

///|
/// Exports Anthropic-compatible Tool Calling JSON Schema array.
pub fn export_anthropic_tools(
  doc : @openapi.OpenApiDocument,
  filter~ : McpFilter = McpFilter::McpFilter(),
) -> Json {
  Json::array(
    export_mcp_tools(doc, filter~).map(t => t.to_anthropic_tool_json()),
  )
}