"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPhaseScaffoldMigrateCommand = createPhaseScaffoldMigrateCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const phase_scaffold_migration_1 = require("../../../lib/planning/phase-scaffold-migration");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createPhaseScaffoldMigrateCommand() {
    const { Command } = await import("commander");
    const command = new Command("scaffold-migrate");
    command
        .description("Preview or atomically adopt recognized pre-scoped-evidence governed scaffolds without replacing authored child bodies.")
        .requiredOption("--phase-overview <path>", "Repository-relative governed phase-overview.md path.")
        .option("--dry-run", "Preview inferred evidence, exact projection rebindings, preconditions, and the plan digest without mutation.")
        .option("--apply", "Atomically apply the exact currently recomputed migration plan.")
        .option("--expected-plan-digest <digest>", "Exact sha256 plan digest returned by the reviewed dry-run; required with --apply.")
        .addHelpText("after", [
        "",
        "Boundaries:",
        "  Migration recognizes child stamps reproduced by supported versioned pre-scoped-evidence projection readers.",
        "  Authored milestone and task bodies are preserved; only missing canonical parent evidence and projection metadata may change.",
        "  Apply recomputes the plan and transactionally rejects stale source revisions or an unexpected plan digest."
    ].join("\n"))
        .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 options = commandInstance.opts();
        if ((options.dryRun === true) === (options.apply === true)) {
            throw (0, errors_1.createUsageError)("Select exactly one phase scaffold migration mode: --dry-run or --apply.");
        }
        if (options.apply === true && typeof options.expectedPlanDigest !== "string") {
            throw (0, errors_1.createUsageError)("--apply requires --expected-plan-digest from the current dry-run.");
        }
        if (options.dryRun === true && options.expectedPlanDigest !== undefined) {
            throw (0, errors_1.createUsageError)("--expected-plan-digest is accepted only with --apply.");
        }
        const repository = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        let result;
        try {
            const preview = (0, phase_scaffold_migration_1.previewPhaseScaffoldMigrationSync)({
                repositoryRoot: repository.root,
                phaseOverviewPath: options.phaseOverview
            });
            result = options.dryRun === true
                ? preview
                : (0, phase_scaffold_migration_1.applyPhaseScaffoldMigrationSync)(preview, options.expectedPlanDigest);
        }
        catch (error) {
            if (error instanceof errors_1.RuntimeError)
                throw error;
            throw (0, errors_1.createUsageError)(error instanceof Error ? error.message : String(error), ["No phase, milestone, task, reconciliation, lifecycle-run, or historical evidence write was attempted."]);
        }
        if (result.writeOutcome !== "previewed" && result.writeOutcome !== "committed") {
            throw (0, errors_1.createUsageError)(`Phase scaffold migration ended with '${result.writeOutcome}'.`, [
                ...(result.failure === null ? [] : [result.failure]),
                ...(result.recoveryPath === null ? [] : [`Recovery record: ${result.recoveryPath}`]),
                ...result.conflicts.map((entry) => JSON.stringify(entry))
            ]);
        }
        (0, output_1.emitSuccess)({
            command: "phase scaffold-migrate",
            format,
            text: renderText(result),
            data: {
                repositoryRoot: repository.root,
                detectionSource: repository.detectionSource,
                ...result,
                nextAction: result.writeOutcome === "previewed"
                    ? [
                        "day-shift", "phase", "scaffold-migrate",
                        "--phase-overview", result.phaseOverviewPath,
                        "--apply", "--expected-plan-digest", result.planDigest,
                        "--format", "json"
                    ]
                    : [
                        "day-shift", "phase", "review",
                        "--phase-overview", result.phaseOverviewPath,
                        "--metadata-posture", "read-only",
                        "--review-mode", "readiness",
                        "--format", "json"
                    ]
            }
        });
    });
    return command;
}
function renderText(result) {
    return [
        "Phase scaffold evidence migration",
        "",
        `Phase overview: ${result.phaseOverviewPath}`,
        `Legacy evidence detected: ${result.legacyEvidenceDetected}`,
        `Affected artifacts: ${result.affectedArtifacts.length}`,
        `Plan digest: ${result.planDigest}`,
        `Write outcome: ${result.writeOutcome}`,
        `Changed paths: ${result.changedPaths.length}`
    ].join("\n");
}
