"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkCloudTestGenStatus = checkCloudTestGenStatus;
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const constants_1 = require("../../constants");
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const sessionHelpers_1 = require("@mablhq-internal/runtime/trainer/cli/sessionHelpers");
const env_1 = require("@mablhq-internal/runtime/env/env");
const chalk = require('chalk');
const CommandArgSessionId = 'session-id';
const CommandArgInstanceId = 'instance-id';
exports.command = 'cloud-status';
exports.describe =
    'Check the status of a cloud test generation initiated by create --mode cloud';
exports.builder = (yargs) => {
    yargs
        .option(CommandArgSessionId, {
        describe: 'The agent session ID from create --mode cloud',
        nargs: 1,
        type: 'string',
        demandOption: true,
    })
        .option(CommandArgInstanceId, {
        describe: 'The cloud instance ID from create --mode cloud',
        nargs: 1,
        type: 'string',
    })
        .option(constants_1.CommandArgOutput, {
        describe: 'Output format: "json" for machine-readable output',
        nargs: 1,
        type: 'string',
    });
};
exports.handler = (0, cliUtil_1.failWrapper)(checkCloudTestGenStatus);
async function checkCloudTestGenStatus(parsed) {
    const sessionId = parsed[CommandArgSessionId];
    const instanceId = parsed[CommandArgInstanceId];
    const outputJson = parsed.output === 'json';
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const agentSession = await apiClient.getAgentSession(sessionId);
    let instanceStatus;
    if (instanceId) {
        const cloudInstance = await apiClient.getAgentCloudInstance(sessionId, 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 viewTestUrl;
    if (createdTestId && agentSession.workspace_id) {
        viewTestUrl = `${env_1.BASE_APP_URL}/workspaces/${agentSession.workspace_id}/train/tests/${createdTestId}/current`;
    }
    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;
                }
            }
        }
    }
    const result = {
        sessionId,
        instanceId,
        status: instanceStatus,
        createdTestId,
        viewTestUrl,
        latestModelMessage,
    };
    if (outputJson) {
        console.log(JSON.stringify(result, undefined, 2));
    }
    else {
        console.log(chalk.cyan('\nCloud Test Generation Status'));
        console.log(chalk.gray('  Session ID:'), chalk.white(sessionId));
        if (instanceId) {
            console.log(chalk.gray('  Instance ID:'), chalk.white(instanceId));
        }
        if (instanceStatus) {
            const statusColor = instanceStatus === 'completed'
                ? chalk.green
                : instanceStatus === 'failed' || instanceStatus === 'terminated'
                    ? chalk.red
                    : chalk.yellow;
            console.log(chalk.gray('  Status:'), statusColor(instanceStatus));
        }
        if (createdTestId) {
            console.log(chalk.gray('  Created Test ID:'), chalk.white(createdTestId));
        }
        if (viewTestUrl) {
            console.log(chalk.gray('  View Test:'), chalk.cyan(viewTestUrl));
        }
        if (latestModelMessage) {
            console.log(chalk.gray('\n  Latest Agent Message:'));
            console.log(`  ${latestModelMessage}`);
        }
    }
    return 'done';
}
