"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCommandsValidateCommand = createCommandsValidateCommand;
const errors_1 = require("../../../lib/errors");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const automation_protocol_1 = require("../../../lib/automation-protocol");
const output_1 = require("../../../lib/output");
async function createCommandsValidateCommand() {
    const { Command } = await import('commander');
    const command = new Command('validate');
    command
        .description('Validate authoritative descriptors against the live command tree and tool manifest.')
        .action((_options, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)(commandInstance.optsWithGlobals?.().format);
        if (format === null)
            throw (0, errors_1.createUsageError)('Unsupported output format for commands validate.');
        const root = commandInstance.parent?.parent;
        if (root == null)
            throw (0, errors_1.createUsageError)('Unable to resolve the live command tree for validation.');
        const runtimeCommands = (0, output_1.createRuntimeCommandContracts)(root);
        const protocolVersion = (0, automation_protocol_1.getSelectedAutomationProtocolVersion)();
        const runtimeCommandNames = new Set(runtimeCommands.map((entry) => entry.command));
        const executableDescriptors = output_1.COMMAND_DESCRIPTOR_REGISTRY.filter((descriptor) => descriptor.availability === 'callable' && runtimeCommandNames.has(descriptor.command));
        const manifest = (0, output_1.createNativeToolManifest)(executableDescriptors);
        const report = (0, output_1.validateCommandDescriptorDrift)({
            descriptors: output_1.COMMAND_DESCRIPTOR_REGISTRY,
            runtimeCommands,
            tools: manifest.tools,
            protocolVersion,
        });
        (0, output_1.emitSuccess)({
            command: 'commands validate',
            format,
            data: {
                ...report,
                runtimeProvenance: (0, runtime_contract_1.getRuntimeProvenance)(),
            },
            text: [
                `Command descriptor drift verdict: ${report.verdict}`,
                `Callable: ${report.callableCount}; descriptors: ${report.descriptorCount}; tools: ${report.toolCount}`,
                `Input coverage: ${report.inputCoverage.coverageVerdict} (${report.inputCoverage.alignedDescriptorInputs}/${report.inputCoverage.runtimeCommandsWithInputs} runtime commands with inputs aligned)`,
                ...report.findings.map((finding) => `- ${finding.code}${finding.command === null ? '' : ` (${finding.command})`}: ${finding.detail}`),
                (0, output_1.renderTerminalBoundary)({ kind: 'read-only' }),
            ].join('\n'),
        });
    });
    return command;
}
