"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 sessionHelpers_1 = require("@mablhq-internal/runtime/trainer/cli/sessionHelpers");
const testUtils_1 = require("../utils/testUtils");
const getCloudTestGenStatus = (0, mcpMablTool_1.defineTool)({
    schema: {
        name: 'get_cloud_test_gen_status',
        title: 'Get cloud test generation status',
        description: 'Check the status of a cloud test generation initiated by #create_mabl_test_cloud. Returns the current status, created test ID (if complete), and the latest model message.',
        inputSchema: zod_1.z.object({
            sessionId: zod_1.z
                .string()
                .describe('The agent session ID returned by create_mabl_test_cloud'),
            instanceId: zod_1.z
                .string()
                .describe('The cloud instance ID returned by create_mabl_test_cloud')
                .optional(),
        }),
        type: 'readOnly',
        outputSchema: zod_1.z.object({
            sessionStatus: zod_1.z
                .string()
                .describe('The status of the latest cloud instance (queued, running, completed, failed, terminated)')
                .optional(),
            createdTestId: zod_1.z
                .string()
                .describe('The ID of the test created by cloud generation')
                .optional(),
            viewTestUrl: zod_1.z
                .string()
                .describe('URL to view the created test in the mabl app')
                .optional(),
            latestModelMessage: zod_1.z
                .string()
                .describe('The latest message from the model/agent')
                .optional(),
        }),
    },
    handle: async (params, context) => {
        const { mablApiClient } = context.getCurrentContext();
        const agentSession = await mablApiClient.getAgentSession(params.sessionId);
        let instanceStatus;
        if (params.instanceId) {
            const cloudInstance = await mablApiClient.getAgentCloudInstance(params.sessionId, params.instanceId);
            instanceStatus = cloudInstance.status;
        }
        else if (agentSession.latest_instance_status) {
            instanceStatus = agentSession.latest_instance_status;
        }
        const createdTestId = (0, sessionHelpers_1.extractTestIdFromArtifacts)(agentSession.related_artifacts);
        let latestModelMessage;
        if (agentSession.messages?.length) {
            for (let i = agentSession.messages.length - 1; i >= 0; i--) {
                const message = agentSession.messages[i];
                if (message.role === mablApi_1.MessageRole.Model) {
                    const textParts = message.parts
                        ?.filter((part) => part.text)
                        .map((part) => part.text);
                    if (textParts?.length) {
                        latestModelMessage = textParts.join('\n');
                        break;
                    }
                }
            }
        }
        let viewTestUrl;
        if (createdTestId && agentSession.workspace_id) {
            viewTestUrl = (0, testUtils_1.getViewTestUrl)(agentSession.workspace_id, createdTestId);
        }
        const result = {
            sessionStatus: instanceStatus,
            createdTestId,
            viewTestUrl,
            latestModelMessage,
        };
        const lines = [];
        lines.push(`Session: ${params.sessionId}`);
        if (instanceStatus) {
            lines.push(`Status: ${instanceStatus}`);
        }
        if (createdTestId) {
            lines.push(`Created Test ID: ${createdTestId}`);
        }
        if (viewTestUrl) {
            lines.push(`View Test: ${viewTestUrl}`);
        }
        if (latestModelMessage) {
            lines.push(`\nLatest Agent Message:\n${latestModelMessage}`);
        }
        return {
            content: [
                {
                    type: 'text',
                    text: lines.join('\n'),
                },
            ],
            structuredContent: result,
        };
    },
});
exports.default = [getCloudTestGenStatus];
