"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reviewMilestoneReconciliation = reviewMilestoneReconciliation;
// Responsibility-focused implementation extracted from the public compatibility facade.
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../errors");
const front_matter_utils_1 = require("../front-matter-utils");
const context_1 = require("../implementation-summary/context");
const contracts_1 = require("../implementation-summary/contracts");
const document_paths_1 = require("../implementation-summary/document-paths");
const semantic_placeholder_1 = require("../semantic-placeholder");
const acceptance_1 = require("./acceptance");
const evidence_review_1 = require("./evidence-review");
const milestone_evidence_1 = require("./milestone-evidence");
const selector_evidence_1 = require("./selector-evidence");
function reviewMilestoneReconciliation(repositoryRoot, milestoneOverviewPathInput) {
    const milestoneOverviewPath = (0, document_paths_1.resolveRepositoryPath)(repositoryRoot, milestoneOverviewPathInput, "milestone overview");
    if (!node_fs_1.default.existsSync(milestoneOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Milestone overview not found at '${milestoneOverviewPath.relative}'.`, ["Pass an existing repository-relative --milestone-overview path."]);
    }
    const milestoneDocument = (0, document_paths_1.parseMarkdownDocument)(milestoneOverviewPath.relative, node_fs_1.default.readFileSync(milestoneOverviewPath.absolute, "utf8"));
    (0, context_1.assertArtifactType)(milestoneDocument.frontMatterLines, milestoneOverviewPath.relative, "milestone_overview");
    const context = (0, context_1.parseMilestoneOverviewContext)(milestoneOverviewPath.relative, milestoneDocument);
    const reconciliationPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(milestoneOverviewPath.relative), "reconciliation.md"));
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    if (!node_fs_1.default.existsSync(reconciliationAbsolute)) {
        throw (0, errors_1.createUsageError)(`Paired reconciliation not found at '${reconciliationPath}'.`, ["Run day-shift reconciliation build first or restore the paired reconciliation.md artifact."]);
    }
    const reconciliationDocument = (0, document_paths_1.parseMarkdownDocument)(reconciliationPath, node_fs_1.default.readFileSync(reconciliationAbsolute, "utf8"));
    (0, context_1.assertArtifactType)(reconciliationDocument.frontMatterLines, reconciliationPath, "reconciliation");
    const taskEvidence = (0, milestone_evidence_1.collectMilestoneTaskEvidence)(repositoryRoot, milestoneOverviewPath.relative);
    const evidenceGaps = [];
    const placeholderResidue = [];
    const alignmentIssues = [];
    const reviewConcerns = [];
    const findingIssues = [];
    const reconciliationArtifact = {
        family: "reconciliation",
        path: reconciliationPath,
        artifactType: "reconciliation"
    };
    const milestoneOverviewArtifact = {
        family: "milestone_overview",
        path: milestoneOverviewPath.relative,
        artifactType: "milestone_overview"
    };
    const reconciliationAffectedPath = {
        role: "finding-location",
        path: reconciliationPath,
        artifact: reconciliationArtifact
    };
    const milestoneOverviewAffectedPath = {
        role: "trace-link",
        path: milestoneOverviewPath.relative,
        artifact: milestoneOverviewArtifact,
        description: "review source milestone overview"
    };
    const recordEvidenceGap = (message, category, affectedPaths = [reconciliationAffectedPath]) => {
        evidenceGaps.push(message);
        findingIssues.push({
            message,
            severity: "error",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths
        });
    };
    const recordPlaceholderResidue = (message, category) => {
        placeholderResidue.push(message);
        findingIssues.push({
            message,
            severity: "error",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths: [reconciliationAffectedPath]
        });
    };
    const recordAlignmentIssue = (message, category, affectedPaths = [reconciliationAffectedPath]) => {
        alignmentIssues.push(message);
        findingIssues.push({
            message,
            severity: "error",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths
        });
    };
    const recordReviewConcern = (message, category, affectedPaths = [reconciliationAffectedPath]) => {
        reviewConcerns.push(message);
        findingIssues.push({
            message,
            severity: "warning",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths
        });
    };
    const reconciliationStatus = (0, selector_evidence_1.readTopLevelField)(reconciliationDocument.frontMatterLines, "reconciliation_status")?.trim() ?? null;
    const artifactStatus = (0, selector_evidence_1.readTopLevelField)(reconciliationDocument.frontMatterLines, "status")?.trim() ?? null;
    const declaredLaterWork = (0, evidence_review_1.collectDeclaredLaterWorkEntries)(repositoryRoot, context);
    const planningIdentityAlignmentIssues = [];
    (0, selector_evidence_1.assertMatchingPlanningIdentity)(context, reconciliationDocument.frontMatterLines, reconciliationPath, planningIdentityAlignmentIssues, [
        "slice",
        "phase",
        "milestone",
        "planning_depth"
    ]);
    for (const planningIdentityAlignmentIssue of planningIdentityAlignmentIssues) {
        recordAlignmentIssue(planningIdentityAlignmentIssue, "metadata-alignment");
    }
    const upstreamMilestoneOverview = (0, selector_evidence_1.readUpstreamField)(reconciliationDocument.frontMatterLines, "milestone_overview")?.trim() ?? null;
    if (upstreamMilestoneOverview !== milestoneOverviewPath.relative) {
        recordAlignmentIssue(`Upstream milestone_overview should point to '${milestoneOverviewPath.relative}', found '${upstreamMilestoneOverview ?? "(missing)"}'.`, "metadata-alignment", [reconciliationAffectedPath, milestoneOverviewAffectedPath]);
    }
    for (const sectionName of contracts_1.RECONCILIATION_SECTIONS) {
        const sectionText = reconciliationDocument.sections.get(sectionName);
        const findingCategory = (0, evidence_review_1.reconciliationSectionFindingCategory)(sectionName);
        if (sectionText === undefined) {
            if (sectionName === "Resolved Findings" && reconciliationStatus === "completed") {
                // Legacy accepted reconciliations remain readable without an automatic
                // rewrite solely to add the newer resolved-history lane.
                continue;
            }
            recordEvidenceGap(`Missing required section '${sectionName}'.`, findingCategory);
            continue;
        }
        if ((0, semantic_placeholder_1.hasSemanticPlaceholderContent)(sectionText)) {
            recordPlaceholderResidue(`Section '${sectionName}' still contains placeholder review content.`, findingCategory);
        }
    }
    if (taskEvidence.completed.length === 0) {
        recordEvidenceGap("No completed task implementation summaries were found for this milestone.", "task-summary-reference-health");
    }
    for (const pendingSummary of taskEvidence.incomplete) {
        const pendingSummaryArtifact = {
            family: "implementation_summary",
            path: pendingSummary.relativePath,
            artifactType: "implementation_summary"
        };
        recordReviewConcern(`Task summary '${pendingSummary.relativePath}' is not complete yet (implementation_status: ${pendingSummary.implementationStatus || "(missing)"}).`, "task-summary-reference-health", [
            reconciliationAffectedPath,
            {
                role: "trace-link",
                path: pendingSummary.relativePath,
                artifact: pendingSummaryArtifact,
                description: "incomplete task implementation-summary evidence"
            }
        ]);
    }
    const completedTaskSummariesText = reconciliationDocument.sections.get("Completed Task Summaries");
    if (completedTaskSummariesText !== undefined && !(0, semantic_placeholder_1.hasSemanticPlaceholderContent)(completedTaskSummariesText)) {
        const referencedSummaryPaths = (0, evidence_review_1.extractImplementationSummaryReferences)(completedTaskSummariesText, reconciliationPath);
        const completedSummaryPaths = new Set(taskEvidence.completed.map((entry) => entry.relativePath));
        const incompleteSummaryPaths = new Set(taskEvidence.incomplete.map((entry) => entry.relativePath));
        const knownSummaryPaths = new Set([...completedSummaryPaths, ...incompleteSummaryPaths]);
        for (const completedSummary of taskEvidence.completed) {
            if (!referencedSummaryPaths.has(completedSummary.relativePath)) {
                const completedSummaryArtifact = {
                    family: "implementation_summary",
                    path: completedSummary.relativePath,
                    artifactType: "implementation_summary"
                };
                recordEvidenceGap(`Completed Task Summaries does not reference completed task summary '${completedSummary.relativePath}'.`, "task-summary-reference-health", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: completedSummary.relativePath,
                        artifact: completedSummaryArtifact,
                        description: "completed task implementation-summary evidence"
                    }
                ]);
            }
        }
        for (const referencedSummaryPath of referencedSummaryPaths) {
            const referencedSummaryArtifact = {
                family: "implementation_summary",
                path: referencedSummaryPath,
                artifactType: "implementation_summary"
            };
            if (!knownSummaryPaths.has(referencedSummaryPath)) {
                recordEvidenceGap(`Completed Task Summaries references stale or undiscovered task summary '${referencedSummaryPath}'.`, "task-summary-reference-health", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: referencedSummaryPath,
                        artifact: referencedSummaryArtifact,
                        description: "stale or undiscovered task implementation-summary reference"
                    }
                ]);
                continue;
            }
            if (incompleteSummaryPaths.has(referencedSummaryPath)) {
                recordReviewConcern(`Completed Task Summaries references incomplete task summary '${referencedSummaryPath}'.`, "task-summary-reference-health", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: referencedSummaryPath,
                        artifact: referencedSummaryArtifact,
                        description: "incomplete task implementation-summary reference"
                    }
                ]);
            }
        }
    }
    if (reconciliationStatus === "completed" && taskEvidence.incomplete.length > 0) {
        recordAlignmentIssue("reconciliation_status is 'completed' while one or more task implementation summaries remain incomplete.", "metadata-alignment");
    }
    if (reconciliationStatus === "completed" && artifactStatus !== "completed") {
        recordAlignmentIssue(`reconciliation_status is 'completed' while shared status is '${artifactStatus ?? "(missing)"}'.`, "metadata-alignment");
    }
    if (reconciliationStatus === "ready_for_review" && artifactStatus !== "active") {
        recordAlignmentIssue(`reconciliation_status is 'ready_for_review' while shared status is '${artifactStatus ?? "(missing)"}'.`, "metadata-alignment");
    }
    if (artifactStatus === "completed" && reconciliationStatus !== "completed") {
        recordAlignmentIssue(`Shared status is 'completed' while reconciliation_status is '${reconciliationStatus ?? "(missing)"}'.`, "metadata-alignment");
    }
    const acceptanceCriteriaReviewText = reconciliationDocument.sections.get("Acceptance Criteria Review");
    if (acceptanceCriteriaReviewText === undefined || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(acceptanceCriteriaReviewText)) {
        recordEvidenceGap("Acceptance Criteria Review does not resolve milestone acceptance criteria against completed task evidence yet.", "acceptance-criteria-coverage");
    }
    else if (contracts_1.UNRESOLVED_ACCEPTANCE_REVIEW_PATTERN.test(acceptanceCriteriaReviewText)) {
        recordEvidenceGap("Acceptance Criteria Review still describes unresolved or incomplete acceptance evidence.", "acceptance-criteria-coverage");
    }
    const validationReviewText = reconciliationDocument.sections.get("Validation Review");
    if (validationReviewText === undefined || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(validationReviewText)) {
        recordEvidenceGap("Validation Review does not summarize reviewable validation evidence yet.", "validation-coverage");
    }
    else if (contracts_1.WEAK_VALIDATION_REVIEW_PATTERN.test(validationReviewText)) {
        recordEvidenceGap("Validation Review still describes missing or weak validation evidence.", "validation-coverage");
    }
    for (const completedSummary of taskEvidence.completed) {
        if (completedSummary.validationText === null || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(completedSummary.validationText)) {
            const completedSummaryArtifact = {
                family: "implementation_summary",
                path: completedSummary.relativePath,
                artifactType: "implementation_summary"
            };
            recordEvidenceGap(`Completed task summary '${completedSummary.relativePath}' does not provide reviewable validation evidence.`, "validation-coverage", [
                reconciliationAffectedPath,
                {
                    role: "trace-link",
                    path: completedSummary.relativePath,
                    artifact: completedSummaryArtifact,
                    description: "completed task validation evidence source"
                }
            ]);
        }
        for (const runtimeEvidenceIssue of (0, selector_evidence_1.collectReconciliationRuntimeEvidenceIssues)(completedSummary)) {
            const completedSummaryArtifact = {
                family: "implementation_summary",
                path: completedSummary.relativePath,
                artifactType: "implementation_summary"
            };
            recordEvidenceGap(runtimeEvidenceIssue, "validation-coverage", [
                reconciliationAffectedPath,
                {
                    role: "trace-link",
                    path: completedSummary.relativePath,
                    artifact: completedSummaryArtifact,
                    description: "runtime or hybrid task implementation-summary evidence source"
                }
            ]);
        }
    }
    const reviewConcernText = reconciliationDocument.sections.get("Review Concerns");
    if ((0, evidence_review_1.hasActionableReviewText)(reviewConcernText)) {
        recordReviewConcern("Review Concerns records authored review concerns that need human disposition.", "review-concern");
        if (reconciliationStatus === "completed" && contracts_1.CONTRADICTS_COMPLETED_STATUS_PATTERN.test(reviewConcernText ?? "")) {
            recordAlignmentIssue("reconciliation_status is 'completed' while Review Concerns still describes unresolved closeout concerns.", "metadata-alignment");
        }
    }
    for (const sectionName of ["Discovered Work", "Backlog Work", "Follow-Up Tasks"]) {
        const sectionText = reconciliationDocument.sections.get(sectionName);
        if ((0, evidence_review_1.hasActionableReviewText)(sectionText)) {
            const declaredLaterWorkMatch = (0, evidence_review_1.matchDeclaredLaterWork)(sectionText ?? "", declaredLaterWork);
            if (declaredLaterWorkMatch !== null) {
                const declarationArtifact = {
                    family: declaredLaterWorkMatch.kind === "milestone" ? "phase_overview" : "slice_overview",
                    path: declaredLaterWorkMatch.sourcePath,
                    artifactType: declaredLaterWorkMatch.kind === "milestone" ? "phase_overview" : "slice_overview"
                };
                recordReviewConcern(`${sectionName} records declared later ${declaredLaterWorkMatch.kind} work '${declaredLaterWorkMatch.slug}' from '${declaredLaterWorkMatch.sourcePath}' and is classified separately from unresolved residual concerns.`, "declared-later-work", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: declaredLaterWorkMatch.sourcePath,
                        artifact: declarationArtifact,
                        description: `parent ${declaredLaterWorkMatch.kind === "milestone" ? "phase" : "slice"} declaration for later ${declaredLaterWorkMatch.kind} '${declaredLaterWorkMatch.slug}'`
                    }
                ]);
                continue;
            }
            recordReviewConcern(`${sectionName} records remaining work as advisory reconciliation evidence.`, "review-concern");
            if (reconciliationStatus === "ready_for_review" || reconciliationStatus === "completed") {
                recordAlignmentIssue(`reconciliation_status is '${reconciliationStatus}' while ${sectionName} still describes unresolved closeout work.`, "metadata-alignment");
            }
        }
    }
    const acceptedResidualWorkText = reconciliationDocument.sections.get("Accepted Residual Work");
    if ((0, evidence_review_1.hasActionableReviewText)(acceptedResidualWorkText)) {
        recordReviewConcern("Accepted Residual Work records accepted residual evidence for visibility.", "review-concern");
    }
    if (reconciliationStatus !== "ready_for_review" && reconciliationStatus !== "completed") {
        recordReviewConcern(`reconciliation_status is '${reconciliationStatus ?? "(missing)"}'; run reconciliation build after task evidence is complete before requesting acceptance.`, "review-concern");
    }
    const lifecycleStateSupportsReview = (reconciliationStatus === "ready_for_review" && artifactStatus === "active")
        || (reconciliationStatus === "completed" && artifactStatus === "completed");
    const closureEvidenceStatus = evidenceGaps.length === 0
        && placeholderResidue.length === 0
        && alignmentIssues.length === 0
        && taskEvidence.incomplete.length === 0
        && lifecycleStateSupportsReview
        ? "sufficient"
        : "insufficient";
    const blockingIssues = [
        ...evidenceGaps,
        ...placeholderResidue,
        ...alignmentIssues
    ];
    const warnings = [...reviewConcerns];
    const metadataHygieneFollowUps = [];
    const recoveryGuidance = (0, evidence_review_1.buildEvidenceReviewRecoveryGuidance)({
        artifactPath: reconciliationPath,
        reviewKind: "reconciliation",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps
    });
    const findings = (0, evidence_review_1.buildEvidenceReviewFindings)({
        artifactPath: reconciliationPath,
        reviewKind: "reconciliation",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        issues: findingIssues
    });
    const reviewReceipt = closureEvidenceStatus === "sufficient"
        && reconciliationStatus === "ready_for_review"
        && artifactStatus === "active"
        ? (0, acceptance_1.buildReconciliationReviewReceipt)(repositoryRoot, {
            mode: "milestone",
            sourcePath: milestoneOverviewPath.relative,
            reconciliationPath,
            reconciliationText: reconciliationDocument.rawText,
            taskSummaryPaths: taskEvidence.completed.map((entry) => entry.relativePath)
        })
        : null;
    return {
        mode: "milestone",
        milestoneOverviewPath: milestoneOverviewPath.relative,
        taskDefinitionPath: null,
        reconciliationPath,
        reconciliationStatus,
        artifactStatus,
        closureEvidenceStatus,
        evidenceGaps,
        placeholderResidue,
        alignmentIssues,
        reviewConcerns,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        recoveryGuidance,
        findings,
        reviewReceipt
    };
}
