"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mcpMablTool_1 = require("./mcpMablTool");
const zod_1 = require("zod");
const run_1 = require("../../../tests/tests_cmds/run");
const messaging_1 = require("@mablhq-internal/runtime/core/messaging/messaging");
const common_1 = require("../utils/common");
const testUtils_1 = require("../utils/testUtils");
const runTestOutputSchema = zod_1.z.object({
    Success: zod_1.z.boolean().describe('Whether the test run succeeded'),
    ErrorMessage: zod_1.z
        .string()
        .describe('Error message if the test failed, empty if succeeded'),
    Logs: zod_1.z.array(zod_1.z.string()).describe('All log lines in order'),
});
const runMablTestLocal = (0, mcpMablTool_1.defineTool)({
    schema: {
        name: 'run_mabl_test_local',
        title: 'Run a mabl test',
        description: 'Locally run a mabl test. Example: Run mabl test "Mabl Login" in environment Development using the "Admin user" credential',
        inputSchema: zod_1.z.object({
            environmentId: zod_1.z
                .string()
                .describe('The id of the environment to run the test in'),
            testId: zod_1.z.string().describe('The id of the test to run'),
            credentialsId: zod_1.z
                .string()
                .describe('Optional. The id of the credentials to use for running the test. If not provided, the user will be prompted to select from available non-cloud credentials.')
                .optional(),
            allowLocalTestBilling: zod_1.z
                .boolean()
                .describe('Optional. Allow execution of billable features like AI assertions in CLI runs. Defaults to false.')
                .optional(),
        }),
        type: 'destructive',
        outputSchema: runTestOutputSchema,
    },
    handle: async (params, context) => {
        messaging_1.mablEventEmitter.resetOutputEventChannel();
        const { mablApiClient, workspaceId } = context.getCurrentContext();
        const test = await mablApiClient.getJourney(params.testId);
        if (test.credentials_id && !params.credentialsId) {
            const error = await (0, testUtils_1.needCredentialsError)(mablApiClient, workspaceId);
            return (0, common_1.stringToToolResult)(error, true);
        }
        const logs = [];
        function logListener(line, _timestamp, _color, metadata) {
            if (!metadata?.shouldOutputInConsole) {
                return;
            }
            logs.push(line);
        }
        messaging_1.mablEventEmitter
            .getOutputEventChannel()
            .on(messaging_1.EventChannelMessageType.outputLogLine, logListener);
        const result = await (0, run_1.run)({
            id: params.testId,
            'environment-id': params.environmentId ?? '',
            'credentials-id': params.credentialsId ?? '',
            'allow-billable-features': params.allowLocalTestBilling ?? false,
            branch: 'master',
            'branch-changes-only': false,
            browser: 'chrome',
            'browser-disable-isolation': false,
            'browser-ignore-certificate-errors': false,
            'enable-link': false,
            headless: false,
            height: 1024,
            highlights: false,
            'keep-browser-open': false,
            'run-id': undefined,
            width: 1024,
            output: 'json',
            _: [],
            $0: '',
        }, false, mablApiClient);
        messaging_1.mablEventEmitter
            .getOutputEventChannel()
            .off(messaging_1.EventChannelMessageType.outputLogLine, logListener);
        const success = !!result.success;
        const errorMessage = success
            ? ''
            : result.testResults[0]?.errorMessage || 'Unknown error';
        return {
            content: [
                {
                    type: 'text',
                    text: `Test run ${success ? 'succeeded' : `failed ${errorMessage}`}`,
                },
                {
                    type: 'text',
                    text: `\n--- Logs ---\n` + logs.join('\n'),
                },
            ],
            structuredContent: {
                Success: success,
                ErrorMessage: errorMessage,
                Logs: logs,
            },
        };
    },
});
exports.default = [runMablTestLocal];
