"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runValidationLinksCheckReport = void 0;
exports.createValidationLinksCheckCommand = createValidationLinksCheckCommand;
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 validation_output_contracts_1 = require("../../../lib/output/validation-output-contracts");
const markdown_link_materialization_1 = require("../../../lib/planning/markdown-link-materialization");
const validation_links_report_1 = require("../../../lib/validation/validation-links-report");
Object.defineProperty(exports, "runValidationLinksCheckReport", { enumerable: true, get: function () { return validation_links_report_1.runValidationLinksCheckReport; } });
const cli_constants_1 = require("../../../lib/config/cli-constants");
const global_format_1 = require("../global-format");
async function createValidationLinksCheckCommand() {
    const { Command } = await import('commander');
    const command = new Command('links-check');
    command
        .description('Run a read-only, local-only validation links check over repository-relative planning trace links.')
        .option('--scope <scope>', "Validation links-check scope. Currently only 'planning' is supported.", 'planning')
        .option('--format <format>', 'Validation links-check output format. Accepted values: text, json.')
        .option('--artifact <path>', 'Optional repository-relative planning artifact file or directory path to focus links-check input validation.')
        .addHelpText('after', [
        '',
        'Boundaries:',
        '  Read-only and local-only: no remote provider checks, metadata repair, checkpoint writes, status mutation, or artifact generation.',
        '  This command resolves local trace values, hierarchy evidence, paired-artifact evidence, disposition-backed lifecycle findings, and trace-link findings without writing files.',
        '  Disposition evidence may report retired, deleted, migrated, malformed-storage, or applied-migration state and may recommend preview/apply commands, but validation never repairs links or infers replacement targets.',
    ].join('\n'))
        .action((_, commandInstance) => {
        const options = commandInstance.opts();
        const requestedFormat = options.format ?? (0, global_format_1.getGlobalFormat)(commandInstance);
        const format = (0, output_1.resolveOutputFormat)(requestedFormat);
        if (format === null) {
            throw (0, errors_1.createUnsupportedOutputFormatError)({
                received: requestedFormat,
                commandBoundary: 'validation links-check command output format',
            });
        }
        if (options.scope !== 'planning') {
            throw (0, errors_1.createUsageError)("Validation links-check currently supports only the 'planning' scope.", [
                `Received: ${String(options.scope)}`,
            ]);
        }
        const repositoryRoot = getRootCommand(commandInstance).configRepositoryContext?.root ?? process.cwd();
        const report = (0, validation_links_report_1.runValidationLinksCheckReport)({
            repositoryRoot,
            artifactPath: options.artifact,
        });
        const { artifact: artifactPath, discovery, resolution, findings } = report;
        if (findings.some((finding) => finding.severity === 'error')) {
            getRootCommand(commandInstance).runtimeExitCode = errors_1.RuntimeExitCode.ERROR;
        }
        (0, output_1.emitSuccess)({
            command: 'validation links-check',
            format,
            text: renderValidationLinksCheckReport(discovery, resolution, findings),
            data: {
                repositoryRoot,
                scope: 'planning',
                artifact: artifactPath,
                artifactInputKind: artifactPath === null
                    ? 'repository'
                    : node_fs_1.default.existsSync(node_path_1.default.join(repositoryRoot, artifactPath)) &&
                        node_fs_1.default.statSync(node_path_1.default.join(repositoryRoot, artifactPath)).isDirectory()
                        ? 'directory'
                        : 'file',
                readOnly: true,
                localOnly: true,
                writeCapable: false,
                implementationState: 'finding-output-implemented',
                checksImplemented: true,
                checkedArtifactCount: discovery.summary.artifactCount,
                checkedRelationshipCount: resolution.summary.valueResolutionCount +
                    resolution.summary.hierarchyCheckCount +
                    resolution.summary.pairingCheckCount,
                traceLinkFindingCount: findings.length,
                blockingFindingCount: findings.filter((finding) => finding.severity === 'error').length,
                advisoryFindingCount: findings.filter((finding) => finding.severity !== 'error').length,
                selectedRevisionEvidence: (0, markdown_link_materialization_1.createLinkScopeRevisionEvidence)({
                    repositoryRoot,
                    artifactPath,
                    discovery,
                }),
                findingSummary: (0, validation_output_contracts_1.createCompactValidationFindingSummary)(findings),
                outputContracts: (0, output_1.getValidationCommandOutputContracts)(),
                readOnlyFailureContract: (0, output_1.getValidationReadOnlyFailureContract)(),
                noWriteBoundary: cli_constants_1.VALIDATION_LINKS_CHECK_NO_WRITE_BOUNDARY,
                discovery,
                resolution,
                dispositionStorage: report.dispositionStorage,
                summary: (0, validation_links_report_1.createValidationLinksCheckSummary)(discovery, resolution, findings),
            },
            findings,
        });
    });
    return command;
}
function renderValidationLinksCheckReport(discovery, resolution, findings) {
    return [
        (0, output_1.renderTerminalHeading)('Day Shift validation links-check', 'title').trimEnd(),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Summary',
            fields: [
                { label: 'Command', value: 'validation links-check' },
                { label: 'Scope', value: 'planning' },
                { label: 'Artifact', value: discovery.artifact ?? '(none)' },
                { label: 'Mode', value: 'read-only, local-only' },
                { label: 'Write capable', value: 'no' },
                {
                    label: 'Checks implemented',
                    value: 'discovery, local resolution, hierarchy comparison, paired-artifact checks',
                },
                { label: 'No-write boundary', value: cli_constants_1.VALIDATION_LINKS_CHECK_NO_WRITE_BOUNDARY },
                { label: 'Findings', value: findings.length },
                { label: 'Blocking findings', value: findings.filter((finding) => finding.severity === 'error').length },
                { label: 'Advisory findings', value: findings.filter((finding) => finding.severity !== 'error').length },
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: 'read-only' })],
        }),
        '',
        'Discovery summary:',
        `- Mode: ${discovery.mode}`,
        `- Artifacts discovered: ${discovery.summary.artifactCount}`,
        `- Parsed artifacts: ${discovery.summary.parsedCount}`,
        `- Evidence records: ${discovery.summary.evidenceCount}`,
        `- Unsupported artifacts: ${discovery.summary.unsupportedCount}`,
        `- Malformed artifacts: ${discovery.summary.malformedCount}`,
        `- Missing artifacts: ${discovery.summary.missingCount}`,
        `- Outside coverage artifacts: ${discovery.summary.outsideCoverageCount}`,
        '',
        'Resolution summary:',
        `- Value resolutions: ${resolution.summary.valueResolutionCount}`,
        `- Resolved local targets: ${resolution.summary.resolvedLocalTargetCount}`,
        `- Supported non-local sources: ${resolution.summary.resolvedNonLocalSourceCount}`,
        `- Missing local targets: ${resolution.summary.missingLocalTargetCount}`,
        `- Malformed local links: ${resolution.summary.malformedLocalLinkCount}`,
        `- Outside traversal boundary: ${resolution.summary.outsideTraversalBoundaryCount}`,
        `- Unsupported references: ${resolution.summary.unsupportedReferenceCount}`,
        `- Disposition lifecycle evidence: ${resolution.summary.dispositionLifecycleEvidenceCount}`,
        `- Hierarchy checks: ${resolution.summary.hierarchyCheckCount}`,
        `- Hierarchy mismatches: ${resolution.summary.hierarchyMismatchCount}`,
        `- Stale explicit links: ${resolution.summary.staleLinkCount}`,
        `- Paired-artifact checks: ${resolution.summary.pairingCheckCount}`,
        `- Paired-artifact mismatches: ${resolution.summary.pairingMismatchCount}`,
        `- Blocking evidence: ${resolution.summary.blockingEvidenceCount}`,
        `- Advisory evidence: ${resolution.summary.advisoryEvidenceCount}`,
        '',
        'Report lanes:',
        '- discovery',
        '- resolution',
        '- relationship evidence',
        '- summary',
        '- findings',
        '',
        (0, output_1.renderValidationFindingsText)(findings, 'Structured findings'),
    ].join('\n');
}
function getRootCommand(commandInstance) {
    let current = commandInstance;
    while (current?.parent != null) {
        current = current.parent;
    }
    return (current ?? commandInstance);
}
