"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMcpCompatibleInputShape = exports.createMcpCompatibleInputSchema = exports.McpSchemaCompatLayer = void 0;
/* eslint-disable class-methods-use-this, no-underscore-dangle, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */
const schema_compat_1 = require("@mastra/schema-compat");
const zod_1 = require("zod");
const isNullable = (v) => v._def.typeName === 'ZodNullable';
const isDiscriminatedUnion = (v) => v._def.typeName === 'ZodDiscriminatedUnion';
/**
 * Create a new Zod schema instance with the same _def but a distinct object
 * identity. zodToJsonSchema uses reference equality to detect shared schemas
 * and emits $ref pointers for them. The MCP Gateway cannot resolve those
 * pointers and returns 500 ERR_INVALID_URL. By cloning every node during
 * processZodType, we guarantee all output instances are unique.
 */
const cloneZodInstance = (v) => new v.constructor({ ...v._def });
class McpSchemaCompatLayer extends schema_compat_1.SchemaCompatLayer {
    constructor() {
        // We don't need a real model for MCP, just pass dummy info
        super({
            modelId: 'mcp-lightdash',
            provider: 'lightdash',
            supportsStructuredOutputs: true,
        });
    }
    getSchemaTarget() {
        return 'jsonSchema7';
    }
    shouldApply() {
        // Always apply this compatibility layer when explicitly used
        return true;
    }
    processZodType(value) {
        // Clone the node so every processed schema has a unique identity.
        // This prevents zodToJsonSchema from generating $ref pointers when
        // the MCP SDK converts the schema for tool listing.
        const v = cloneZodInstance(value);
        // Handle nullable types (e.g., z.string().nullable()) map them to optional but default to null
        if (isNullable(v)) {
            let innerType = this.processZodType(v._def.innerType);
            // fix for `.default(...).nullable()`
            if (!(innerType instanceof zod_1.ZodDefault)) {
                innerType = innerType.optional();
            }
            // Accept an explicit null too: descriptions advertise nullable
            // fields as "or null", so MCP clients send null as often as they
            // omit the key. Coerce it to undefined before validation and let
            // the transform below restore null on output.
            return zod_1.z
                .preprocess((val) => (val === null ? undefined : val), innerType.describe([
                v.description ?? '',
                v._def.innerType.description ?? '',
            ].join(', ')))
                .transform((val) => (val === undefined ? null : val));
        }
        // always coerce numbers
        if ((0, schema_compat_1.isNumber)(v)) {
            return zod_1.z.preprocess((val) => Number(val), v);
        }
        // Identical to @mastra/schema-compat/src/provider-compats/anthropic.ts
        if ((0, schema_compat_1.isOptional)(v)) {
            const handleTypes = [
                'ZodObject',
                'ZodArray',
                'ZodUnion',
                'ZodNever',
                'ZodUndefined',
                'ZodTuple',
            ];
            return this.defaultZodOptionalHandler(v, handleTypes);
        }
        if ((0, schema_compat_1.isObj)(v)) {
            return this.defaultZodObjectHandler(v);
        }
        if ((0, schema_compat_1.isArr)(v)) {
            return this.defaultZodArrayHandler(v, []);
        }
        if ((0, schema_compat_1.isUnion)(v)) {
            return this.defaultZodUnionHandler(v);
        }
        // ZodDiscriminatedUnion is not recognized by isUnion() from
        // @mastra/schema-compat, so handle it explicitly by converting to a
        // regular union. This ensures its variants are recursively processed
        // (and therefore cloned) to prevent $ref generation.
        if (isDiscriminatedUnion(v)) {
            return this.defaultZodUnionHandler(zod_1.z.union(v._def.options.map((opt) => this.processZodType(opt))));
        }
        if ((0, schema_compat_1.isString)(v)) {
            return v;
        }
        return this.defaultUnsupportedZodTypeHandler(v, [
            'ZodNever',
            'ZodTuple',
            'ZodUndefined',
        ]);
    }
}
exports.McpSchemaCompatLayer = McpSchemaCompatLayer;
const mcpSchemaCompatLayer = new McpSchemaCompatLayer();
const createMcpCompatibleInputSchema = (inputSchema) => mcpSchemaCompatLayer.processZodType(inputSchema);
exports.createMcpCompatibleInputSchema = createMcpCompatibleInputSchema;
const createMcpCompatibleInputShape = (inputSchema) => (0, exports.createMcpCompatibleInputSchema)(inputSchema).shape;
exports.createMcpCompatibleInputShape = createMcpCompatibleInputShape;
//# sourceMappingURL=McpSchemaCompatLayer.js.map