"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const util_1 = require("../../../commandUtil/util");
const uuid_1 = require("uuid");
const authoringUtil_1 = require("./authoringUtil");
const CommandArgIntent = 'intent';
const CommandArgSessionId = 'session-id';
const CommandArgChanges = 'changes';
exports.command = 'plan';
exports.describe =
    'Start or continue a test planning conversation with the mabl AI planning agent';
exports.builder = (yargs) => yargs
    .option(CommandArgIntent, {
    describe: 'Detailed description of what the test should do. Required for starting a new session.',
    type: 'string',
})
    .option(CommandArgSessionId, {
    describe: 'Planning session ID from a previous plan call. Required for follow-up changes.',
    type: 'string',
})
    .option(CommandArgChanges, {
    describe: 'Changes to request for an existing plan. Requires --session-id.',
    type: 'string',
})
    .check((argv) => {
    if (!argv[CommandArgSessionId] && !argv[CommandArgIntent]) {
        throw new Error('Either --intent (for a new session) or --session-id + --changes (for a follow-up) is required.');
    }
    if (argv[CommandArgSessionId] && !argv[CommandArgChanges]) {
        throw new Error('--changes is required when providing --session-id for a follow-up.');
    }
    return true;
});
exports.handler = (0, cliUtil_1.failWrapper)(runPlan);
async function runPlan(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    let sessionId = parsed[CommandArgSessionId];
    if (!sessionId) {
        const initResponse = await apiClient.initiateTestPlanningSession(workspaceId);
        if (!initResponse.session_id) {
            throw new Error('Failed to create planning session: no session_id in response.');
        }
        sessionId = initResponse.session_id;
    }
    const messageText = parsed[CommandArgChanges] ?? parsed[CommandArgIntent];
    const userMessage = {
        id: (0, uuid_1.v4)(),
        role: mablApi_1.MessageRole.User,
        parts: [{ type: mablApi_1.MessagePartType.Text, text: messageText }],
        timestamp: Date.now(),
    };
    console.error('Planning...');
    const response = await apiClient.executeTestPlanNextStep(workspaceId, {
        agent_session_id: sessionId,
        new_messages: [userMessage],
    });
    if (!response.session_id) {
        throw new Error('Planning agent returned a malformed response: missing session_id.');
    }
    const { responseText, planContent, testInformation } = (0, authoringUtil_1.extractPlanningResponse)(response.new_messages ?? [], response.new_artifacts);
    const result = {
        planningSessionId: sessionId,
        response: responseText,
    };
    if (planContent) {
        result.planContent = planContent;
    }
    if (testInformation) {
        result.testInformation = testInformation;
    }
    console.log(JSON.stringify(result, undefined, 2));
}
