"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildReconciliationArtifact = buildReconciliationArtifact;
exports.normalizeCanonicalBuildCommandWriteSummary = normalizeCanonicalBuildCommandWriteSummary;
exports.buildMilestoneReconciliationArtifact = buildMilestoneReconciliationArtifact;
// 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 command_write_summary_1 = require("../../license/command-write-summary");
const front_matter_utils_1 = require("../front-matter-utils");
const context_1 = require("../implementation-summary/context");
const document_paths_1 = require("../implementation-summary/document-paths");
const document_rendering_1 = require("../implementation-summary/document-rendering");
const document_rendering_2 = require("./document-rendering");
const milestone_evidence_1 = require("./milestone-evidence");
const selector_evidence_1 = require("./selector-evidence");
const task_artifact_1 = require("./task-artifact");
function buildReconciliationArtifact(repositoryRoot, options) {
    const selector = (0, selector_evidence_1.resolveReconciliationSelector)(options);
    if (selector.kind === "task") {
        return (0, task_artifact_1.buildTaskReconciliationArtifact)(repositoryRoot, selector.taskDefinitionPath, selector.rationale);
    }
    return buildMilestoneReconciliationArtifact(repositoryRoot, selector.milestoneOverviewPath);
}
function normalizeCanonicalBuildCommandWriteSummary(options) {
    return (0, command_write_summary_1.normalizeCommandWriteSummary)({
        commandFamily: options.commandFamily,
        primaryOutputArtifacts: [options.artifactPath],
        updatedArtifacts: [
            {
                path: options.artifactPath,
                action: options.changed ? options.action : "kept",
                reason: options.materialWhenChanged && options.changed
                    ? undefined
                    : options.changed
                        ? options.action === "created"
                            ? "accepted_create"
                            : "accepted_refresh"
                        : "no_write",
                materialUpdate: options.materialWhenChanged && options.changed ? true : undefined
            }
        ]
    });
}
function buildMilestoneReconciliationArtifact(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);
    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 taskEvidence = (0, milestone_evidence_1.collectMilestoneTaskEvidence)(repositoryRoot, milestoneOverviewPath.relative);
    const metadata = (0, context_1.resolveReconciliationMetadataState)(existingDocument, milestoneOverviewPath.relative, taskEvidence);
    const rendered = (0, document_rendering_2.renderReconciliationDocument)(repositoryRoot, context, {
        metadata,
        sections: (0, document_rendering_1.resolveReconciliationSectionValues)(existingDocument, taskEvidence, context, reconciliationPath),
        milestoneOverviewPath: milestoneOverviewPath.relative
    });
    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: "milestone",
        milestoneOverviewPath: milestoneOverviewPath.relative,
        taskDefinitionPath: null,
        reconciliationPath,
        action: existingText === null ? "created" : "refreshed",
        changed,
        writeApplied: changed,
        commandWriteSummary: normalizeCanonicalBuildCommandWriteSummary({
            commandFamily: "reconciliation",
            artifactPath: reconciliationPath,
            action: existingText === null ? "created" : "refreshed",
            changed,
            materialWhenChanged: false
        }),
        completedTaskSummaries: taskEvidence.completed.map((entry) => entry.relativePath),
        incompleteTaskSummaries: taskEvidence.incomplete.map((entry) => entry.relativePath),
        canonicalDestination: {
            sourcePath: milestoneOverviewPath.relative,
            destinationPath: reconciliationPath,
            destinationKind: "milestone-reconciliation",
            writeMode: "canonical-paired-artifact",
            writeApplied: changed,
            readOnly: false
        },
        reviewHandoff: {
            sourcePath: milestoneOverviewPath.relative,
            destinationPath: reconciliationPath,
            handoffKind: "implementation-summary-to-milestone-reconciliation",
            defaultReviewRollup: "milestone-reconciliation",
            taskLevelReconciliation: "explicit-exception-only"
        }
    };
}
