"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkTaskCommand = createWorkTaskCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const work_creation_1 = require("../../../lib/work-creation");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
const registration_1 = require("../registration");
async function createWorkTaskCommand() {
    const { Command } = await import('commander');
    const command = new Command('task');
    command.description('Create and manage direct Structured child tasks.');
    (0, registration_1.registerCommand)(command, await createWorkTaskCreateCommand());
    return command;
}
async function createWorkTaskCreateCommand() {
    const { Command } = await import('commander');
    const command = new Command('create');
    command
        .description('Preview or create ordered direct task-definition and implementation-summary pairs for Structured work.')
        .requiredOption('--overview <path>', 'Canonical Structured work overview path.')
        .option('--task <json>', 'Structured task JSON object; repeat in dependency order.', collectValue, [])
        .option('--dry-run', 'Preview task pairs and mutation preconditions without writing.')
        .action((_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)(commandInstance.parent?.parent?.parent?.opts?.().format ?? (0, global_format_1.getGlobalFormat)(commandInstance));
        if (format === null)
            throw (0, errors_1.createUsageError)('Output format must be one of: text, json.');
        const repository = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        let result;
        try {
            const preview = (0, work_creation_1.previewStructuredTaskPairCreationSync)({
                repositoryRoot: repository.root,
                overviewPath: options.overview,
                tasks: options.task.map(parseTaskInput),
            });
            result = options.dryRun === true ? preview : (0, work_creation_1.applyStructuredTaskPairCreationSync)(preview);
        }
        catch (error) {
            throw normalizeWorkTaskCreateError(error);
        }
        if (result.writeOutcome !== 'previewed' && result.writeOutcome !== 'committed') {
            throw createTaskPairOutcomeError(result);
        }
        (0, output_1.emitSuccess)({
            command: 'work task create',
            format,
            text: renderSuccessText(result),
            data: result,
        });
    });
    return command;
}
function collectValue(value, previous) {
    return [...previous, value];
}
function parseTaskInput(value) {
    let parsed;
    try {
        parsed = JSON.parse(value);
    }
    catch {
        throw new work_creation_1.StructuredWorkCreationError('invalid-request', 'Each --task value must be a valid JSON object.');
    }
    if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
        throw new work_creation_1.StructuredWorkCreationError('invalid-request', 'Each --task value must be a JSON object.');
    }
    return parsed;
}
function normalizeWorkTaskCreateError(error) {
    if (error instanceof errors_1.RuntimeError)
        return error;
    if (error instanceof work_creation_1.StructuredWorkCreationError) {
        const conflict = error.code === 'destination-conflict' || error.code === 'stale-preview';
        return new errors_1.RuntimeError({
            message: error.message,
            code: `WORK_TASK_CREATE_${error.code.toUpperCase().replace(/-/g, '_')}`,
            exitCode: conflict ? errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT : errors_1.RuntimeExitCode.USAGE,
            details: [
                conflict
                    ? 'Refresh the Structured task-pair preview after inspecting current parent and destination evidence.'
                    : 'Correct the Structured overview, ordered task graph, task contract, or policy input before retrying.',
            ],
        });
    }
    if (error instanceof Error)
        return (0, errors_1.createUsageError)(error.message, ['No Structured task-pair write was accepted.']);
    return (0, errors_1.createUsageError)('Invalid Structured task-pair creation input.');
}
function createTaskPairOutcomeError(result) {
    const details = [
        `workId: ${result.workId}`,
        `overviewPath: ${result.overviewPath}`,
        `writeOutcome: ${result.writeOutcome}`,
        `nextAction: ${result.nextAction}`,
        ...(result.recoveryPath === null ? [] : [`recoveryPath: ${result.recoveryPath}`]),
    ];
    if (result.writeOutcome === 'conflict') {
        return new errors_1.RuntimeError({
            message: 'Structured task-pair creation preview is stale.',
            code: 'WORK_TASK_CREATE_CONFLICT',
            exitCode: errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT,
            details,
        });
    }
    if (result.writeOutcome === 'incomplete') {
        return new errors_1.RuntimeError({
            message: 'Structured task-pair creation stopped after a partial repository mutation.',
            code: 'WORK_TASK_CREATE_INCOMPLETE',
            exitCode: errors_1.RuntimeExitCode.PARTIAL_MUTATION,
            writeOutcome: 'partial',
            details,
            recoveryActions: [
                (0, errors_1.createNonCallableRecoveryAction)({
                    id: 'recovery.inspect-work-task-create-transaction',
                    explanation: 'Inspect retained transaction evidence before retrying Structured task-pair creation.',
                    reason: result.recoveryPath ?? 'The retained transaction path was unavailable.',
                }),
            ],
        });
    }
    return new errors_1.RuntimeError({
        message: 'Structured task-pair creation did not write its intended task pairs.',
        code: 'WORK_TASK_CREATE_NO_WRITE',
        exitCode: errors_1.RuntimeExitCode.ERROR,
        details,
    });
}
function renderSuccessText(result) {
    return [
        result.writeOutcome === 'previewed' ? 'Previewed Structured task-pair creation.' : 'Created Structured task pairs.',
        `Workflow level: ${result.workflowLevel}`,
        `Work id: ${result.workId}`,
        `Overview path: ${result.overviewPath}`,
        `Tasks: ${result.tasks.map((task) => `${task.sequencePrefix}:${task.taskId}:${task.orderedTaskRootName}`).join(', ')}`,
        `Task inventory fingerprint: ${result.taskInventoryFingerprint}`,
        `Intended paths: ${result.intendedPaths.join(', ')}`,
        `Changed paths: ${result.changedPaths.join(', ') || 'none'}`,
        `Write outcome: ${result.writeOutcome}`,
        `Transaction id: ${result.transactionId ?? 'none'}`,
        `Recovery path: ${result.recoveryPath ?? 'none'}`,
        `Next action: ${result.nextAction}`,
    ].join('\n');
}
