"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectGitStatusPorcelainLines = collectGitStatusPorcelainLines;
exports.renderImplementationSummaryBuildResult = renderImplementationSummaryBuildResult;
exports.renderImplementationSummaryReviewResult = renderImplementationSummaryReviewResult;
exports.requireImplementationSummaryWorkflowTopology = requireImplementationSummaryWorkflowTopology;
exports.implementationSummaryReviewHandoff = implementationSummaryReviewHandoff;
exports.renderReconciliationBuildResult = renderReconciliationBuildResult;
exports.renderReconciliationReviewResult = renderReconciliationReviewResult;
// Responsibility-focused implementation extracted from the public compatibility facade.
const node_child_process_1 = require("node:child_process");
const errors_1 = require("../../errors");
const output_1 = require("../../output");
const selector_evidence_1 = require("../reconciliation/selector-evidence");
const review_output_contracts_1 = require("../review-output-contracts");
function collectGitStatusPorcelainLines(repositoryRoot) {
    const result = (0, node_child_process_1.spawnSync)("git", [
        "-C",
        repositoryRoot,
        "status",
        "--porcelain=v1",
        "--untracked-files=all"
    ], {
        encoding: "utf8"
    });
    if ((result.status !== 0 || result.error !== undefined) && result.stdout.trim() === "") {
        return [];
    }
    return result.stdout
        .split(/\r?\n/)
        .map((line) => line.trimEnd())
        .filter((line) => line.length > 0);
}
function renderImplementationSummaryBuildResult(result) {
    return [
        (0, output_1.renderTerminalHeading)("Implementation summary build", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Task definition", value: result.taskDefinitionPath },
                { label: "Implementation summary", value: result.implementationSummaryPath },
                { label: "Source path", value: result.canonicalDestination.sourcePath },
                { label: "Destination path", value: result.canonicalDestination.destinationPath },
                { label: "Review handoff", value: result.reviewHandoff.handoffKind },
                { label: "Default review rollup", value: result.reviewHandoff.defaultReviewRollup },
                { label: "Task-summary review boundary", value: result.reviewHandoff.taskSummaryReviewBoundary ?? "(unavailable)" },
                { label: "Reconciliation artifact kind", value: result.reviewHandoff.reconciliationArtifactKind ?? "(none)" },
                { label: "Reconciliation required", value: result.reviewHandoff.reconciliationRequired === true ? "yes" : "no" },
                { label: "Organization parents", value: result.reviewHandoff.organizationParents?.join(", ") || "(none)" },
                { label: "Project review capability", value: result.reviewHandoff.projectReviewCapability ?? "(unavailable)" },
                { label: "Task-level reconciliation", value: result.reviewHandoff.taskLevelReconciliation },
                { label: "Action", value: result.action },
                { label: "Changed", value: result.changed ? "yes" : "no" }
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)(result.writeApplied
                    ? {
                        kind: "write-applied",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "implementation summary artifact"
                    }
                    : {
                        kind: "mutating-no-op",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "implementation summary artifact",
                        reason: result.changed ? "Build reported changed content without applying a write." : "Summary already matched the intended paired artifact state."
                    })
            ]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Task-Scoped Change Evidence",
            fields: [
                { label: "Status paths", value: String(result.taskScopedChangeReport.statusPathCount) },
                { label: "Declared-target changed paths", value: String(result.taskScopedChangeReport.declaredTargetChangedPaths.length) },
                { label: "Justified-deviation changed paths", value: String(result.taskScopedChangeReport.justifiedDeviationChangedPaths.length) },
                { label: "Unrelated changed paths", value: String(result.taskScopedChangeReport.unrelatedChangedPathCount) },
                { label: "Invalid changed-path evidence", value: String(result.taskScopedChangeReport.invalidChangedPathEvidenceCount) },
                { label: "Candidate paths", value: String(result.changedPathAuthoring.candidatePaths.length) },
                { label: "Excluded paths", value: String(result.changedPathAuthoring.excludedPaths.length) }
            ],
            lines: [
                ...(result.taskScopedChangeReport.declaredTargetChangedPaths.length === 0
                    ? ["- Declared-target changed paths: none detected."]
                    : result.taskScopedChangeReport.declaredTargetChangedPaths
                        .map((changedPath) => `- Declared-target changed path: ${changedPath}`)),
                ...result.taskScopedChangeReport.justifiedDeviationChangedPaths
                    .map((changedPath) => `- Justified-deviation changed path: ${changedPath}`),
                ...(result.changedPathAuthoring.candidatePaths.length === 0
                    ? ["- Changed Paths candidates: none currently eligible."]
                    : [
                        "- Changed Paths candidate Markdown:",
                        ...result.changedPathAuthoring.renderedMarkdown
                            .split("\n")
                            .map((line) => `  ${line}`)
                    ]),
                ...result.changedPathAuthoring.excludedPaths.map((entry) => `- Excluded Changed Paths candidate: ${entry.path} (${entry.reason})`),
                `- ${result.taskScopedChangeReport.safeContinuationGuidance}`,
                `- ${result.taskScopedChangeReport.explicitAuditGuidance}`
            ]
        })
    ].join("\n");
}
function renderImplementationSummaryReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Implementation summary review", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Task definition", value: result.taskDefinitionPath },
                { label: "Implementation summary", value: result.implementationSummaryPath },
                { label: "Implementation status", value: result.implementationStatus ?? "(missing)" },
                { label: "Artifact status", value: result.artifactStatus ?? "(missing)" },
                { label: "Closeout evidence", value: result.closeoutEvidenceStatus },
                { label: "Effective validation IDs", value: result.validationIdentityProjection.effectiveValidationIds.join(", ") || "(none)" },
                { label: "Superseded validation IDs", value: result.validationIdentityProjection.supersededValidationIds.join(", ") || "(none)" },
                { label: "Task-summary review boundary", value: result.reviewHandoff.taskSummaryReviewBoundary ?? "(unavailable)" },
                { label: "Reconciliation artifact kind", value: result.reviewHandoff.reconciliationArtifactKind ?? "(none)" },
                { label: "Reconciliation required", value: result.reviewHandoff.reconciliationRequired === null
                        ? "(unavailable)"
                        : result.reviewHandoff.reconciliationRequired ? "yes" : "no" },
                { label: "Organization parents", value: result.reviewHandoff.organizationParents.join(", ") || "(none)" },
                { label: "Project review capability", value: result.reviewHandoff.projectReviewCapability ?? "(unavailable)" }
            ],
            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, selector_evidence_1.appendIssueLines)(lines, result.blockingIssues);
    lines.push("", "Warnings:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.warnings);
    lines.push("", "Metadata-Hygiene Follow-Ups:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.metadataHygieneFollowUps);
    lines.push("", "Recovery Guidance:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.recoveryGuidance);
    if (result.findings.length > 0) {
        lines.push("", (0, output_1.renderValidationFindingsText)(result.findings, "Structured Findings"));
    }
    return lines.join("\n");
}
function requireImplementationSummaryWorkflowTopology(taskDefinitionPath, policy) {
    if (policy.topology !== null) {
        return policy.topology;
    }
    throw (0, errors_1.createInvalidConfigError)(`Task definition '${taskDefinitionPath}' does not project a usable workflow topology.`, ["Repair the typed topology findings before building or refreshing the paired implementation summary."], policy.blockingFindings.map((finding) => ({
        code: finding.code,
        message: finding.message,
        severity: "error",
        path: taskDefinitionPath
    })));
}
function implementationSummaryReviewHandoff(policy, validationIdentityProjection) {
    const topology = policy.topology;
    return {
        workflowTopology: topology,
        taskSummaryReviewBoundary: topology?.taskSummaryReviewBoundary ?? null,
        reconciliationArtifactKind: topology?.reconciliationArtifactKind ?? null,
        reconciliationRequired: topology?.reconciliationRequired ?? null,
        organizationParents: topology?.organizationParents ?? [],
        projectReviewCapability: topology?.projectReviewCapability ?? null,
        blockingFindings: topology === null ? policy.blockingFindings : [],
        validationIdentityProjection
    };
}
function renderReconciliationBuildResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Reconciliation build", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Reconciliation mode", value: result.mode },
                { label: "Milestone overview", value: result.milestoneOverviewPath ?? "(not selected)" },
                { label: "Task definition", value: result.taskDefinitionPath ?? "(not selected)" },
                { label: "Reconciliation", value: result.reconciliationPath },
                { label: "Source path", value: result.canonicalDestination.sourcePath },
                { label: "Destination path", value: result.canonicalDestination.destinationPath },
                { label: "Review handoff", value: result.reviewHandoff.handoffKind },
                { label: "Default review rollup", value: result.reviewHandoff.defaultReviewRollup },
                { label: "Task-level reconciliation", value: result.reviewHandoff.taskLevelReconciliation },
                { label: "Action", value: result.action },
                { label: "Changed", value: result.changed ? "yes" : "no" }
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)(result.writeApplied
                    ? {
                        kind: "write-applied",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "reconciliation artifact"
                    }
                    : {
                        kind: "mutating-no-op",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "reconciliation artifact",
                        reason: result.changed ? "Build reported changed content without applying a write." : "Reconciliation already matched the intended artifact state."
                    })
            ]
        }),
        "",
        "Completed Task Summaries:"
    ];
    (0, selector_evidence_1.appendIssueLines)(lines, result.completedTaskSummaries);
    lines.push("", "Incomplete Task Summaries:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.incompleteTaskSummaries);
    return lines.join("\n");
}
function renderReconciliationReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Reconciliation review", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Reconciliation mode", value: result.mode },
                { label: "Milestone overview", value: result.milestoneOverviewPath ?? "(not selected)" },
                { label: "Task definition", value: result.taskDefinitionPath ?? "(not selected)" },
                { label: "Reconciliation", value: result.reconciliationPath },
                { label: "Reconciliation status", value: result.reconciliationStatus ?? "(missing)" },
                { label: "Artifact status", value: result.artifactStatus ?? "(missing)" },
                { label: "Closure evidence", value: result.closureEvidenceStatus },
                { label: "Acceptance receipt", value: result.reviewReceipt?.reviewReceiptId ?? "(not available)" }
            ],
            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, selector_evidence_1.appendIssueLines)(lines, result.blockingIssues);
    lines.push("", "Warnings:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.warnings);
    lines.push("", "Metadata-Hygiene Follow-Ups:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.metadataHygieneFollowUps);
    lines.push("", "Recovery Guidance:");
    (0, selector_evidence_1.appendIssueLines)(lines, result.recoveryGuidance);
    if (result.findings.length > 0) {
        lines.push("", (0, output_1.renderValidationFindingsText)(result.findings, "Structured Findings"));
    }
    return lines.join("\n");
}
