"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderStructuralPressureReport = renderStructuralPressureReport;
exports.renderStructuralPressureSyncResult = renderStructuralPressureSyncResult;
const output_1 = require("../output");
const structural_pressure_thresholds_1 = require("./structural-pressure-thresholds");
const STRUCTURAL_PRESSURE_CLASSIFICATION_TEXT_ORDER = [
    "hotspot",
    "pressure",
    "watch"
];
const STRUCTURAL_PRESSURE_SNARK_BANDS = [
    {
        minimumLineCount: 20000,
        comments: ["wtf"]
    },
    {
        minimumLineCount: 10000,
        comments: [
            "At this size, scrolling counts as cardio.",
            "This file has crossed from module into municipal infrastructure."
        ]
    },
    {
        minimumLineCount: 5000,
        comments: [
            "This file may require its own onboarding buddy.",
            "This file is not large; it is a seating chart with imports."
        ]
    },
    {
        minimumLineCount: 2000,
        comments: [
            "At this size, 'quick skim' is no longer a plan.",
            "This file is doing the work of several reasonably sized files."
        ]
    },
    {
        minimumLineCount: 1000,
        comments: [
            "This file is auditioning for a table of contents.",
            "This is where future debugging starts packing snacks."
        ]
    },
    {
        minimumLineCount: 600,
        comments: [
            "Chunky enough to deserve a closer look.",
            "This file is getting a little too comfortable."
        ]
    },
    {
        minimumLineCount: 300,
        comments: [
            "This file is big enough to deserve boundaries.",
            "This file has entered the maybe-split-me zone."
        ]
    }
];
function renderStructuralPressureReport(result) {
    const lines = [
        (0, output_1.renderTerminalSection)({
            heading: "Day Shift structural pressure report",
            headingStyle: "title",
            fields: [
                { label: "State path", value: result.statePath },
                { label: "State present", value: result.statePresent ? "yes" : "no" },
                { label: "State entries", value: result.entries.length }
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)({ kind: "read-only" })
            ]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Source scan summary",
            headingStyle: "section",
            fields: [
                { label: "Requested path", value: result.scan.summary.requestedPath ?? "(default roots: src, tests when present)" },
                { label: "Scan roots", value: result.scan.summary.roots.length > 0 ? result.scan.summary.roots.join(", ") : "(none)" },
                {
                    label: "Thresholds",
                    value: `source watch/pressure/hotspot = ${(0, structural_pressure_thresholds_1.renderStructuralPressureThresholdFamilyValues)(result.thresholds.source)} lines; test watch/pressure/hotspot = ${(0, structural_pressure_thresholds_1.renderStructuralPressureThresholdFamilyValues)(result.thresholds.test)} lines`
                },
                {
                    label: "Threshold provenance",
                    value: `source ${(0, structural_pressure_thresholds_1.renderStructuralPressureThresholdFamilyProvenance)(result.thresholds.source)}; test ${(0, structural_pressure_thresholds_1.renderStructuralPressureThresholdFamilyProvenance)(result.thresholds.test)}`
                },
                { label: "Files scanned", value: result.scan.summary.filesScanned },
                { label: "Observed candidates", value: result.scan.summary.candidates },
                { label: "Observed-only candidates", value: result.scan.summary.observedOnlyCandidates },
                { label: "Tracked-and-observed candidates", value: result.scan.summary.trackedAndObservedCandidates },
                { label: "Tracked-state-only entries", value: result.scan.summary.trackedStateOnlyEntries }
            ],
            lines: [
                "Source files are flagged earlier because production coupling risk usually appears sooner; test files allow broader fixture and scenario coverage before pressure classification."
            ]
        })
    ];
    if (result.scan.candidates.length > 0) {
        const largestCandidate = findLargestStructuralPressureCandidate(result.scan.candidates);
        lines.push("", renderStructuralPressureLargestCandidateCallout(largestCandidate), "", (0, output_1.renderTerminalSection)({
            heading: "Observed candidates",
            headingStyle: "section",
            fields: [
                { label: "Grouping", value: "hotspot, pressure, watch" },
                { label: "Sort order", value: "highest line count first within each threshold group" }
            ]
        }), ...STRUCTURAL_PRESSURE_CLASSIFICATION_TEXT_ORDER.flatMap((classification) => [
            "",
            renderStructuralPressureCandidateThresholdGroup(classification, result.scan.candidates.filter((candidate) => candidate.classification === classification), result.thresholds)
        ]));
    }
    if (!result.statePresent) {
        lines.push("", "State file is absent. Markdown planning and reconciliation artifacts remain canonical until sync writes the derived mirror.");
        return lines.join("\n");
    }
    lines.push((0, output_1.renderTerminalSection)({
        heading: "Derived state provenance",
        headingStyle: "section",
        fields: [
            { label: "Last synced", value: result.syncedAt ?? "(missing)" },
            { label: "Source milestone reconciliation", value: result.sourceMilestoneReconciliationPath ?? "(missing)" },
            { label: "Source milestone overview", value: result.sourceMilestoneOverviewPath ?? "(missing)" }
        ]
    }));
    if (result.entries.length > 0) {
        lines.push("", (0, output_1.renderTerminalCompactList)({
            heading: "Existing state entries",
            headingStyle: "section",
            entrySpacing: "loose",
            entries: result.entries.map((entry) => ({
                label: entry.path,
                fields: [
                    { label: "Status", value: `${entry.status}/${entry.severity}` },
                    { label: "Summary", value: entry.summary },
                    ...(entry.evidence_paths.length > 0
                        ? [{ label: "Evidence", value: entry.evidence_paths.join(", ") }]
                        : [])
                ]
            }))
        }));
    }
    if (result.scan.stateOnlyEntries.length > 0) {
        lines.push("", (0, output_1.renderTerminalCompactList)({
            heading: "Tracked-state-only entries",
            headingStyle: "section",
            entrySpacing: "loose",
            entries: result.scan.stateOnlyEntries.map((entry) => ({
                label: entry.path,
                fields: [
                    { label: "Status", value: `${entry.trackedState.status}/${entry.trackedState.severity}` },
                    { label: "Summary", value: entry.trackedState.summary },
                    ...(entry.trackedState.evidencePaths.length > 0
                        ? [{ label: "Evidence", value: entry.trackedState.evidencePaths.join(", ") }]
                        : [])
                ]
            }))
        }));
    }
    if (result.driftFindings.length > 0) {
        lines.push("", (0, output_1.renderTerminalCompactList)({
            heading: "Derived state drift findings",
            headingStyle: "section",
            entrySpacing: "loose",
            entries: result.driftFindings.map((finding) => ({
                label: finding.entryPath ?? "(state source)",
                fields: [
                    { label: "Severity", value: finding.severity },
                    { label: "Derived state", value: finding.derivedStatePath },
                    { label: "Canonical Markdown", value: finding.canonicalMarkdownPath },
                    { label: "Reason", value: finding.reason }
                ]
            }))
        }), "Markdown reconciliation and implementation-summary artifacts remain authoritative; report output is read-only and does not authorize sync.");
    }
    return lines.join("\n");
}
function renderStructuralPressureSyncResult(result) {
    return (0, output_1.renderTerminalSection)({
        heading: "Day Shift structural pressure sync",
        headingStyle: "title",
        fields: [
            { label: "Milestone reconciliation", value: result.reconciliationPath },
            { label: "Milestone overview", value: result.milestoneOverviewPath },
            { label: "State path", value: result.statePath },
            { label: "Entries mirrored", value: result.entryCount },
            { label: "Changed", value: result.changed ? "yes" : "no" }
        ],
        lines: [
            (0, output_1.renderTerminalBoundary)(result.writeApplied
                ? {
                    kind: "write-applied",
                    target: result.statePath,
                    targetLabel: "State file",
                    stateSurface: "derived structural-pressure state"
                }
                : {
                    kind: "mutating-no-op",
                    target: result.statePath,
                    targetLabel: "State file",
                    stateSurface: "derived structural-pressure state",
                    reason: "Derived state already matched the reconciliation payload."
                })
        ]
    });
}
function findLargestStructuralPressureCandidate(candidates) {
    return [...candidates].sort((left, right) => (right.lineCount - left.lineCount || left.path.localeCompare(right.path)))[0];
}
function renderStructuralPressureLargestCandidateCallout(candidate) {
    return (0, output_1.renderTerminalSection)({
        heading: "Largest file callout",
        headingStyle: "section",
        fields: [
            { label: "Path", value: candidate.path },
            { label: "Line count", value: `${candidate.lineCount} lines` },
            { label: "Classification", value: `${candidate.classification}/${candidate.fileKind}` },
            { label: "Comment", value: selectStructuralPressureSnark(candidate) }
        ]
    });
}
function selectStructuralPressureSnark(candidate) {
    const band = STRUCTURAL_PRESSURE_SNARK_BANDS.find((snarkBand) => candidate.lineCount >= snarkBand.minimumLineCount);
    if (band === undefined) {
        return "This file is still below the snark threshold.";
    }
    if (band.comments.length === 1) {
        return band.comments[0];
    }
    return band.comments[structuralPressureSnarkIndex(candidate, band.comments.length)];
}
function structuralPressureSnarkIndex(candidate, commentCount) {
    return Math.abs(candidate.lineCount + candidate.path.length) % commentCount;
}
function renderStructuralPressureCandidateThresholdGroup(classification, candidates, thresholds) {
    const sortedCandidates = [...candidates].sort((left, right) => (right.lineCount - left.lineCount || left.path.localeCompare(right.path)));
    return [
        (0, output_1.renderTerminalSection)({
            heading: `${renderStructuralPressureClassificationLabel(classification)} threshold`,
            headingStyle: "section",
            fields: [
                {
                    label: "Source threshold",
                    value: renderStructuralPressureClassificationRange(classification, (0, structural_pressure_thresholds_1.structuralPressureThresholdValues)(thresholds.source))
                },
                {
                    label: "Test threshold",
                    value: renderStructuralPressureClassificationRange(classification, (0, structural_pressure_thresholds_1.structuralPressureThresholdValues)(thresholds.test))
                },
                { label: "Candidates", value: sortedCandidates.length }
            ]
        }),
        (0, output_1.renderTerminalCompactList)({
            entries: sortedCandidates.map((candidate) => ({
                label: candidate.path,
                fields: [
                    { label: "Merge status", value: candidate.mergeStatus },
                    { label: "Classification", value: `${candidate.classification}/${candidate.fileKind}` },
                    { label: "Line count", value: `${candidate.lineCount} lines` },
                    { label: "Reasons", value: candidate.reasonCodes.join(", ") },
                    { label: "Thresholds", value: (0, structural_pressure_thresholds_1.renderStructuralPressureCandidateThresholdValues)(candidate.threshold) },
                    ...(candidate.trackedState === undefined
                        ? []
                        : [
                            {
                                label: "Tracked state",
                                value: `${candidate.trackedState.status}/${candidate.trackedState.severity} - ${candidate.trackedState.summary}`
                            }
                        ])
                ]
            })),
            entrySpacing: "loose",
            emptyMessage: "No observed candidates in this threshold group."
        })
    ].join("\n");
}
function renderStructuralPressureClassificationLabel(classification) {
    return `${classification[0].toUpperCase()}${classification.slice(1)}`;
}
function renderStructuralPressureClassificationRange(classification, threshold) {
    if (classification === "hotspot") {
        return `>= ${threshold.hotspot} lines`;
    }
    if (classification === "pressure") {
        return `${threshold.pressure}-${threshold.hotspot - 1} lines`;
    }
    return `${threshold.watch}-${threshold.pressure - 1} lines`;
}
