"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTaskAttemptOpenCommand = createTaskAttemptOpenCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const task_attempts_1 = require("../../../lib/planning/task-attempts");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createTaskAttemptOpenCommand() {
    const { Command } = await import("commander");
    const command = new Command("attempt-open");
    command
        .description("Preview or atomically open one readiness-bound canonical implementation attempt without fabricating evidence.")
        .requiredOption("--task-definition <path>", "Repository-relative canonical task-definition.md path.")
        .requiredOption("--attempt-id <identity>", "Stable canonical attempt_id using 3-128 machine-safe characters.")
        .requiredOption("--opened-at <timestamp>", "ISO-8601 attempt opening time with explicit timezone.")
        .option("--dry-run", "Preview exact pair preconditions and attempt evidence without mutation; omit to apply.")
        .action((_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)((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, task_attempts_1.previewTaskAttemptOpenSync)({
                repositoryRoot: repository.root,
                taskDefinitionPath: options.taskDefinition,
                attemptId: options.attemptId,
                openedAt: options.openedAt
            });
            result = options.dryRun === true ? preview : (0, task_attempts_1.applyTaskAttemptOpenSync)(preview);
        }
        catch (error) {
            if (error instanceof task_attempts_1.TaskAttemptOpenError) {
                if (error.code === "opened-at-in-future") {
                    throw new errors_1.RuntimeError({
                        message: "Task attempt-open rejected a future opened_at timestamp.",
                        code: "ATTEMPT_OPENED_AT_IN_FUTURE",
                        exitCode: errors_1.RuntimeExitCode.USAGE,
                        writeOutcome: "no-writes",
                        details: [
                            error.message,
                            "No task-definition or implementation-summary bytes were changed."
                        ],
                        recoveryActions: [(0, errors_1.createNonCallableRecoveryAction)({
                                id: "recovery.task-attempt-open.correct-opened-at",
                                command: "task attempt-open",
                                explanation: "Supply the intended current or past opened_at instant and preview the attempt again.",
                                reason: "The shared boundary cannot infer the caller's intended timezone or timestamp."
                            })]
                    });
                }
                throw (0, errors_1.createUsageError)(error.message, [
                    `Attempt-open failure class: ${error.code}`,
                    "No attempt evidence was inferred; refresh readiness and the task pair before retrying."
                ]);
            }
            throw error;
        }
        if (result.writeOutcome !== "previewed" && result.writeOutcome !== "committed") {
            throw (0, errors_1.createUsageError)(`Task attempt open ended with '${result.writeOutcome}'.`, [
                ...(result.failure === null ? [] : [result.failure]),
                ...(result.recoveryPath === null ? [] : [`Recovery record: ${result.recoveryPath}`]),
                ...result.conflicts.map((conflict) => `${conflict.path}: ${conflict.guidance}`)
            ]);
        }
        (0, output_1.emitSuccess)({
            command: "task attempt-open",
            format,
            text: renderText(result),
            data: {
                ...result,
                repositoryRoot: repository.root,
                detectionSource: repository.detectionSource,
                nextAction: result.writeOutcome === "previewed"
                    ? "Apply task attempt-open without --dry-run after confirming the exact pair preconditions."
                    : "Capture the attempt baseline before runtime or hybrid implementation writes when attribution is required."
            }
        });
    });
    return command;
}
function renderText(result) {
    return [
        "Task implementation attempt open",
        "",
        `Task definition: ${result.taskDefinitionPath}`,
        `Implementation summary: ${result.implementationSummaryPath}`,
        `Attempt ID: ${result.attemptId}`,
        `Opened at: ${result.openedAtInstant}`,
        `Chronology observed at: ${result.observedAt}`,
        `Readiness review ID: ${result.readinessReviewId}`,
        `Materialization: ${result.materialization}`,
        `Predecessor attempt: ${result.predecessorAttemptId ?? "none"}`,
        `Chronology recovery: ${result.chronologyRecoveryId ?? "none"}`,
        `Write outcome: ${result.writeOutcome}`,
        `Changed paths: ${result.changedPaths.length}`,
        "Evidence gaps:",
        ...(result.evidenceGaps.length === 0 ? ["- None."] : result.evidenceGaps.map((gap) => `- ${gap}`))
    ].join("\n");
}
