"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mcpMablTool_1 = require("./mcpMablTool");
const zod_1 = require("zod");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const common_1 = require("../utils/common");
const getLatestPlanRuns = (0, mcpMablTool_1.defineTool)({
    schema: {
        name: 'get_latest_plan_runs',
        title: 'Get latest mabl plan runs results',
        description: 'Get the latest mabl plan results for a planId. Example: Get the latest results for the mabl plan "App - Feature: Labels".',
        inputSchema: zod_1.z.object({
            planId: zod_1.z
                .string()
                .describe('The id of the mabl plan to get latest runs results of'),
        }),
        type: 'readOnly',
        outputSchema: zod_1.z.object({
            planResults: zod_1.z.array(zod_1.z.object({
                planRunId: zod_1.z.string().nullable(),
                status: zod_1.z.string().nullable(),
                completedTimeMs: zod_1.z.number().nullable(),
                errorMessage: zod_1.z.string(),
            })),
        }),
    },
    handle: async (params, context) => {
        const { mablApiClient, workspaceId } = context.getCurrentContext();
        const planId = params.planId;
        if (!planId) {
            return (0, common_1.stringToToolResult)('planId is required.', true);
        }
        const planRunResults = (await mablApiClient.getRecentPlanRunsForPlan(workspaceId, planId))
            .run_policy_executions || [];
        if (!planRunResults.length) {
            return (0, common_1.stringToToolResult)('No plan runs found for the given planId.', true);
        }
        const processedResults = await Promise.all(planRunResults.map(async (planRun) => {
            let errorMessage;
            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 !== mablApi_1.FailureAnalysisStatus.Done) {
                        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.';
            }
            const id = planRun.id;
            const completedTimeMs = planRun.completed_time;
            const status = planRun.status;
            return {
                planRunId: id,
                status,
                completedTimeMs,
                errorMessage,
            };
        }));
        return {
            content: [
                {
                    type: 'text',
                    text: (0, common_1.jsonPrettyPrint)({ planResults: processedResults }),
                },
            ],
            structuredContent: { planResults: processedResults },
        };
    },
});
exports.default = [getLatestPlanRuns];
