"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMetadataSyncStatusFromReviewCommand = createMetadataSyncStatusFromReviewCommand;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const cli_constants_1 = require("../../../lib/config/cli-constants");
const metadata_sync_and_inventory_1 = require("../../../lib/planning/metadata-sync-and-inventory");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createMetadataSyncStatusFromReviewCommand() {
    const { Command } = await import('commander');
    const command = new Command('sync-status-from-review');
    command
        .description('Synchronize selected artifact status metadata from completed review evidence when the update is deterministic.')
        .option('--task-definition <path>', 'Repository-relative path to the task-definition.md file to sync.')
        .option('--milestone-overview <path>', 'Repository-relative path to the milestone-overview.md file to sync.')
        .option('--phase-overview <path>', 'Repository-relative path to the phase-overview.md file to sync.')
        .option('--active-artifact <path>', 'Repository-relative active artifact path expected by the current handoff.')
        .option('--review-result <path>', 'Bounded JSON result from phase review; required with --phase-overview.')
        .option('--metadata-posture <value>', 'Lifecycle metadata posture; required with --phase-overview.')
        .option('--dry-run', 'Preview exact revision-bound phase and milestone transitions without writing.')
        .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.', [
                `Received: ${String((0, global_format_1.getGlobalFormat)(commandInstance))}`,
            ]);
        }
        const repositoryContext = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        const selectedOptions = [options.taskDefinition, options.milestoneOverview, options.phaseOverview].filter((value) => typeof value === 'string' && value.trim() !== '');
        if (selectedOptions.length !== 1) {
            throw (0, errors_1.createUsageError)('Choose exactly one metadata sync-status-from-review selector.', [
                'Use --task-definition, --milestone-overview, or --phase-overview.',
                'Review commands remain read-only; status sync requires this explicit write command.',
            ]);
        }
        const commonOptions = {
            repositoryRoot: repositoryContext.root,
            activeArtifactPath: options.activeArtifact,
        };
        const phaseSelected = typeof options.phaseOverview === 'string' && options.phaseOverview.trim() !== '';
        if (phaseSelected &&
            (typeof options.reviewResult !== 'string' ||
                options.reviewResult.trim() === '' ||
                typeof options.metadataPosture !== 'string' ||
                options.metadataPosture.trim() === '')) {
            throw (0, errors_1.createUsageError)('Phase metadata sync requires --review-result and --metadata-posture.', [
                'Save one complete JSON phase review result.',
                'Use --metadata-posture sync-on-clean-review and --dry-run to preview before apply.',
            ]);
        }
        if (!phaseSelected &&
            (options.reviewResult !== undefined || options.metadataPosture !== undefined || options.dryRun === true)) {
            throw (0, errors_1.createUsageError)('--review-result, --metadata-posture, and --dry-run are phase-scoped metadata sync inputs.');
        }
        const result = typeof options.taskDefinition === 'string' && options.taskDefinition.trim() !== ''
            ? (0, metadata_sync_and_inventory_1.syncTaskDefinitionStatusFromReview)({
                ...commonOptions,
                rootPath: options.taskDefinition,
            })
            : typeof options.milestoneOverview === 'string' && options.milestoneOverview.trim() !== ''
                ? (0, metadata_sync_and_inventory_1.syncMilestoneOverviewStatusFromReview)({
                    ...commonOptions,
                    rootPath: options.milestoneOverview,
                })
                : (0, metadata_sync_and_inventory_1.syncPhaseMetadataStatusesFromReview)({
                    ...commonOptions,
                    rootPath: options.phaseOverview,
                    phaseReviewResult: readPhaseReviewResult(repositoryContext.root, options.reviewResult),
                    metadataPosture: options.metadataPosture,
                    dryRun: options.dryRun === true,
                });
        const phaseResult = result.source === 'phase-review' ? result : null;
        (0, output_1.emitSuccess)({
            command: 'metadata sync-status-from-review',
            format,
            text: (0, metadata_sync_and_inventory_1.renderMetadataSyncResult)(result),
            data: {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                artifactPath: result.artifactPath,
                artifactType: result.artifactType,
                taskDefinitionPath: result.taskDefinitionPath,
                pairedImplementationSummaryPath: result.pairedImplementationSummaryPath,
                milestoneReconciliationPath: result.milestoneReconciliationPath,
                source: result.source,
                changed: result.changed,
                writeApplied: result.writeApplied,
                ...(phaseResult !== null
                    ? {
                        reviewId: phaseResult.reviewId,
                        metadataPosture: phaseResult.metadataPosture,
                        dryRun: phaseResult.dryRun,
                        transactionId: phaseResult.transactionId,
                        transactionOutcome: phaseResult.transactionOutcome,
                        changedPaths: phaseResult.changedPaths,
                        transitions: phaseResult.transitions,
                        revisionPreconditions: phaseResult.revisionPreconditions,
                    }
                    : {}),
            },
        });
    });
    return command;
}
function readPhaseReviewResult(repositoryRoot, inputPath) {
    const absolutePath = node_path_1.default.isAbsolute(inputPath) ? node_path_1.default.resolve(inputPath) : node_path_1.default.resolve(repositoryRoot, inputPath);
    const before = node_fs_1.default.lstatSync(absolutePath, { throwIfNoEntry: false });
    if (before === undefined || !before.isFile() || before.isSymbolicLink()) {
        throw (0, errors_1.createUsageError)('--review-result must identify a non-symlink regular JSON file.');
    }
    if (before.size <= 0 || before.size > cli_constants_1.CLI_MAX_REVIEW_RESULT_BYTES) {
        throw (0, errors_1.createUsageError)('--review-result must be non-empty and no larger than 2 MiB.');
    }
    const bytes = node_fs_1.default.readFileSync(absolutePath);
    const after = node_fs_1.default.lstatSync(absolutePath, { throwIfNoEntry: false });
    if (after === undefined ||
        after.size !== before.size ||
        after.mtimeMs !== before.mtimeMs ||
        after.ino !== before.ino) {
        throw (0, errors_1.createUsageError)('--review-result changed while it was being inspected.');
    }
    try {
        return JSON.parse(bytes.toString('utf8'));
    }
    catch {
        throw (0, errors_1.createUsageError)('--review-result must contain valid UTF-8 JSON.');
    }
}
