"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderTaskPlanningReviewResult = renderTaskPlanningReviewResult;
exports.renderMilestonePlanningReviewResult = renderMilestonePlanningReviewResult;
exports.renderPhasePlanningReviewResult = renderPhasePlanningReviewResult;
exports.buildPlanningRecoveryGuidance = buildPlanningRecoveryGuidance;
exports.renderValidatedModeBalanceRecovery = renderValidatedModeBalanceRecovery;
exports.buildPlanningReviewFindings = buildPlanningReviewFindings;
const output_1 = require("../../output");
const mode_balance_1 = require("../mode-balance");
const planning_navigation_1 = require("../planning-navigation");
const review_output_contracts_1 = require("../review-output-contracts");
const child_drift_1 = require("./child-drift");
function renderTaskPlanningReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)('Task review', 'title').trimEnd(),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Summary',
            fields: [
                { label: 'Task definition', value: result.taskDefinitionPath },
                { label: 'No-write review surface', value: 'yes' },
                { label: 'Review mode', value: result.reviewMode },
                { label: 'Implementation summary', value: result.implementationSummaryPath },
                { label: 'Task reconciliation exception', value: result.taskReconciliationPath ?? '(none)' },
                { label: 'Task-summary review boundary', value: result.reviewBoundaryKind ?? '(invalid topology)' },
                {
                    label: 'Milestone reconciliation',
                    value: result.reconciliationRequired === null
                        ? '(invalid topology)'
                        : result.reconciliationRequired
                            ? result.milestoneReconciliationPath ?? '(required, missing path)'
                            : '(not applicable)',
                },
                { label: 'Readiness status', value: result.readinessStatus ?? '(not evaluated in evidence mode)' },
                { label: 'Closeout evidence', value: result.closeoutEvidenceStatus ?? '(not evaluated in readiness mode)' },
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: 'read-only' })],
        }),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Review Output Contract',
            lines: (0, review_output_contracts_1.renderReviewOutputContractLines)(),
        }),
        '',
        'Blocking Issues:',
    ];
    (0, child_drift_1.appendIssueLines)(lines, result.blockingIssues);
    lines.push('', 'Warnings:');
    (0, child_drift_1.appendIssueLines)(lines, result.warnings);
    lines.push('', 'Metadata-Hygiene Follow-Ups:');
    (0, child_drift_1.appendIssueLines)(lines, result.metadataHygieneFollowUps);
    lines.push('', 'Recovery Guidance:');
    (0, child_drift_1.appendIssueLines)(lines, result.recoveryGuidance);
    return lines.join('\n');
}
function renderMilestonePlanningReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)('Milestone review', 'title').trimEnd(),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Summary',
            fields: [
                { label: 'Milestone overview', value: result.milestoneOverviewPath },
                { label: 'No-write review surface', value: 'yes' },
                { label: 'Review mode', value: result.reviewMode },
                { label: 'Reconciliation', value: result.reconciliationPath ?? '(missing)' },
                { label: 'Closure evidence', value: result.closureEvidenceStatus ?? '(not evaluated in readiness mode)' },
                {
                    label: 'Runtime criterion coverage',
                    value: result.runtimeCriterionOwnership?.coverageStatus ?? '(not applicable)',
                },
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: 'read-only' })],
        }),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Review Output Contract',
            lines: (0, review_output_contracts_1.renderReviewOutputContractLines)(),
        }),
        '',
        'Completed Task Summaries:',
    ];
    (0, child_drift_1.appendIssueLines)(lines, result.completedTaskSummaryPaths);
    lines.push('', 'Incomplete Task Summaries:');
    (0, child_drift_1.appendIssueLines)(lines, result.incompleteTaskSummaryPaths);
    lines.push('', 'Runtime Criterion Ownership:');
    (0, child_drift_1.appendIssueLines)(lines, result.runtimeCriterionOwnership?.childOwnership.map((ownership) => {
        const shared = ownership.sharedCriterionIds.length === 0
            ? ''
            : `; reviewed shared: ${ownership.sharedCriterionIds.join(', ')}`;
        return `${ownership.childSlug}: ${ownership.criterionIds.join(', ') || '(none)'}${shared}`;
    }) ?? []);
    lines.push('', 'Blocking Issues:');
    (0, child_drift_1.appendIssueLines)(lines, result.blockingIssues);
    lines.push('', 'Warnings:');
    (0, child_drift_1.appendIssueLines)(lines, result.warnings);
    lines.push('', 'Metadata-Hygiene Follow-Ups:');
    (0, child_drift_1.appendIssueLines)(lines, result.metadataHygieneFollowUps);
    lines.push('', 'Recovery Guidance:');
    (0, child_drift_1.appendIssueLines)(lines, result.recoveryGuidance);
    return lines.join('\n');
}
function renderPhasePlanningReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)('Phase review', 'title').trimEnd(),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Summary',
            fields: [
                { label: 'Phase overview', value: result.phaseOverviewPath },
                { label: 'No-write review surface', value: 'yes' },
                { label: 'Review mode', value: result.reviewMode },
                { label: 'Metadata posture', value: result.metadataPosture },
                { label: 'Phase review receipt', value: result.phaseReviewReceipt.reviewId },
                {
                    label: 'Phase authoring receipt',
                    value: result.phaseAuthoringReceipt?.receiptId ?? '(not applicable)',
                },
                {
                    label: 'Milestone creation handoff',
                    value: result.phaseAuthoringReceipt?.handoffReady === true ? 'ready' : 'not ready',
                },
                {
                    label: 'Contract-impact coverage',
                    value: result.contractImpactCoverage === null
                        ? '(not applicable)'
                        : result.contractImpactCoverage.enforced
                            ? `${result.contractImpactCoverage.coveredTargetCount}/${result.contractImpactCoverage.uniqueTargetCount} targets covered`
                            : 'repository contract absent',
                },
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: 'read-only' })],
        }),
        '',
        (0, output_1.renderTerminalSection)({
            heading: 'Review Output Contract',
            lines: (0, review_output_contracts_1.renderReviewOutputContractLines)(),
        }),
        '',
        'Milestone Overviews:',
    ];
    (0, child_drift_1.appendIssueLines)(lines, result.milestoneOverviewPaths);
    lines.push('', 'Materialized Scaffold Paths:');
    (0, child_drift_1.appendIssueLines)(lines, result.materializedScaffoldPaths);
    lines.push('', 'Child Scaffold Projection Drift:');
    (0, child_drift_1.appendIssueLines)(lines, result.scaffoldProjectionDrift.flatMap((entry) => entry.comparison.drift.map((field) => `${entry.childPath} [${field.kind}] ${field.field}`)));
    lines.push('', 'Legacy Scaffold Migration:');
    (0, child_drift_1.appendIssueLines)(lines, result.scaffoldMigration === null
        ? []
        : [
            `plan ${result.scaffoldMigration.planDigest}`,
            result.scaffoldMigration.previewArgv.join(' '),
        ]);
    lines.push('', 'Milestones With Reconciliation Evidence:');
    (0, child_drift_1.appendIssueLines)(lines, result.reconciledMilestonePaths);
    lines.push('', 'Blocking Issues:');
    (0, child_drift_1.appendIssueLines)(lines, result.blockingIssues);
    lines.push('', 'Warnings:');
    (0, child_drift_1.appendIssueLines)(lines, result.warnings);
    lines.push('', 'Live Warning Findings:');
    (0, child_drift_1.appendIssueLines)(lines, result.evidenceLanes.liveWarnings.map((entry) => `${entry.finding.findingId ?? '(prose-only)'}: ${entry.finding.summary}`));
    lines.push('', 'Historical Resolved Findings:');
    (0, child_drift_1.appendIssueLines)(lines, result.evidenceLanes.historicalResolved.map((entry) => `${entry.finding.findingId}: resolved by ${entry.resolution.resolvedBy}`));
    lines.push('', 'Accepted Residual Findings:');
    (0, child_drift_1.appendIssueLines)(lines, result.evidenceLanes.acceptedResidual.map((entry) => `${entry.findingId ?? '(prose-only)'}: ${entry.summary}`));
    lines.push('', 'Metadata-Hygiene Follow-Ups:');
    (0, child_drift_1.appendIssueLines)(lines, result.metadataHygieneFollowUps);
    lines.push('', 'Expected Administrative Status Drift:');
    (0, child_drift_1.appendIssueLines)(lines, result.administrativeStatusDrift.map((entry) => `${entry.artifactPath}: ${entry.observedStatus ?? '(missing)'} -> ${entry.expectedStatus}`));
    lines.push('', 'Metadata Status Preview Targets:');
    (0, child_drift_1.appendIssueLines)(lines, result.metadataStatusTransitions.map((entry) => `${entry.artifactPath}: ${entry.oldStatus ?? '(missing)'} -> ${entry.newStatus} (${entry.artifactRevision})`));
    lines.push('', 'Recovery Guidance:');
    (0, child_drift_1.appendIssueLines)(lines, result.recoveryGuidance);
    return lines.join('\n');
}
function buildPlanningRecoveryGuidance(options) {
    const guidance = [];
    for (const evaluation of options.modeBalanceEvaluations ?? []) {
        guidance.push(...renderValidatedModeBalanceRecovery(options.repositoryRoot, evaluation));
    }
    if (options.blockingIssues.length > 0) {
        guidance.push(`Address the cited blocking findings in '${options.artifactPath}' and its paired evidence before treating this ${options.reviewKind} review as implementation or closeout proof.`);
    }
    if (options.warnings.length > 0) {
        guidance.push('Carry warnings forward as advisory evidence only; they do not authorize lifecycle changes or other writes by implication.');
    }
    if (options.metadataHygieneFollowUps.length > 0) {
        guidance.push(`Apply metadata follow-ups only through an explicit update or sync command for '${options.artifactPath}' after confirming the evidence remains deterministic.`);
    }
    return [...new Set(guidance)];
}
function renderValidatedModeBalanceRecovery(repositoryRoot, evaluation) {
    if (evaluation.recoveryProtocol.length === 0)
        return [];
    const target = (0, planning_navigation_1.inspectTaskCommandArtifactTarget)(repositoryRoot, evaluation.breakoutTaskDefinitionPath);
    const compatible = target.callable
        && target.taskIdentity === evaluation.breakoutTask
        && (target.evidenceProfile === 'runtime' || target.evidenceProfile === 'hybrid');
    if (compatible) {
        return (0, mode_balance_1.renderDocumentationLoopRecoveryProtocol)(evaluation.recoveryProtocol);
    }
    return [
        `Runtime breakout recovery is not callable because '${evaluation.breakoutTaskDefinitionPath ?? '(missing)'}' is not a materialized runtime or hybrid task_definition owned by '${evaluation.breakoutTask ?? '(missing)'}'. ${target.reason}`,
        `Repair runtime_acceptance.breakout_task on '${evaluation.milestoneOverviewPath}', materialize that exact compatible task pair, then rerun the read-only milestone review. Command: \`node dist/cli/index.js milestone review --milestone-overview ${evaluation.milestoneOverviewPath} --format json\`.`,
    ];
}
function buildPlanningReviewFindings(options) {
    const reviewPrefix = options.reviewKind.toUpperCase();
    return [
        ...options.blockingIssues.map((message) => ({
            code: `${reviewPrefix}_REVIEW_BLOCKING`,
            message,
            severity: 'error',
            path: options.artifactPath,
        })),
        ...options.warnings.map((message) => ({
            ...(0, output_1.createAdvisoryValidationFinding)({
                code: `${reviewPrefix}_REVIEW_WARNING`,
                message,
                path: options.artifactPath,
                advisoryReason: 'weak-evidence',
                recovery: 'Carry this warning forward as advisory review evidence; do not treat it as permission for lifecycle changes or other writes by implication.',
            }),
        })),
        ...options.metadataHygieneFollowUps.map((message) => ({
            ...(0, output_1.createAdvisoryValidationFinding)({
                code: `${reviewPrefix}_REVIEW_METADATA_FOLLOW_UP`,
                message,
                path: options.artifactPath,
                advisoryReason: 'weak-evidence',
                level: 'informational',
                recovery: 'Apply this metadata follow-up only through an explicit update or sync command after confirming the evidence remains deterministic.',
            }),
        })),
    ];
}
