import { z } from "zod";
const safeSchemaCache = /* @__PURE__ */ new WeakMap();
function jsonSchemaToZod(jsonSchema) {
  const type = jsonSchema.type;
  if (type === "string") {
    return z.string();
  }
  if (type === "number" || type === "integer") {
    return z.number();
  }
  if (type === "boolean") {
    return z.boolean();
  }
  if (type === "null") {
    return z.null();
  }
  if (type === "array") {
    const items = jsonSchema.items;
    if (items) {
      return z.array(jsonSchemaToZod(items));
    }
    return z.array(z.unknown());
  }
  if (type === "object") {
    const properties = jsonSchema.properties;
    const required = jsonSchema.required || [];
    const additionalProperties = jsonSchema.additionalProperties;
    const hasFixedProperties = properties && Object.keys(properties).length > 0;
    if (additionalProperties && !hasFixedProperties && properties === void 0) {
      if (typeof additionalProperties === "object") {
        return z.record(z.string(), jsonSchemaToZod(additionalProperties));
      }
      return z.record(z.string(), z.unknown());
    }
    if (properties) {
      const shape = {};
      for (const [key, propSchema] of Object.entries(properties)) {
        let fieldSchema = jsonSchemaToZod(propSchema);
        if (!required.includes(key)) {
          fieldSchema = fieldSchema.optional();
        }
        shape[key] = fieldSchema;
      }
      if (additionalProperties) {
        return z.object(shape).passthrough();
      }
      return z.object(shape);
    }
    if (additionalProperties) {
      return z.record(z.string(), z.unknown());
    }
    return z.object({});
  }
  const anyOf = jsonSchema.anyOf;
  const oneOf = jsonSchema.oneOf;
  const unionTypes = anyOf || oneOf;
  if (unionTypes && unionTypes.length >= 2) {
    const schemas = unionTypes.map((s) => jsonSchemaToZod(s));
    return z.union(schemas);
  }
  if (anyOf && anyOf.length === 2) {
    const types = anyOf.map((s) => s.type);
    if (types.includes("null")) {
      const nonNullSchema = anyOf.find((s) => s.type !== "null");
      if (nonNullSchema) {
        return jsonSchemaToZod(nonNullSchema).nullable();
      }
    }
  }
  const enumValues = jsonSchema.enum;
  if (enumValues && enumValues.length > 0) {
    return z.enum(enumValues);
  }
  return z.unknown();
}
function toSafeZodSchema(schema) {
  const cached = safeSchemaCache.get(schema);
  if (cached) {
    return cached;
  }
  try {
    const jsonSchema = z.toJSONSchema(schema, { unrepresentable: "any" });
    if (jsonSchema.type === "object" && !jsonSchema.properties) {
      jsonSchema.properties = {};
    }
    const safeSchema = jsonSchemaToZod(jsonSchema);
    safeSchemaCache.set(schema, safeSchema);
    return safeSchema;
  } catch (error) {
    console.error("[Schema Utils] Error converting schema:", error);
    return schema;
  }
}
export {
  jsonSchemaToZod,
  toSafeZodSchema
};
//# sourceMappingURL=schema-utils.js.map
