"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createReconciliationAcceptCommand = createReconciliationAcceptCommand;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const node_util_1 = require("node:util");
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const implementation_summary_reconciliation_1 = require("../../../lib/planning/implementation-summary-reconciliation");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const cli_constants_1 = require("../../../lib/config/cli-constants");
const global_format_1 = require("../global-format");
async function createReconciliationAcceptCommand() {
    const { Command } = await import('commander');
    const command = new Command('accept');
    command
        .description('Preview or atomically apply receipt-bound reconciliation completion metadata and the command-owned Review Status marker while preserving authored evidence sections.')
        .option('--milestone-overview <path>', 'Repository-relative milestone overview that owns the paired reconciliation.')
        .option('--task-definition <path>', 'Repository-relative task definition for an explicit task-level reconciliation exception.')
        .option('--rationale <text>', 'Required rationale when using --task-definition for an explicit task-level reconciliation exception.')
        .requiredOption('--review-result <path>', 'Repository-local bounded UTF-8 reconciliation review JSON containing the exact current zero-blocker receipt.')
        .option('--dry-run', 'Preview exact reconciliation-only writes and evidence preconditions without mutation.')
        .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();
        const result = (0, implementation_summary_reconciliation_1.acceptReconciliationArtifact)(repository.root, {
            milestoneOverviewPath: options.milestoneOverview,
            taskDefinitionPath: options.taskDefinition,
            taskReconciliationRationale: options.rationale,
            reviewReceipt: readReviewReceipt(repository.root, options.reviewResult),
            dryRun: options.dryRun === true,
        });
        if (result.writeOutcome !== 'previewed'
            && result.writeOutcome !== 'committed'
            && !(result.idempotent && result.writeOutcome === 'no-write')) {
            throw (0, errors_1.createUsageError)(`Reconciliation acceptance did not commit: ${result.writeOutcome}.`, [
                ...(result.conflicts.length === 0
                    ? []
                    : result.conflicts.map((conflict) => `${conflict.path}: expected ${conflict.expectedState}, observed ${conflict.observedState}.`)),
                ...(result.failure === null ? [] : [result.failure]),
            ]);
        }
        (0, output_1.emitSuccess)({
            command: 'reconciliation accept',
            format,
            text: renderAcceptanceResult(result),
            data: {
                repositoryRoot: repository.root,
                detectionSource: repository.detectionSource,
                ...result,
                nextAction: result.writeOutcome === 'previewed'
                    ? 'Inspect the exact preconditions, then rerun without --dry-run to accept.'
                    : `Run ${result.reviewCommand.argv.join(' ')} to confirm current accepted completion evidence.`,
            },
        });
    });
    return command;
}
function readReviewReceipt(repositoryRoot, requestedPath) {
    const root = node_fs_1.default.realpathSync(repositoryRoot);
    const candidate = node_path_1.default.resolve(root, requestedPath);
    const relative = node_path_1.default.relative(root, candidate);
    if (relative === '' || relative.startsWith(`..${node_path_1.default.sep}`) || node_path_1.default.isAbsolute(relative)) {
        throw (0, errors_1.createUsageError)('--review-result must resolve to a regular file inside the effective repository.');
    }
    const stats = node_fs_1.default.lstatSync(candidate);
    if (stats.isSymbolicLink() || !stats.isFile()) {
        throw (0, errors_1.createUsageError)('--review-result must identify a non-symlink regular file.');
    }
    if (stats.size > cli_constants_1.CLI_MAX_REVIEW_RESULT_BYTES) {
        throw (0, errors_1.createUsageError)('--review-result must be no larger than 2 MiB.');
    }
    let parsed;
    try {
        const bytes = node_fs_1.default.readFileSync(candidate);
        const contents = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
        parsed = JSON.parse(contents);
    }
    catch (error) {
        throw (0, errors_1.createUsageError)('--review-result must contain valid UTF-8 JSON.', [
            error instanceof Error ? error.message : String(error),
        ]);
    }
    if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
        throw (0, errors_1.createUsageError)('--review-result must contain a reconciliation review receipt.');
    }
    const record = parsed;
    const data = record.data !== null && typeof record.data === 'object' && !Array.isArray(record.data)
        ? record.data
        : record;
    const receipt = data.reviewReceipt !== null && typeof data.reviewReceipt === 'object' && !Array.isArray(data.reviewReceipt)
        ? data.reviewReceipt
        : data;
    return receipt;
}
function renderAcceptanceResult(result) {
    return [
        (0, output_1.renderTerminalHeading)('Reconciliation acceptance', 'title').trimEnd(),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Summary',
            fields: [
                { label: 'Mode', value: result.mode },
                { label: 'Source', value: result.sourcePath },
                { label: 'Reconciliation', value: result.reconciliationPath },
                { label: 'Idempotent replay', value: result.idempotent ? 'yes' : 'no' },
                { label: 'Review receipt', value: result.reviewReceiptId },
                { label: 'Source revision', value: result.sourceRevision },
                { label: 'Current reconciliation revision', value: result.reconciliationRevision },
                { label: 'Post-acceptance revision', value: result.postAcceptanceRevision },
                { label: 'Metadata changes', value: JSON.stringify(result.metadataChanges) },
                { label: 'Command-owned marker changes', value: JSON.stringify(result.bodyChanges) },
                { label: 'Read-only review command', value: result.reviewCommand.argv.join(' ') },
                { label: 'Write outcome', value: result.writeOutcome },
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)(result.writeOutcome === 'previewed'
                    ? { kind: 'read-only' }
                    : result.idempotent && result.writeOutcome === 'no-write'
                        ? {
                            kind: 'mutating-no-op',
                            reason: 'The reconciliation is already accepted and current terminal evidence remains sufficient.',
                            target: result.reconciliationPath,
                            targetLabel: 'Reconciliation',
                            stateSurface: 'reconciliation completion metadata and command-owned Review Status marker',
                        }
                        : {
                            kind: 'write-applied',
                            target: result.reconciliationPath,
                            targetLabel: 'Reconciliation',
                            stateSurface: 'reconciliation completion metadata and command-owned Review Status marker',
                        }),
            ],
        }),
    ].join('\n');
}
