import { getLogger } from "../../../logger.js";
import { z } from "@hono/zod-openapi";
import { convertZodToJsonSchemaWithPreview } from "@inkeep/agents-core/utils/schema-conversion";
import Ajv from "ajv";

//#region src/domains/run/utils/schema-validation.ts
const logger = getLogger("SchemaValidation");
const ajv = new Ajv({
	allErrors: true,
	strict: false
});
const validatorCache = /* @__PURE__ */ new Map();
/**
* Clear the validator cache to free memory
* Useful for testing or when memory usage becomes a concern
*/
function clearValidatorCache() {
	validatorCache.clear();
}
/**
* Get the current cache size for monitoring
*/
function getValidatorCacheSize() {
	return validatorCache.size;
}
/**
* Validate that a schema is valid (either JSON Schema or Zod)
* Following the same pattern as context validation
*/
function validateComponentSchema(schema, componentName) {
	try {
		if (schema instanceof z.ZodType) return {
			isValid: true,
			validatedSchema: convertZodToJsonSchemaWithPreview(schema)
		};
		if (!schema || typeof schema !== "object" || Array.isArray(schema)) return {
			isValid: false,
			error: "Schema must be a valid JSON Schema object or Zod schema"
		};
		const schemaKey = JSON.stringify(schema);
		let validator = validatorCache.get(schemaKey);
		if (!validator) {
			validator = ajv.compile(schema);
			validatorCache.set(schemaKey, validator);
		}
		return {
			isValid: true,
			validatedSchema: schema
		};
	} catch (error) {
		logger.error({
			componentName,
			error: error instanceof Error ? error.message : "Unknown error"
		}, "Invalid component schema");
		return {
			isValid: false,
			error: error instanceof Error ? error.message : "Invalid JSON Schema"
		};
	}
}
/**
* Extract preview fields from a schema (fields marked with inPreview: true)
*/
function extractPreviewFields(schema) {
	const previewProperties = {};
	if (schema.properties) {
		for (const [key, prop] of Object.entries(schema.properties)) if (prop.inPreview === true) {
			const cleanProp = { ...prop };
			delete cleanProp.inPreview;
			previewProperties[key] = cleanProp;
		}
	}
	return {
		type: "object",
		properties: previewProperties,
		required: schema.required?.filter((field) => previewProperties[field])
	};
}
/**
* Extract full fields from a schema (all fields, with inPreview flags removed)
*/
function extractFullFields(schema) {
	const fullProperties = {};
	if (schema.properties) for (const [key, prop] of Object.entries(schema.properties)) {
		const cleanProp = { ...prop };
		delete cleanProp.inPreview;
		fullProperties[key] = cleanProp;
	}
	return {
		type: "object",
		properties: fullProperties,
		required: schema.required
	};
}

//#endregion
export { clearValidatorCache, extractFullFields, extractPreviewFields, getValidatorCacheSize, validateComponentSchema };