/**
 * Strip JSON Schema fields that Gemini functionDeclarations reject (400 / parse errors),
 * and normalize `type` to Google Gen AI uppercase enums.
 */
export function sanitizeSchemaForGemini(schema: unknown): unknown {
  if (schema === null || schema === undefined) {
    return schema;
  }
  if (Array.isArray(schema)) {
    return schema.map((item) => sanitizeSchemaForGemini(item));
  }
  if (typeof schema !== "object") {
    return schema;
  }

  const node = { ...(schema as Record<string, unknown>) };
  delete node.$schema;
  delete node.$id;
  delete node.additionalProperties;
  delete node.$defs;
  delete node.definitions;

  if (typeof node.type === "string") {
    node.type = node.type.toUpperCase();
  }

  for (const [key, value] of Object.entries(node)) {
    if (value !== null && typeof value === "object") {
      node[key] = sanitizeSchemaForGemini(value);
    }
  }

  return node;
}
