"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createValidateWorkflowCodeTool = void 0;
const zod_1 = __importDefault(require("zod"));
const mcp_constants_1 = require("../../mcp.constants");
const workflow_validation_utils_1 = require("../workflow-validation.utils");
const constants_1 = require("./constants");
const inputSchema = {
    code: zod_1.default
        .string()
        .describe('Full TypeScript/JavaScript workflow code using the n8n Workflow SDK. Must include the workflow export.'),
};
const outputSchema = {
    valid: zod_1.default.boolean().describe('Whether the workflow code is valid'),
    nodeCount: zod_1.default.number().optional().describe('The number of nodes in the workflow (if valid)'),
    warnings: zod_1.default
        .array(zod_1.default.object({
        code: zod_1.default.string().describe('The warning code identifying the type of warning'),
        message: zod_1.default.string().describe('The warning message'),
        nodeName: zod_1.default.string().optional().describe('The node that triggered the warning'),
        parameterPath: zod_1.default
            .string()
            .optional()
            .describe('The parameter path that triggered the warning'),
    }))
        .optional()
        .describe('Validation warnings (if any)'),
    errors: zod_1.default.array(zod_1.default.string()).optional().describe('Validation errors (if invalid)'),
    hint: zod_1.default
        .string()
        .optional()
        .describe('Actionable hint for recovering from the error. When present, follow the suggested action before retrying.'),
};
const createValidateWorkflowCodeTool = (user, telemetry) => ({
    name: constants_1.CODE_BUILDER_VALIDATE_TOOL.toolName,
    config: {
        description: 'Validate n8n Workflow SDK code. Parses the code into a workflow and checks for errors. Returns the workflow JSON if valid, or detailed error messages to fix. Always validate before creating a workflow.',
        inputSchema,
        outputSchema,
        annotations: {
            title: constants_1.CODE_BUILDER_VALIDATE_TOOL.displayTitle,
            readOnlyHint: true,
            destructiveHint: false,
            idempotentHint: true,
            openWorldHint: false,
        },
    },
    handler: async ({ code }) => {
        const telemetryPayload = {
            user_id: user.id,
            tool_name: constants_1.CODE_BUILDER_VALIDATE_TOOL.toolName,
            parameters: { codeLength: code.length },
        };
        try {
            const { ParseValidateHandler, stripImportStatements } = await Promise.resolve().then(() => __importStar(require('@n8n/ai-workflow-builder')));
            const handler = new ParseValidateHandler({ generatePinData: false });
            const strippedCode = stripImportStatements(code);
            const result = await handler.parseAndValidate(strippedCode);
            telemetryPayload.results = {
                success: true,
                data: {
                    nodeCount: result.workflow.nodes.length,
                    warningCount: result.warnings.length,
                },
            };
            telemetry.track(mcp_constants_1.USER_CALLED_MCP_TOOL_EVENT, telemetryPayload);
            const response = {
                valid: true,
                nodeCount: result.workflow.nodes.length,
            };
            if (result.warnings.length > 0) {
                response.warnings = result.warnings;
            }
            return {
                content: [{ type: 'text', text: JSON.stringify(response, null, 2) }],
                structuredContent: response,
            };
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            telemetryPayload.results = {
                success: false,
                error: errorMessage,
            };
            telemetry.track(mcp_constants_1.USER_CALLED_MCP_TOOL_EVENT, telemetryPayload);
            const hint = (0, workflow_validation_utils_1.getSdkReferenceHint)(error);
            const output = {
                valid: false,
                errors: [errorMessage],
                ...(hint ? { hint } : {}),
            };
            return {
                content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
                structuredContent: output,
                isError: true,
            };
        }
    },
});
exports.createValidateWorkflowCodeTool = createValidateWorkflowCodeTool;
//# sourceMappingURL=validate-workflow-code.tool.js.map