"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 cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
const util_1 = require("../../../commandUtil/util");
const CommandArgPlanningSessionId = 'planning-session-id';
const CommandArgTestInformation = 'test-information';
const CommandArgPlan = 'plan';
const CommandArgTestType = 'test-type';
const CommandArgApiSpec = 'api-spec';
const CommandArgMode = 'mode';
exports.command = 'initiate';
exports.describe =
    'Start test authoring from a planning session or direct test information';
exports.builder = (yargs) => yargs
    .option(CommandArgPlanningSessionId, {
    describe: 'Planning session ID from "mabl agent authoring plan". Mutually exclusive with --test-information.',
    type: 'string',
})
    .option(CommandArgTestInformation, {
    describe: 'JSON string with test information (name, test_case, deployment_id or url_override, etc.). Mutually exclusive with --planning-session-id.',
    type: 'string',
})
    .option(CommandArgPlan, {
    describe: 'Markdown test plan/outline. Only valid with --test-information.',
    type: 'string',
})
    .option(CommandArgTestType, {
    describe: 'Type of test to create.',
    choices: ['browser', 'api'],
    default: 'browser',
})
    .option(CommandArgApiSpec, {
    describe: 'API specification (OpenAPI/Swagger). Required when --test-type is api.',
    type: 'string',
})
    .option(CommandArgMode, {
    describe: 'Execution mode. Cloud is recommended (parallelizable). Local is for testing locally running apps.',
    choices: ['cloud', 'local'],
    default: 'cloud',
})
    .check((argv) => {
    if (!argv[CommandArgPlanningSessionId] && !argv[CommandArgTestInformation]) {
        throw new Error('Either --planning-session-id or --test-information is required.');
    }
    if (argv[CommandArgPlanningSessionId] && argv[CommandArgTestInformation]) {
        throw new Error('Provide either --planning-session-id or --test-information, not both.');
    }
    if (argv[CommandArgPlan] && argv[CommandArgPlanningSessionId]) {
        throw new Error('--plan is only valid with --test-information, not --planning-session-id.');
    }
    if (argv[CommandArgTestType] === 'api' && !argv[CommandArgApiSpec]) {
        throw new Error('--api-spec is required when --test-type is api.');
    }
    return true;
});
exports.handler = (0, cliUtil_1.failWrapper)(runInitiate);
async function runInitiate(parsed) {
    const apiClient = await mablApiClientFactory_1.MablApiClientFactory.createApiClient();
    const workspaceId = await (0, util_1.getWorkspaceId)(parsed);
    const request = buildInitiateRequest(parsed);
    console.error(`Initiating ${parsed[CommandArgTestType]} test authoring (${parsed[CommandArgMode]})...`);
    const response = await apiClient.initiateTestAuthoringSession(workspaceId, request);
    if (!response.session_id) {
        throw new Error('Failed to initiate authoring session: no session_id in response.');
    }
    const viewTaskUrl = `${env_1.BASE_APP_URL}/workspaces/${workspaceId}/agents/tasks/${response.session_id}`;
    const result = {
        sessionId: response.session_id,
        instanceId: response.instance_id,
        viewTaskUrl,
        mode: parsed[CommandArgMode],
    };
    console.log(JSON.stringify(result, undefined, 2));
    if (parsed[CommandArgMode] === 'cloud') {
        console.error('Use "mabl agent authoring status --session-id %s" to check progress.', response.session_id);
    }
    else {
        console.error('Local session created. Open the mabl desktop app to see authoring progress.');
    }
}
function buildInitiateRequest(parsed) {
    if (parsed[CommandArgPlanningSessionId]) {
        return {
            parent_session_id: parsed[CommandArgPlanningSessionId],
            is_cloud: parsed[CommandArgMode] === 'cloud',
        };
    }
    let testInfo;
    try {
        testInfo = JSON.parse(parsed[CommandArgTestInformation]);
    }
    catch {
        throw new Error('Invalid --test-information JSON. Expected format: {"name": "...", "test_case": "...", "deployment_id": "..."}');
    }
    if (!testInfo.name || !testInfo.test_case) {
        throw new Error('--test-information must include "name" and "test_case" fields.');
    }
    if (!testInfo.deployment_id && !testInfo.url_override) {
        throw new Error('--test-information must include either "deployment_id" or "url_override".');
    }
    if (parsed[CommandArgTestType] === 'api' && parsed[CommandArgApiSpec]) {
        testInfo.test_case = `${testInfo.test_case}\n\nAPI Specification:\n${parsed[CommandArgApiSpec]}`;
    }
    return {
        test_information: testInfo,
        plan: parsed[CommandArgPlan],
        is_cloud: parsed[CommandArgMode] === 'cloud',
        application_id: testInfo.application_id,
        environment_id: testInfo.environment_id,
    };
}
