"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLatestTestRunsOutputSchema = void 0;
const mcpMablTool_1 = require("./mcpMablTool");
const zod_1 = require("zod");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const common_1 = require("../utils/common");
exports.getLatestTestRunsOutputSchema = zod_1.z.object({
    testResults: zod_1.z.array(zod_1.z.object({
        testRunId: zod_1.z.string().nullable(),
        environmentId: zod_1.z.string().optional().nullable(),
        status: zod_1.z.string().nullable(),
        completedTimeMs: zod_1.z.number().nullable(),
        errorMessage: zod_1.z.string(),
    })),
});
const getLatestTestRuns = (0, mcpMablTool_1.defineTool)({
    schema: {
        name: 'get_latest_test_runs',
        title: 'Get recent mabl test run results',
        description: 'Get the recent execution results for a mabl test by testId. Example: Can you fetch the latest results for the test "Mabl login"?',
        inputSchema: zod_1.z.object({
            testId: zod_1.z
                .string()
                .describe('The id of the mabl test to get recent results of'),
        }),
        type: 'readOnly',
        outputSchema: exports.getLatestTestRunsOutputSchema,
    },
    handle: async (params, context) => {
        const { mablApiClient, workspaceId } = context.getCurrentContext();
        const testId = params.testId;
        if (!testId) {
            return (0, common_1.stringToToolResult)('testId is required.', true);
        }
        const testRunResults = (await mablApiClient.getRecentTestRunsForTest(testId))
            .test_script_executions || [];
        if (!testRunResults.length) {
            return (0, common_1.stringToToolResult)('No test runs found for the given testId.', true);
        }
        const processedResults = await Promise.all(testRunResults.map(async (testRun) => {
            let errorMessage;
            if (testRun.status === mablApi_1.TestRun.StatusEnum.Failed) {
                try {
                    const analysisResponse = await mablApiClient.getTestRunFailureAnalysis(workspaceId, testRun.id ?? '');
                    errorMessage = analysisResponse?.analysis?.summary_text;
                    if (!analysisResponse || analysisResponse.status !== 'done') {
                        const testRunAnalysisResponse = await mablApiClient.analyzeTestRun(workspaceId, {
                            test_run_id: testRun.id,
                            save_summary: true,
                        });
                        errorMessage = testRunAnalysisResponse?.summary;
                    }
                }
                catch (e) {
                    errorMessage = `Analysis error: ${e instanceof Error ? e.message : String(e)}`;
                }
            }
            if (!errorMessage) {
                errorMessage =
                    testRun.failure_summary?.error || 'No error message available.';
            }
            const id = testRun.id;
            const completedTimeMs = testRun.completed_time;
            const status = testRun.status;
            const envId = testRun.journey_parameters?.deployment?.environment_id;
            return {
                testRunId: id,
                environmentId: envId,
                status,
                completedTimeMs,
                errorMessage,
            };
        }));
        return {
            content: [
                {
                    type: 'text',
                    text: (0, common_1.jsonPrettyPrint)({ testResults: processedResults }),
                },
            ],
            structuredContent: { testResults: processedResults },
        };
    },
});
exports.default = [getLatestTestRuns];
