/**
 * Schema Conversion Utilities
 *
 * Converts between Zod schemas and JSON Schema format for MCP tool integration
 * and AI SDK interoperability.
 */
import { z } from "zod";
/**
 * Lightweight Zod to JSON Schema converter.
 *
 * Accesses Zod internal `shape` and `_def` properties which lack public type
 * declarations. We use `unknown` with narrowing where possible and explicit
 * interface casts for Zod internals that have no public API surface.
 */
export function zodToJsonSchema(schema) {
    const objectSchema = schema;
    const shape = objectSchema.shape ?? Object.create(null);
    const properties = Object.create(null);
    const required = [];
    for (const key of Object.keys(shape)) {
        const field = shape[key];
        const desc = field.description;
        let type = "string";
        let enumValues;
        if (field instanceof z.ZodString) {
            type = "string";
        }
        else if (field instanceof z.ZodNumber) {
            type = "number";
        }
        else if (field instanceof z.ZodBoolean) {
            type = "boolean";
        }
        else if (field instanceof z.ZodEnum) {
            type = "string";
            enumValues = field._def.values;
        }
        else if (field instanceof z.ZodOptional) {
            const inner = field._def.innerType;
            if (inner instanceof z.ZodString)
                type = "string";
            else if (inner instanceof z.ZodNumber)
                type = "number";
            else if (inner instanceof z.ZodBoolean)
                type = "boolean";
            else if (inner instanceof z.ZodEnum) {
                type = "string";
                enumValues = inner._def.values;
            }
        }
        const prop = { type };
        if (desc)
            prop.description = desc;
        if (enumValues)
            prop.enum = enumValues;
        properties[key] = prop;
        if (!(field instanceof z.ZodOptional)) {
            required.push(key);
        }
    }
    return {
        type: "object",
        properties,
        required,
    };
}
/**
 * Simple JSON Schema to Zod converter for MCP tools.
 */
export function jsonSchemaToZod(schema) {
    const shape = Object.create(null);
    const props = schema?.properties ?? Object.create(null);
    const requiredFields = schema?.required ?? [];
    for (const key of Object.keys(props)) {
        const prop = props[key];
        let zType = z.string();
        if (prop.type === "number")
            zType = z.number();
        else if (prop.type === "boolean")
            zType = z.boolean();
        if (prop.description)
            zType = zType.describe(prop.description);
        if (!requiredFields.includes(key)) {
            zType = zType.optional();
        }
        shape[key] = zType;
    }
    return z.object(shape);
}
