"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCommandsRepairCommand = createCommandsRepairCommand;
const errors_1 = require("../../../lib/errors");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const output_1 = require("../../../lib/output");
async function createCommandsRepairCommand() {
    const { Command } = await import("commander");
    const command = new Command("repair");
    command
        .description("Derive bounded read-only command corrections from authoritative descriptors without invoking a proposal.")
        .argument("[argv...]", "Rejected command argv supplied after --, excluding the day-shift executable token.")
        .option("--input-json <json>", "Structured request object containing an argv string array.")
        .action((argv, options, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)(commandInstance.optsWithGlobals?.().format);
        if (format === null)
            throw (0, errors_1.createUsageError)("Unsupported output format for commands repair.");
        let normalized;
        try {
            if (options.inputJson !== undefined) {
                if (argv.length > 0)
                    throw new Error("--input-json cannot be combined with argv after --.");
                const input = (0, output_1.parseStructuredCommandInput)(options.inputJson, ["argv"]);
                normalized = normalizeRepairRequest((0, output_1.requireStringArray)(input.argv, "argv", true), "structured");
            }
            else {
                normalized = normalizeRepairRequest((0, output_1.requireStringArray)(argv, "argv", true), "shell");
            }
        }
        catch (error) {
            throw (0, errors_1.createUsageError)(error instanceof Error ? error.message : "Invalid commands repair request.", [
                "Recovery: supply rejected argv after -- or as --input-json with an argv string array."
            ]);
        }
        const explicitRoot = process.env.DAY_SHIFT_REPOSITORY_ROOT;
        const repositoryRoot = (0, runtime_contract_1.detectRepositoryRoot)({
            explicitRoot: explicitRoot && explicitRoot.trim().length > 0 ? explicitRoot : undefined
        }).root;
        const repair = (0, output_1.repairCommandArgv)(normalized.request.argv, { repositoryRoot });
        (0, output_1.emitSuccess)({
            command: "commands repair",
            format,
            data: { ...repair, ...normalized },
            text: ({ data }) => {
                const lines = [
                    `Rejected argv: ${(0, output_1.quoteShellArgv)(["day-shift", ...data.rejectedArgv])}`,
                    `Confidence: ${data.confidence}; selection required: ${data.selectionRequired}`
                ];
                for (const proposal of data.candidates) {
                    lines.push(`${proposal.rank}. ${proposal.matchedCommand} (${proposal.callable ? "callable" : "not callable"})`, proposal.shellCommand === null
                        ? `   Skeleton: ${(0, output_1.quoteShellArgv)(proposal.argvSkeleton)}`
                        : `   Proposed argv: ${proposal.shellCommand}`, ...(proposal.nonCallableReason === null ? [] : [`   Reason: ${proposal.nonCallableReason}`]));
                }
                lines.push((0, output_1.renderTerminalBoundary)({ kind: "read-only" }));
                return lines.join("\n");
            }
        });
    });
    return command;
}
function normalizeRepairRequest(argv, inputStyle) {
    const tokens = Object.freeze([...argv]);
    return {
        request: Object.freeze({ argv: tokens }),
        requestArgv: Object.freeze(["day-shift", "commands", "repair", "--", ...tokens]),
        inputStyle
    };
}
