"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveReconciliationSectionValues = resolveReconciliationSectionValues;
exports.resolveTaskReconciliationSectionValues = resolveTaskReconciliationSectionValues;
exports.renderImplementationSummaryDocument = renderImplementationSummaryDocument;
exports.resolveSummaryLifecycleLines = resolveSummaryLifecycleLines;
exports.assertLightweightTaskPath = assertLightweightTaskPath;
exports.implementationSummaryIdentityKeys = implementationSummaryIdentityKeys;
// 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 path_resolution_1 = require("../../templates/path-resolution");
const front_matter_utils_1 = require("../front-matter-utils");
const reconciliation_resolution_1 = require("../reconciliation-resolution");
const defaults_1 = require("../reconciliation/defaults");
const selector_evidence_1 = require("../reconciliation/selector-evidence");
const semantic_placeholder_1 = require("../semantic-placeholder");
const contracts_1 = require("./contracts");
const template_rendering_1 = require("./template-rendering");
function resolveReconciliationSectionValues(document, taskEvidence, context, reconciliationPath) {
    const defaults = (0, defaults_1.getDefaultReconciliationSections)(taskEvidence, context);
    for (const [sectionName, generatedValue] of Object.entries(defaults)) {
        if (contracts_1.GENERATED_RECONCILIATION_SECTIONS.has(sectionName)) {
            defaults[sectionName] = generatedValue;
            continue;
        }
        const existing = document?.sections.get(sectionName);
        if (existing === undefined || existing.trim() === "") {
            defaults[sectionName] = generatedValue;
            continue;
        }
        const preservedExisting = (0, selector_evidence_1.removeTemplateScaffoldContent)(existing);
        if ((0, semantic_placeholder_1.hasSemanticPlaceholderContent)(preservedExisting)) {
            defaults[sectionName] = generatedValue;
            continue;
        }
        defaults[sectionName] = (0, selector_evidence_1.sectionContradictsTaskEvidence)(sectionName, preservedExisting, taskEvidence)
            ? generatedValue
            : preservedExisting;
    }
    return (0, reconciliation_resolution_1.materializeReconciliationFindingIdentities)(reconciliationPath, defaults);
}
function resolveTaskReconciliationSectionValues(document, context, taskEvidence, rationale, reconciliationPath) {
    const defaults = (0, defaults_1.getDefaultTaskReconciliationSections)(context, taskEvidence, rationale);
    for (const [sectionName, defaultValue] of Object.entries(defaults)) {
        const existing = document?.sections.get(sectionName);
        if (existing === undefined || existing.trim() === "") {
            defaults[sectionName] = defaultValue;
            continue;
        }
        const preservedExisting = (0, selector_evidence_1.removeTemplateScaffoldContent)(existing);
        defaults[sectionName] = (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(preservedExisting) ? defaultValue : preservedExisting;
    }
    return (0, reconciliation_resolution_1.materializeReconciliationFindingIdentities)(reconciliationPath, defaults);
}
function renderImplementationSummaryDocument(repositoryRoot, context, options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot,
        templatePath: `.day-shift/templates/${context.planningDepth === "lightweight"
            ? "lightweight-implementation-summary.md"
            : "implementation-summary.md"}`
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Implementation summary template is missing.", [`Expected template at ${(0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, templatePath))}`]);
    }
    let text = node_fs_1.default.readFileSync(templatePath, "utf8");
    text = (0, template_rendering_1.serializeWorkflowManualExceptionField)(text, "implementation_summary", options.metadata);
    text = (0, template_rendering_1.replaceImplementationSummaryUpstream)(text, context);
    if (context.workflowLevel === "basic" || context.workflowLevel === "structured") {
        text = (0, template_rendering_1.projectDirectImplementationSummaryIdentity)(text, context);
    }
    const replacements = {
        "{{slice}}": context.slice,
        "{{phase}}": context.phase ?? "",
        "{{milestone}}": context.milestone ?? "",
        "{{task}}": context.task,
        "{{implementation_order}}": context.implementationOrder ?? "",
        "{{workflow_level}}": context.workflowLevel,
        "{{agent_mode}}": context.agentMode,
        "{{evidence_profile}}": context.executionMode,
        "current_attempt_id: null\nattempts: []": options.lifecycleLines.join("\n"),
        "{{planning_depth}}": context.planningDepth,
        "{{workflow_provenance}}": options.metadata.workflowProvenance,
        "{{workflow_cli_command}}": options.metadata.workflowCliCommand,
        "{{task_title}}": context.title,
        "{{slice_overview}}": context.sliceOverviewPath,
        "{{phase_overview}}": context.phaseOverviewPath ?? "",
        "{{milestone_overview}}": context.milestoneOverviewPath ?? "",
        "{{task_definition}}": context.taskDefinitionPath,
        "implementation_status: pending": `implementation_status: ${options.metadata.implementationStatus}`,
        "status: draft": `status: ${options.metadata.status}`,
        "{{summary}}": options.sections["Summary"],
        "- `{{changed_paths}}`": options.sections["Changed Paths"],
        "{{acceptance_criteria_results}}": options.sections["Acceptance Criteria Results"],
        "{{validation_performed}}": options.sections["Validation Performed"],
        "{{validation_exceptions}}": options.sections["Validation Exceptions"] ?? "None.",
        "{{scope_classification}}": options.sections["Scope Classification"],
        "{{runtime_evidence_boundary}}": options.sections["Runtime Evidence Boundary"] ?? "Not evaluated yet.",
        "{{deviations}}": options.sections["Deviations"],
        "{{risks_and_follow_ups}}": options.sections["Risks and Follow-Ups"],
        "{{open_questions}}": options.sections["Open Questions"]
    };
    return (0, template_rendering_1.replaceAll)(text, replacements);
}
function resolveSummaryLifecycleLines(document) {
    if (document === null) {
        return ["current_attempt_id: null", "attempts: []"];
    }
    const lines = document.frontMatterLines;
    const currentAttempt = (0, selector_evidence_1.readTopLevelField)(lines, "current_attempt_id")?.trim();
    const preserved = [
        `current_attempt_id: ${currentAttempt === undefined || currentAttempt === "" ? "null" : currentAttempt}`
    ];
    const attemptsIndex = lines.findIndex((line) => /^attempts:\s*/.test(line));
    if (attemptsIndex < 0) {
        preserved.push("attempts: []");
    }
    else {
        preserved.push(lines[attemptsIndex]);
        for (let index = attemptsIndex + 1; index < lines.length && /^\s+/.test(lines[index]); index += 1) {
            preserved.push(lines[index]);
        }
    }
    for (const field of [
        "implementation_status",
        "review_disposition",
        "status",
        "completed_at"
    ]) {
        const value = (0, selector_evidence_1.readTopLevelField)(lines, field)?.trim();
        if (value !== undefined && value !== "")
            preserved.push(`${field}: ${value}`);
    }
    return preserved;
}
function assertLightweightTaskPath(filePath, frontMatterLines) {
    const taskSlug = (0, selector_evidence_1.readRequiredTopLevelField)(frontMatterLines, filePath, "task");
    const expectedSuffix = `/tasks/${taskSlug}/task-definition.md`;
    if (!filePath.endsWith(expectedSuffix)) {
        throw (0, errors_1.createUsageError)(`Lightweight task definition '${filePath}' must live under a direct slice tasks/<task-slug>/ directory.`, [`Expected path suffix: ${expectedSuffix}`]);
    }
}
function implementationSummaryIdentityKeys(context) {
    if (context.workflowLevel === "basic") {
        return context.implementationOrder !== null
            ? ["task", "implementation_order", "planning_depth"]
            : ["task", "planning_depth"];
    }
    if (context.workflowLevel === "structured") {
        return ["task", "planning_depth"];
    }
    if (context.planningDepth === "lightweight") {
        return ["slice", "task", "planning_depth"];
    }
    return ["slice", "phase", "milestone", "task", "planning_depth"];
}
