"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTaskImplementationCompleteCommand = createTaskImplementationCompleteCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const task_implementation_completion_1 = require("../../../lib/planning/task-implementation-completion");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createTaskImplementationCompleteCommand() {
    const { Command } = await import("commander");
    const command = new Command("implementation-complete");
    command
        .description("Preview or atomically apply the revision-bound current-attempt implementation completion transition without changing review, closure, task, or reconciliation state.")
        .requiredOption("--task-definition <path>", "Repository-relative canonical task-definition.md path.")
        .requiredOption("--attempt-id <identity>", "Exact active implementation attempt identity.")
        .requiredOption("--task-revision <revision>", "Exact lowercase 64-character task revision.")
        .requiredOption("--completed-by <actor>", "Non-empty completion actor.")
        .requiredOption("--completed-at <timestamp>", "ISO-8601 completion time with explicit timezone.")
        .option("--dry-run", "Project the exact transition and typed findings without mutation.")
        .action((_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)((0, global_format_1.getGlobalFormat)(commandInstance));
        if (format === null) {
            throw new errors_1.RuntimeError({
                message: "Output format must be one of: text, json.",
                code: "INVALID_OUTPUT_FORMAT",
                exitCode: errors_1.RuntimeExitCode.USAGE
            });
        }
        const repository = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        let result;
        try {
            const preview = (0, task_implementation_completion_1.previewTaskImplementationCompletionSync)({
                repositoryRoot: repository.root,
                taskDefinitionPath: options.taskDefinition,
                attemptId: options.attemptId,
                taskRevision: options.taskRevision,
                completedBy: options.completedBy,
                completedAt: options.completedAt
            });
            result = options.dryRun === true
                ? preview
                : (0, task_implementation_completion_1.applyTaskImplementationCompletionSync)(preview);
        }
        catch (error) {
            throw normalizeImplementationCompletionError(error, options.taskDefinition);
        }
        (0, output_1.emitSuccess)({
            command: "task implementation-complete",
            format,
            text: renderText(result),
            data: {
                ...result,
                repositoryRoot: repository.root,
                detectionSource: repository.detectionSource,
                nextAction: result.writeOutcome === "previewed" && result.applicable
                    ? "Omit --dry-run with the same exact request to apply through the repository transaction."
                    : result.writeOutcome === "committed"
                        ? "Continue through read-only implementation-summary review; review, disposition, close, task completion, and reconciliation remain separate."
                        : result.idempotent && result.writeOutcome === "no-write"
                            ? "Implementation completion is already present; continue through the next separate lifecycle transition."
                            : "Resolve every error finding, capture a fresh task revision, and rerun the dry-run preview."
            }
        });
    });
    return command;
}
function normalizeImplementationCompletionError(error, taskDefinitionPath) {
    if (error instanceof errors_1.RuntimeError)
        return error;
    if (error instanceof task_implementation_completion_1.TaskImplementationCompletionError) {
        const normalizedCode = error.code.replace(/-/g, "_").toUpperCase();
        const code = `TASK_IMPLEMENTATION_COMPLETE_${normalizedCode}`;
        return new errors_1.RuntimeError({
            message: "Task implementation-complete was rejected.",
            code,
            exitCode: error.code === "artifact-unreadable"
                ? errors_1.RuntimeExitCode.INVALID_CONFIG
                : errors_1.RuntimeExitCode.USAGE,
            writeOutcome: "no-writes",
            details: [
                error.message,
                "No task-definition, implementation-summary, attempt, reconciliation, or related state was written."
            ],
            findings: [{
                    code,
                    severity: "error",
                    message: error.message,
                    path: taskDefinitionPath,
                    noWriteBoundary: "Rejected implementation-complete requests do not mutate repository state."
                }],
            recoveryActions: [(0, errors_1.createNonCallableRecoveryAction)({
                    id: "recovery.task.implementation-complete.correct-input",
                    command: "task implementation-complete",
                    explanation: "Correct the malformed or unsupported implementation-completion input and request a fresh preview.",
                    reason: "The rejected request does not contain enough valid information to infer a complete safe replacement argv."
                })]
        });
    }
    throw error;
}
function renderText(result) {
    return [
        result.writeOutcome === "previewed"
            ? "Task implementation completion preview"
            : "Task implementation completion apply",
        "",
        `Task definition: ${result.taskDefinitionPath}`,
        `Implementation summary: ${result.implementationSummaryPath}`,
        `Attempt ID: ${result.attemptId}`,
        `Completed by: ${result.completedBy}`,
        `Completed at: ${result.completedAt}`,
        `Bound task revision: ${result.boundTaskRevision}`,
        `Observed task revision: ${result.taskRevision}`,
        `Intended transition: ${result.intendedTransition.field} ${result.intendedTransition.from ?? "(missing)"} -> ${result.intendedTransition.to}`,
        `Applicable: ${result.applicable ? "yes" : "no"}`,
        `Idempotent: ${result.idempotent ? "yes" : "no"}`,
        `Write outcome: ${result.writeOutcome}`,
        `Changed paths: ${result.changedPaths.length}`,
        ...result.changedPaths.map((entry) => `- ${entry}`),
        `Findings: ${result.findings.length}`,
        ...result.findings.map((finding) => `- [${finding.severity}] ${finding.code}: ${finding.message}`),
        `Recovery actions: ${result.recoveryActions.length}`,
        ...result.recoveryActions.map((recovery) => recovery.callable
            ? `- [callable] ${recovery.argv.map((segment) => JSON.stringify(segment)).join(" ")}`
            : `- [non-callable] ${recovery.nonCallableReason}`)
    ].join("\n");
}
