import { DANGEROUS_PATTERNS, MAX_EXPRESSION_LENGTH, compileJMESPath, validateJMESPathSecure } from "./jmespath-utils.js";
import { getLogger } from "./logger.js";
import * as jmespath from "jmespath";

//#region src/utils/JsonTransformer.ts
const logger = getLogger("JsonTransformer");
var JsonTransformer = class JsonTransformer {
	static DEFAULT_TIMEOUT = 5e3;
	/**
	* Validate JMESPath expression for security and correctness
	*/
	static validateExpression(expression, _allowedFunctions) {
		if (!expression || typeof expression !== "string") throw new Error("JMESPath expression must be a non-empty string");
		if (expression.length > MAX_EXPRESSION_LENGTH) throw new Error(`JMESPath expression too long (max ${MAX_EXPRESSION_LENGTH} characters)`);
		for (const pattern of DANGEROUS_PATTERNS) if (pattern.test(expression)) throw new Error(`JMESPath expression contains dangerous pattern: ${pattern.source}`);
		const result = validateJMESPathSecure(expression, {
			maxLength: MAX_EXPRESSION_LENGTH + 1,
			dangerousPatterns: []
		});
		if (!result.valid) throw new Error(`Invalid JMESPath syntax: ${result.error}`);
		logger.debug("JMESPath expression validated", `${expression.substring(0, 100)}...`);
	}
	/**
	* Execute JMESPath with timeout protection
	*/
	static executeWithTimeout(input, expression, timeoutMs) {
		return new Promise((resolve, reject) => {
			const timeout = setTimeout(() => {
				reject(/* @__PURE__ */ new Error(`JMESPath transformation timed out after ${timeoutMs}ms`));
			}, timeoutMs);
			try {
				const result = jmespath.search(input, expression);
				clearTimeout(timeout);
				resolve(result);
			} catch (error) {
				clearTimeout(timeout);
				reject(error);
			}
		});
	}
	/**
	* Transform input data using JMESPath expression with security validation
	*/
	static async transform(input, jmesPathExpression, options = {}) {
		const { timeout = JsonTransformer.DEFAULT_TIMEOUT, allowedFunctions } = options;
		JsonTransformer.validateExpression(jmesPathExpression, allowedFunctions);
		try {
			logger.debug("Executing JMESPath transformation", `inputType: ${typeof input}, expression: ${jmesPathExpression.substring(0, 100)}..., timeout: ${timeout}`);
			const result = await JsonTransformer.executeWithTimeout(input, jmesPathExpression, timeout);
			logger.debug("JMESPath transformation completed successfully", "");
			return result;
		} catch (error) {
			const message = error instanceof Error ? error.message : String(error);
			logger.error("JMESPath transformation failed", `expression: ${jmesPathExpression.substring(0, 100)}..., error: ${message}`);
			throw new Error(`JMESPath transformation failed for expression "${jmesPathExpression}": ${message}`);
		}
	}
	/**
	* Convert simple object transformation to JMESPath expression
	* For SDK convenience - converts { key: 'path' } to JMESPath
	*/
	static objectToJMESPath(objectTransformation) {
		if (!objectTransformation || typeof objectTransformation !== "object") throw new Error("Object transformation must be a non-null object");
		return `{ ${Object.entries(objectTransformation).map(([key, path]) => {
			if (!key || typeof key !== "string") throw new Error("Object transformation keys must be non-empty strings");
			if (!path || typeof path !== "string") throw new Error("Object transformation values must be non-empty strings");
			try {
				compileJMESPath(path);
			} catch (error) {
				throw new Error(`Invalid JMESPath in object transformation value "${path}": ${error instanceof Error ? error.message : String(error)}`);
			}
			return `${key}: ${path}`;
		}).join(", ")} }`;
	}
	/**
	* Transform using either direct JMESPath string or object transformation
	* Supports both SDK patterns
	*/
	static async transformWithConfig(input, config, options = {}) {
		if (config.jmespath) return JsonTransformer.transform(input, config.jmespath, options);
		if (config.objectTransformation) {
			const jmesPath = JsonTransformer.objectToJMESPath(config.objectTransformation);
			return JsonTransformer.transform(input, jmesPath, options);
		}
		throw new Error("Either jmespath or objectTransformation must be provided");
	}
	/**
	* Synchronous transform method for backward compatibility
	* WARNING: This bypasses security validation - use async transform() instead
	* @deprecated Use async transform() method instead
	*/
	static transformSync(input, jmesPathExpression) {
		logger.warn("Using deprecated synchronous transform method - security validation bypassed", "");
		try {
			return jmespath.search(input, jmesPathExpression);
		} catch (error) {
			throw new Error(`JMESPath transformation failed: ${error instanceof Error ? error.message : String(error)}`);
		}
	}
};

//#endregion
export { JsonTransformer };