"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mablApiClientFactory_1 = require("@mablhq-internal/runtime/api/mablApiClientFactory");
const env_1 = require("@mablhq-internal/runtime/env/env");
const mablApi_1 = require("@mablhq-internal/runtime/mablApi");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const authoringUtil_1 = require("./authoringUtil");
const CommandArgSessionId = 'session-id';
const CommandArgVerbose = 'verbose';
const TERMINAL_STATUSES = new Set(['completed', 'failed', 'terminated']);
exports.command = 'status';
exports.describe = 'Check the status of a test authoring session';
exports.builder = (yargs) => yargs
    .option(CommandArgSessionId, {
    describe: 'The agent session ID from "mabl agent authoring initiate".',
    type: 'string',
    demandOption: true,
})
    .option(CommandArgVerbose, {
    describe: 'Show full details including latest agent message and test URL. Without this flag, only the status enum is returned for minimal output.',
    type: 'boolean',
    default: false,
});
exports.handler = (0, cliUtil_1.failWrapper)(runStatus);
async function runStatus(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const session = await apiClient.getAgentSession(parsed[CommandArgSessionId]);
    const status = session.latest_instance_status ?? 'unknown';
    const isTerminal = TERMINAL_STATUSES.has(status);
    const createdTestId = isTerminal || parsed[CommandArgVerbose]
        ? extractCreatedTestId(session.related_artifacts)
        : undefined;
    const viewTestUrl = createdTestId && session.workspace_id
        ? `${env_1.BASE_APP_URL}/workspaces/${session.workspace_id}/train/tests/${createdTestId}`
        : undefined;
    if (!parsed[CommandArgVerbose]) {
        const result = { sessionStatus: status };
        if (createdTestId) {
            result.createdTestId = createdTestId;
        }
        if (viewTestUrl) {
            result.viewTestUrl = viewTestUrl;
        }
        console.log(JSON.stringify(result));
        return;
    }
    const reversedMessages = [...(session.messages ?? [])].reverse();
    const lastModelMessage = reversedMessages.find((m) => m.role === mablApi_1.MessageRole.Model);
    const latestModelMessage = lastModelMessage
        ? (0, authoringUtil_1.extractAgentResponseText)([lastModelMessage]) || undefined
        : undefined;
    const result = {
        sessionStatus: status,
        createdTestId,
        viewTestUrl,
        latestModelMessage,
    };
    console.log(JSON.stringify(result, undefined, 2));
}
function extractCreatedTestId(artifacts) {
    for (const artifact of artifacts ?? []) {
        if (artifact.artifact_type === 'remote' &&
            (artifact.entity_kind === 'Test' || artifact.entity_kind === 'test')) {
            return artifact.entity_id;
        }
    }
    return undefined;
}
