"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildTaskReconciliationArtifact = buildTaskReconciliationArtifact;
exports.reviewTaskReconciliation = reviewTaskReconciliation;
// 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 context_1 = require("../implementation-summary/context");
const contracts_1 = require("../implementation-summary/contracts");
const document_paths_1 = require("../implementation-summary/document-paths");
const document_rendering_1 = require("../implementation-summary/document-rendering");
const semantic_placeholder_1 = require("../semantic-placeholder");
const acceptance_1 = require("./acceptance");
const build_1 = require("./build");
const document_rendering_2 = require("./document-rendering");
const evidence_review_1 = require("./evidence-review");
const milestone_evidence_1 = require("./milestone-evidence");
const selector_evidence_1 = require("./selector-evidence");
function buildTaskReconciliationArtifact(repositoryRoot, taskDefinitionPathInput, rationale) {
    const taskDefinitionPath = (0, document_paths_1.resolveRepositoryPath)(repositoryRoot, taskDefinitionPathInput, "task definition");
    const context = (0, milestone_evidence_1.loadTaskDefinitionContext)(repositoryRoot, taskDefinitionPath);
    const reconciliationPath = (0, milestone_evidence_1.resolveTaskReconciliationPath)(taskDefinitionPath.relative);
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    const existingText = node_fs_1.default.existsSync(reconciliationAbsolute)
        ? node_fs_1.default.readFileSync(reconciliationAbsolute, "utf8")
        : null;
    const existingDocument = existingText === null
        ? null
        : (0, document_paths_1.parseMarkdownDocument)(reconciliationPath, existingText);
    if (existingDocument !== null) {
        (0, context_1.assertArtifactType)(existingDocument.frontMatterLines, reconciliationPath, "reconciliation");
    }
    const implementationSummaryPath = (0, milestone_evidence_1.resolveTaskImplementationSummaryPath)(taskDefinitionPath.relative);
    const taskEvidence = (0, milestone_evidence_1.collectTaskImplementationSummaryEvidence)(repositoryRoot, implementationSummaryPath);
    const rendered = (0, document_rendering_2.renderTaskReconciliationDocument)(repositoryRoot, context, {
        metadata: (0, context_1.resolveReconciliationMetadataState)(existingDocument, taskDefinitionPath.relative),
        sections: (0, document_rendering_1.resolveTaskReconciliationSectionValues)(existingDocument, context, taskEvidence, rationale, reconciliationPath),
        taskDefinitionPath: taskDefinitionPath.relative,
        implementationSummaryPath
    });
    const changed = existingText !== rendered;
    if (changed) {
        node_fs_1.default.mkdirSync(node_path_1.default.dirname(reconciliationAbsolute), { recursive: true });
        node_fs_1.default.writeFileSync(reconciliationAbsolute, rendered, "utf8");
    }
    return {
        repositoryRoot,
        mode: "task",
        milestoneOverviewPath: context.milestoneOverviewPath,
        taskDefinitionPath: taskDefinitionPath.relative,
        reconciliationPath,
        action: existingText === null ? "created" : "refreshed",
        changed,
        writeApplied: changed,
        commandWriteSummary: (0, build_1.normalizeCanonicalBuildCommandWriteSummary)({
            commandFamily: "reconciliation",
            artifactPath: reconciliationPath,
            action: existingText === null ? "created" : "refreshed",
            changed,
            materialWhenChanged: false
        }),
        completedTaskSummaries: (0, milestone_evidence_1.isReconciliationCompletedSummaryEvidence)(taskEvidence) ? [implementationSummaryPath] : [],
        incompleteTaskSummaries: (0, milestone_evidence_1.isReconciliationCompletedSummaryEvidence)(taskEvidence) ? [] : [implementationSummaryPath],
        canonicalDestination: {
            sourcePath: taskDefinitionPath.relative,
            destinationPath: reconciliationPath,
            destinationKind: "task-reconciliation",
            writeMode: "canonical-paired-artifact",
            writeApplied: changed,
            readOnly: false
        },
        reviewHandoff: {
            sourcePath: taskDefinitionPath.relative,
            destinationPath: reconciliationPath,
            handoffKind: "task-definition-to-task-reconciliation",
            defaultReviewRollup: "milestone-reconciliation",
            taskLevelReconciliation: "explicit-exception-only"
        }
    };
}
function reviewTaskReconciliation(repositoryRoot, taskDefinitionPathInput) {
    const taskDefinitionPath = (0, document_paths_1.resolveRepositoryPath)(repositoryRoot, taskDefinitionPathInput, "task definition");
    const context = (0, milestone_evidence_1.loadTaskDefinitionContext)(repositoryRoot, taskDefinitionPath);
    const reconciliationPath = (0, milestone_evidence_1.resolveTaskReconciliationPath)(taskDefinitionPath.relative);
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    if (!node_fs_1.default.existsSync(reconciliationAbsolute)) {
        throw (0, errors_1.createUsageError)(`Task-level reconciliation not found at '${reconciliationPath}'.`, ["Run day-shift reconciliation build --task-definition <path> first or restore the explicit task-local 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 evidenceGaps = [];
    const placeholderResidue = [];
    const alignmentIssues = [];
    const reviewConcerns = [];
    (0, selector_evidence_1.assertMatchingPlanningIdentity)(context, reconciliationDocument.frontMatterLines, reconciliationPath, alignmentIssues, ["slice", "phase", "milestone", "task", "planning_depth"]);
    const expectedParentLinks = [
        ["slice_overview", context.sliceOverviewPath],
        ["phase_overview", context.phaseOverviewPath],
        ["milestone_overview", context.milestoneOverviewPath],
        ["task_definition", taskDefinitionPath.relative]
    ];
    for (const [key, expected] of expectedParentLinks) {
        const actual = (0, selector_evidence_1.readUpstreamField)(reconciliationDocument.frontMatterLines, key)?.trim() ?? null;
        if (actual !== expected) {
            alignmentIssues.push(`Upstream ${key} should point to '${expected ?? "(missing)"}', found '${actual ?? "(missing)"}'.`);
        }
    }
    for (const sectionName of contracts_1.TASK_RECONCILIATION_SECTIONS) {
        const sectionText = reconciliationDocument.sections.get(sectionName);
        if (sectionText === undefined) {
            if (sectionName === "Resolved Findings"
                && (0, selector_evidence_1.readTopLevelField)(reconciliationDocument.frontMatterLines, "reconciliation_status")?.trim() === "completed") {
                continue;
            }
            evidenceGaps.push(`Missing required section '${sectionName}'.`);
            continue;
        }
        if ((0, semantic_placeholder_1.hasSemanticPlaceholderContent)(sectionText)) {
            placeholderResidue.push(`Section '${sectionName}' still contains placeholder review content.`);
        }
    }
    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;
    if (reconciliationStatus !== "ready_for_review" && reconciliationStatus !== "completed") {
        reviewConcerns.push(`reconciliation_status is '${reconciliationStatus ?? "(missing)"}', so task-level reconciliation is not ready for explicit acceptance.`);
    }
    if (reconciliationStatus === "completed" && artifactStatus !== "completed") {
        alignmentIssues.push(`reconciliation_status is 'completed' while shared status is '${artifactStatus ?? "(missing)"}'.`);
    }
    if (artifactStatus === "completed" && reconciliationStatus !== "completed") {
        alignmentIssues.push(`Shared status is 'completed' while reconciliation_status is '${reconciliationStatus ?? "(missing)"}'.`);
    }
    if (reconciliationStatus === "ready_for_review" && artifactStatus !== "active") {
        alignmentIssues.push(`reconciliation_status is 'ready_for_review' while shared status is '${artifactStatus ?? "(missing)"}'.`);
    }
    const lifecycleStateSupportsReview = (reconciliationStatus === "ready_for_review" && artifactStatus === "active")
        || (reconciliationStatus === "completed" && artifactStatus === "completed");
    const closureEvidenceStatus = evidenceGaps.length === 0
        && placeholderResidue.length === 0
        && alignmentIssues.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
    });
    const implementationSummaryPath = (0, milestone_evidence_1.resolveTaskImplementationSummaryPath)(taskDefinitionPath.relative);
    const reviewReceipt = closureEvidenceStatus === "sufficient"
        && reconciliationStatus === "ready_for_review"
        && artifactStatus === "active"
        ? (0, acceptance_1.buildReconciliationReviewReceipt)(repositoryRoot, {
            mode: "task",
            sourcePath: taskDefinitionPath.relative,
            reconciliationPath,
            reconciliationText: reconciliationDocument.rawText,
            taskSummaryPaths: [implementationSummaryPath]
        })
        : null;
    return {
        mode: "task",
        milestoneOverviewPath: context.milestoneOverviewPath,
        taskDefinitionPath: taskDefinitionPath.relative,
        reconciliationPath,
        reconciliationStatus,
        artifactStatus,
        closureEvidenceStatus,
        evidenceGaps,
        placeholderResidue,
        alignmentIssues,
        reviewConcerns,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        recoveryGuidance,
        findings,
        reviewReceipt
    };
}
