"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const zod_1 = require("zod");
const mcpMablTool_1 = require("./mcpMablTool");
const trainingSessions_1 = require("@mablhq-internal/runtime/core/trainer/trainingSessions");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const common_1 = require("../utils/common");
const featureSet_1 = require("@mablhq-internal/runtime/api/featureSet");
const testUtils_1 = require("../utils/testUtils");
const runCloudTestGeneration_1 = require("@mablhq-internal/runtime/trainer/cli/runCloudTestGeneration");
const createMablTestFromPlan = (0, mcpMablTool_1.defineTool)({
    schema: {
        name: 'create_mabl_test_from_plan',
        title: 'Create a mabl test from a plan artifact created by the #plan_new_test tool',
        description: 'Create a mabl test from a plan artifact created by the #plan_new_test tool. Example: Create a mabl test from a plan artifact created by the #plan_new_test tool. This tool can only be called after calling #plan_new_test as it needs the artifact created by the #plan_new_test tool. Set mode to "cloud" to run test generation in the mabl cloud instead of locally.',
        inputSchema: zod_1.z.object({
            mode: zod_1.z
                .enum(['local', 'cloud'])
                .describe('Test generation mode: "local" runs locally (default), "cloud" runs in the mabl cloud and returns session/instance IDs for polling status with #get_cloud_test_gen_status.')
                .optional()
                .default('local'),
        }),
        type: 'readOnly',
    },
    handle: async (params, context) => {
        const { mablApiClient, workspaceId, planHistory } = context.getCurrentContext();
        if (!context.featureIsAvailable(featureSet_1.GENERATIVE_AI_FEATURE_FLAG)) {
            return (0, common_1.stringToToolResult)('Generative AI is not available for your account. Please contact your workspace owner or mabl support for assistance in activating this feature.', true);
        }
        const { lastArtifact: artifact, trainingSessionId } = planHistory.getPlanHistoryState();
        if (!artifact) {
            return (0, common_1.stringToToolResult)('No artifact found. Please call #plan_new_test first to create a plan artifact.', true);
        }
        let url = artifact?.test_information?.url_override;
        if (!url && artifact?.test_information?.deployment_id) {
            const deployment = await mablApiClient.getDeploymentEntity(artifact?.test_information?.deployment_id);
            url = deployment.uri;
        }
        const planningArtifacts = (0, runCloudTestGeneration_1.buildPlanningArtifacts)(artifact);
        const initiateRequest = {
            is_cloud: params.mode === 'cloud',
            planning_artifacts: planningArtifacts,
            planning_messages: [],
            application_id: artifact?.test_information?.application_id,
            environment_id: artifact?.test_information?.environment_id,
        };
        const initiateResponse = await mablApiClient.initiateTestAuthoringSession(workspaceId, initiateRequest);
        if (params.mode === 'cloud') {
            planHistory.reset();
            const result = {
                sessionId: initiateResponse.session_id,
                instanceId: initiateResponse.instance_id,
            };
            return {
                content: [
                    {
                        type: 'text',
                        text: `Cloud test generation initiated from plan.\n\nSession ID: ${result.sessionId}\nInstance ID: ${result.instanceId ?? 'pending'}\n\nUse #get_cloud_test_gen_status to check the status of the test generation.`,
                    },
                ],
                structuredContent: result,
            };
        }
        const trainerUrl = await (0, trainingSessions_1.trainNewTest)({
            environmentId: artifact?.test_information?.environment_id,
            applicationId: artifact?.test_information?.application_id,
            credentialsId: artifact?.test_information?.credentials_id,
            url: url ?? '',
            testName: artifact?.test_information?.name ?? 'New Test',
            autoBranch: false,
            autoLogin: false,
            workspaceId,
            intent: artifact?.test_information?.test_case,
            testDescription: artifact?.test_information?.description || undefined,
            testType: artifact?.agent_state?.test_type === mablApi_1.TestTypeEnum.Api
                ? mablApi_1.TestTypeEnum.Api
                : mablApi_1.TestTypeEnum.Browser,
            apiDescription: artifact?.agent_state?.api_description,
            agentSessionId: initiateResponse.session_id,
            initialArtifacts: planningArtifacts,
            trainingSessionId,
            initialTestGenState: artifact?.agent_state
                ? {
                    agentState: artifact.agent_state,
                    publicAgentState: artifact.public_state,
                }
                : undefined,
        }, mablApiClient, false);
        planHistory.reset();
        return {
            content: [
                {
                    type: 'text',
                    text: (0, testUtils_1.getCreateTestOutputText)(trainerUrl),
                },
            ],
        };
    },
});
exports.default = [createMablTestFromPlan];
