"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const mcpMablTool_1 = require("./mcpMablTool");
const zod_1 = require("zod");
const common_1 = require("../utils/common");
const featureSet_1 = require("@mablhq-internal/runtime/api/featureSet");
const analyzeFailure = (0, mcpMablTool_1.defineTool)({
    schema: {
        name: 'analyze_failure',
        title: 'Analyze a mabl test or plan execution failure',
        description: 'Get a GenAI analysis of why a test or plan execution failed. Example: Tell me why the this test/plan failed',
        inputSchema: zod_1.z.object({
            runId: zod_1.z
                .string()
                .describe('The runId of the failed test run or plan run to analyze'),
            testOrPlan: zod_1.z
                .enum(['test', 'plan'])
                .describe("Specify 'test' for test run, 'plan' for plan run"),
        }),
        type: 'readOnly',
    },
    handle: async (params, context, server) => {
        const { mablApiClient, workspaceId } = context.getCurrentContext();
        const { runId, testOrPlan } = params;
        const hasAiAvailable = context.featureIsAvailable(featureSet_1.GENERATIVE_AI_FEATURE_FLAG) &&
            context.featureIsAvailable(featureSet_1.GENERATIVE_AI_FAILURE_ANALYSIS_FEATURE_FLAG);
        if (!hasAiAvailable) {
            return (0, common_1.stringToToolResult)('Failure Analysis with AI is not available for your account. Please contact your workspace owner or mabl support for assistance in activating this feature.', true);
        }
        if (runId.endsWith('-j')) {
            return (0, common_1.stringToToolResult)(`The runId ${runId} appears to be a test id. Please call the getResults tool with this id first, then call analyze-failure again with the resulting first runId with status "Failed".`, true);
        }
        if (runId.endsWith('-p')) {
            return (0, common_1.stringToToolResult)(`The runId ${runId} appears to be a plan id. Please call the getPlanResults tool with this id first, then call analyze-failure again with the resulting first planRunId with status "Failed".`, true);
        }
        if (testOrPlan === 'plan') {
            return analyzePlanRunFailure(runId, mablApiClient, server, workspaceId);
        }
        return analyzeTestRunFailure(runId, mablApiClient, server, workspaceId);
    },
});
async function analyzeTestRunFailure(runId, mablApiClient, server, workspaceId) {
    let errorMessage;
    const testRun = await mablApiClient.getTestRun(runId);
    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') {
                await server?.notification({
                    method: 'notifications/message',
                    params: {
                        level: 'info',
                        data: `Analyzing test run ${testRun.id}`,
                    },
                });
                const testRunAnalysisResponse = await mablApiClient.analyzeTestRun(workspaceId, {
                    test_run_id: testRun.id,
                    save_summary: true,
                });
                errorMessage = testRunAnalysisResponse?.summary;
            }
        }
        catch (e) {
            console.error('Error analyzing test run:', e);
            errorMessage = `Analysis error: ${e instanceof Error ? e.message : String(e)}`;
        }
    }
    if (!errorMessage) {
        errorMessage =
            testRun.failure_summary?.error || 'No error message available.';
    }
    return {
        content: [
            {
                type: 'text',
                text: errorMessage,
            },
        ],
    };
}
async function analyzePlanRunFailure(runId, mablApiClient, server, workspaceId) {
    let errorMessage;
    const planRun = await mablApiClient.getPlanRun(runId);
    if (planRun.status === mablApi_1.PlanRun.StatusEnum.Failed) {
        try {
            const analysisResponse = await mablApiClient.getPlanRunFailureAnalysis(workspaceId, planRun.id);
            errorMessage = analysisResponse?.analysis?.summary_text;
            if (!analysisResponse || analysisResponse.status !== 'done') {
                await server.notification({
                    method: 'notifications/message',
                    params: {
                        level: 'info',
                        data: `Analyzing plan run ${planRun.id}`,
                    },
                });
                const planRunAnalysisResponse = await mablApiClient.analyzePlanRun(workspaceId, {
                    plan_run_id: planRun.id,
                    save_summary: true,
                });
                errorMessage = planRunAnalysisResponse?.summary;
            }
        }
        catch (e) {
            console.error('Error analyzing plan run:', e);
            errorMessage = `Analysis error: ${e instanceof Error ? e.message : String(e)}`;
        }
    }
    if (!errorMessage) {
        errorMessage = planRun.status_cause || 'No error message available.';
    }
    return {
        content: [
            {
                type: 'text',
                text: errorMessage,
            },
        ],
    };
}
exports.default = [analyzeFailure];
