"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderPlanningInventoryResult = renderPlanningInventoryResult;
exports.renderPlanningWorkCandidatesResult = renderPlanningWorkCandidatesResult;
exports.renderLegacyCompatibilityAdvisory = renderLegacyCompatibilityAdvisory;
exports.summarizeLegacyPlanningCompatibility = summarizeLegacyPlanningCompatibility;
exports.renderPlanningGapReportResult = renderPlanningGapReportResult;
exports.renderWorkflowExplainResult = renderWorkflowExplainResult;
exports.renderPlanningNextActionResult = renderPlanningNextActionResult;
const config_layer_resolution_1 = require("../../config/config-layer-resolution");
const output_1 = require("../../output");
const document_support_1 = require("./document-support");
function renderPlanningInventoryResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Planning inventory", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Scope", value: result.scopePath },
                { label: "Scope kind", value: result.scopeKind },
                { label: "Work overviews (non-actionable)", value: result.workOverviewPaths.length },
                { label: "Slice overviews", value: result.sliceOverviewPaths.length },
                { label: "Phase overviews", value: result.phaseOverviewPaths.length },
                { label: "Milestone overviews", value: result.milestoneOverviewPaths.length },
                { label: "Task definitions", value: result.taskDefinitionPaths.length },
                { label: "Implementation summaries", value: result.implementationSummaryPaths.length },
                { label: "Reconciliations", value: result.reconciliationPaths.length },
                {
                    label: "Legacy compatibility",
                    value: result.legacyCompatibility === null
                        ? "(not evaluated for artifact scope)"
                        : `${result.legacyCompatibility.workUnits.length} advisory work unit(s)`
                }
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: "read-only" })]
        }),
        "",
        "Findings:"
    ];
    (0, document_support_1.appendLines)(lines, result.findings);
    if (result.legacyCompatibility !== null) {
        lines.push("", renderLegacyCompatibilityAdvisory(result.legacyCompatibility));
    }
    return lines.join("\n");
}
function renderPlanningWorkCandidatesResult(result) {
    return [
        (0, output_1.renderTerminalHeading)("Planning work candidates", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Scope", value: result.scopePath },
                { label: "Scope kind", value: result.scopeKind },
                { label: "Candidates", value: result.totalCandidateCount },
                { label: "Returned", value: result.returnedCandidateCount },
                { label: "Omitted", value: result.omittedCandidateCount },
                {
                    label: "Legacy compatibility",
                    value: `${result.legacyCompatibility.workUnits.length} advisory work unit(s)`
                }
            ],
            lines: [
                "Candidate evidence is advisory. It does not select work or write selection state.",
                (0, output_1.renderTerminalBoundary)({ kind: "read-only" })
            ]
        }),
        "",
        (0, output_1.renderTerminalCompactList)({
            heading: "Candidates:",
            entries: result.candidates.map((candidate) => ({
                label: `${candidate.status}: ${candidate.artifactPath}`,
                fields: [
                    { label: "Artifact type", value: candidate.artifactType },
                    { label: "Observed state", value: candidate.observedState },
                    { label: "Selection command state", value: candidate.selectionCommandState }
                ],
                lines: [
                    ...candidate.reasons,
                    ...candidate.blockers.map((blocker) => `${blocker.code}: ${blocker.path} — ${blocker.message}`),
                    `Selection argv: ${JSON.stringify(candidate.selectionArgv)}`
                ]
            })),
            emptyMessage: "- (none)"
        }),
        "",
        renderLegacyCompatibilityAdvisory(result.legacyCompatibility)
    ].join("\n");
}
function renderLegacyCompatibilityAdvisory(result) {
    return (0, output_1.renderTerminalCompactList)({
        heading: "Legacy compatibility (advisory; no migration applied):",
        entries: result.workUnits.map((unit) => ({
            label: `${unit.proposalStatus}: ${unit.workUnitId}`,
            fields: [
                { label: "Proposed workflow level", value: unit.proposedWorkflowLevel ?? "(unresolved)" },
                { label: "Layout kind", value: unit.layoutKind ?? "(conflicting)" },
                { label: "Slice id", value: unit.sliceId ?? "(not evidenced)" },
                {
                    label: "Former container identity",
                    value: unit.formerContainerIdentity ?? "(not applicable)"
                },
                { label: "Task pairs", value: unit.taskPairCount },
                { label: "Terminal task pairs", value: unit.terminalTaskPairCount },
                { label: "Evidence gaps", value: unit.evidenceGapCodes.length }
            ],
            lines: [
                `Source paths: ${JSON.stringify(unit.sourcePaths)}`,
                ...unit.ambiguityReasonCodes.map((code) => `Ambiguity: ${code}`),
                `Evidence gap codes: ${JSON.stringify(unit.evidenceGapCodes)}`
            ]
        })),
        emptyMessage: "- (none)"
    });
}
function summarizeLegacyPlanningCompatibility(projection) {
    return {
        protocolVersion: projection.protocolVersion,
        proposalStatus: projection.proposalStatus,
        readOnly: true,
        migrationApplied: false,
        canonicalDestination: null,
        workUnits: projection.workUnits.map((unit) => ({
            workUnitId: unit.workUnitId,
            proposalStatus: unit.proposalStatus,
            proposedWorkflowLevel: unit.proposedWorkflowLevel,
            layoutKind: unit.layoutKind,
            sliceId: unit.sliceId,
            formerContainerIdentity: unit.formerContainerIdentity,
            sourcePaths: [...unit.sourcePaths],
            taskPairCount: unit.taskPairs.length,
            terminalTaskPairCount: unit.taskPairs.filter((pair) => pair.lifecycle.terminal).length,
            evidenceGapCodes: [...new Set(unit.evidenceGaps.map((entry) => entry.code))]
                .sort((left, right) => left.localeCompare(right)),
            ambiguityReasonCodes: [...new Set(unit.ambiguityReasons.map((entry) => entry.code))]
                .sort((left, right) => left.localeCompare(right))
        })),
        findingCodes: [...new Set(projection.findings.map((finding) => finding.code))]
            .sort((left, right) => left.localeCompare(right)),
        discoveryComplete: projection.discovery.complete
    };
}
function renderPlanningGapReportResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Planning gap report", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Scope", value: result.scopePath },
                { label: "Scope kind", value: result.scopeKind },
                { label: "Gaps", value: result.gaps.length },
                {
                    label: "Blocking refinement gaps",
                    value: result.gaps.filter((gap) => gap.severity === "error").length
                }
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: "read-only" })]
        }),
        "",
        (0, output_1.renderTerminalCompactList)({
            heading: "Gaps:",
            entries: result.gaps.map((gap) => ({
                label: `${gap.code}: ${gap.path}`,
                lines: [gap.message]
            })),
            emptyMessage: "- (none)"
        })
    ];
    return lines.join("\n");
}
function renderWorkflowExplainResult(result) {
    return [
        (0, output_1.renderTerminalHeading)("Workflow explain", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Artifact",
            fields: [
                { label: "Path", value: result.artifactPath },
                { label: "Type", value: result.artifactType }
            ]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Workflow",
            fields: [
                { label: "Workflow", value: result.workflowPath },
                { label: "Prompt", value: result.promptPath ?? "(none)" },
                { label: "Prompt resolution", value: (0, config_layer_resolution_1.renderPromptResolutionSummary)(result.promptResolution) }
            ]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Guidance",
            fields: [
                { label: "Explanation", value: result.explanation },
                { label: "Recommendation", value: result.recommendation },
                { label: "Recommended command", value: result.recommendedCommand ?? "(workflow-guided step; no direct CLI command)" },
                { label: "Next boundary", value: result.nextBoundary }
            ],
            lines: [
                "Workflow guidance is advisory evidence only; it does not write files, mark tasks ready, complete implementation summaries, or update reconciliation.",
                (0, output_1.renderTerminalBoundary)({ kind: "read-only" }),
                (0, output_1.renderTerminalNextAction)({
                    command: result.recommendedCommand ?? result.workflowPath
                })
            ]
        })
    ].join("\n");
}
function renderPlanningNextActionResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Planning next action", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Artifact", value: result.artifactPath },
                { label: "Artifact type", value: result.artifactType },
                { label: "Recommendation", value: result.recommendation },
                { label: "Reason", value: result.reason },
                { label: "Command", value: result.command ?? "(workflow-guided step; no direct CLI command)" },
                { label: "Optional read-only review", value: result.optionalReviewCommand ?? "(none)" },
                { label: "Workflow", value: result.workflowPath ?? "(none)" },
                { label: "Prompt", value: result.promptPath ?? "(none)" },
                { label: "Prompt resolution", value: (0, config_layer_resolution_1.renderPromptResolutionSummary)(result.promptResolution) }
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)({ kind: "read-only" }),
                (0, output_1.renderTerminalNextAction)({
                    command: result.command
                        ?? (result.optionalReviewCommand === null || result.optionalReviewCommand === undefined
                            ? result.workflowPath ?? "Use the reported workflow and prompt for the next manual step."
                            : "No required lifecycle action; optional read-only review is reported separately.")
                })
            ]
        })
    ];
    if ((result.scaffoldRefinementFindings?.length ?? 0) > 0) {
        lines.push("", (0, output_1.renderTerminalCompactList)({
            heading: "Blocking scaffold refinement findings:",
            entries: result.scaffoldRefinementFindings?.map((finding) => ({
                label: `${finding.code}: ${finding.path}`,
                lines: [finding.message]
            })) ?? [],
            emptyMessage: "No scaffold refinement findings."
        }));
    }
    return lines.join("\n");
}
