"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createValidationSmokeCommand = createValidationSmokeCommand;
const node_fs_1 = __importDefault(require("node:fs"));
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const validation_output_contracts_1 = require("../../../lib/output/validation-output-contracts");
const doctor_1 = require("../../../lib/doctor");
const global_format_1 = require("../global-format");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const paths_1 = require("../../../lib/paths");
async function createValidationSmokeCommand() {
    const { Command } = await import('commander');
    const command = new Command('smoke');
    command
        .description('Run a concise read-only, no-write planning validation summary and advisory safe-next-step report.')
        .option('--scope <scope>', "Validation smoke scope. Currently only 'planning' is supported.", 'planning')
        .option('--artifact <path>', 'Optional repository-relative planning artifact to include in next-action guidance.')
        .option('--action <descriptor>', 'Optional exact authoritative command descriptor id used to classify the unchanged focused findings.')
        .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 options = commandInstance.opts();
        const repositoryRoot = getRootCommand(commandInstance).configRepositoryContext?.root ?? process.cwd();
        if (options.scope !== 'planning') {
            throw (0, errors_1.createUsageError)("Validation smoke currently supports only the 'planning' scope.", [
                `Received: ${String(options.scope)}`,
            ]);
        }
        if (options.action !== undefined && options.artifact === undefined) {
            throw (0, errors_1.createUsageError)('--action requires one explicit --artifact for focused planning validation.', [
                'No validation, repair, metadata, status, or planning-artifact write was performed.',
            ]);
        }
        const artifactPath = normalizeArtifactPath(options.artifact, repositoryRoot);
        const actionDescriptor = options.action === undefined ? null : (0, output_1.getRegisteredCommandDescriptor)(String(options.action).trim());
        if (options.action !== undefined && (actionDescriptor === null || actionDescriptor.availability !== 'callable')) {
            throw (0, errors_1.createUsageError)(`Unknown callable action descriptor '${String(options.action)}'.`, [
                'Use an exact callable command id from the authoritative command descriptor registry.',
                'No files were changed.',
            ]);
        }
        const report = (0, doctor_1.runPlanningValidationSmoke)({
            artifactPath,
            repositoryRoot,
            actionId: options.action,
        });
        (0, output_1.emitSuccess)({
            command: 'validation smoke',
            format,
            text: (0, doctor_1.renderPlanningValidationSmokeReport)(report),
            data: {
                repositoryRoot: report.repositoryRoot,
                detectionSource: report.detectionSource,
                runtimeProvenance: (0, runtime_contract_1.getRuntimeProvenance)(),
                scope: report.scope,
                artifact: artifactPath ?? null,
                planningRootPath: report.planningRootPath,
                readOnly: true,
                writeCapable: false,
                findingSummary: (0, validation_output_contracts_1.createCompactValidationFindingSummary)(report.findings),
                outputContracts: (0, output_1.getValidationCommandOutputContracts)(),
                readOnlyFailureContract: (0, output_1.getValidationReadOnlyFailureContract)(),
                evidenceSourceInventory: report.evidenceSourceInventory,
                specializedReviewBoundaries: report.specializedReviewBoundaries,
                aggregationContract: report.aggregationContract,
                checks: report.checks,
                summary: report.summary,
                readinessStatus: report.readinessStatus,
                inventoryFindings: report.inventoryFindings,
                crossArtifactAlignment: report.crossArtifactAlignment,
                baseline: report.baseline,
                gaps: report.gaps,
                expectedChildGaps: report.expectedChildGaps,
                nextActions: report.nextActions,
                nextAction: report.nextAction,
                ...(report.actionRelevance === null ? {} : { actionRelevance: report.actionRelevance }),
            },
            findings: [...report.findings],
        });
    });
    return command;
}
function getRootCommand(commandInstance) {
    let current = commandInstance;
    while (current?.parent) {
        current = current.parent;
    }
    return (current ?? commandInstance);
}
function normalizeArtifactPath(input, repositoryRoot) {
    if (input === undefined) {
        return undefined;
    }
    if (typeof input !== 'string') {
        throw (0, errors_1.createUsageError)('Validation smoke artifact path must be a repository-relative planning artifact file.', [
            `Received: ${String(input)}`,
            'No validation, repair, metadata, status, or planning-artifact write was performed.',
        ]);
    }
    let artifactPath;
    try {
        artifactPath = (0, paths_1.parseRepositoryRelativePath)(input).normalizedPath;
    }
    catch (error) {
        if (error instanceof RangeError) {
            throw (0, errors_1.createUsageError)('Validation smoke artifact path must be a repository-relative planning artifact file.', [
                error.message,
                'No validation, repair, metadata, status, or planning-artifact write was performed.',
            ]);
        }
        throw error;
    }
    const absolutePath = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, artifactPath);
    if (node_fs_1.default.existsSync(absolutePath) && node_fs_1.default.statSync(absolutePath).isDirectory()) {
        throw (0, errors_1.createUsageError)('Validation smoke --artifact must point to a planning artifact file, not a directory.', [
            `Received directory: ${artifactPath}`,
            'Use --artifact <repository-relative-path-to-planning-artifact.md> for focused validation.',
            `For directory-scoped evidence, use day-shift planning inventory --root ${artifactPath} or day-shift planning gap-report --scope ${artifactPath}.`,
            'No validation, repair, metadata, status, or planning-artifact write was performed.',
        ]);
    }
    return artifactPath;
}
