"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.materializeTaskNavigationPlaceholders = materializeTaskNavigationPlaceholders;
exports.canonicalNavigationMarkdownLink = canonicalNavigationMarkdownLink;
exports.buildStandardTaskReplacements = buildStandardTaskReplacements;
const node_path_1 = __importDefault(require("node:path"));
const paths_1 = require("../../paths");
const authoring_support_1 = require("./authoring-support");
function materializeTaskNavigationPlaceholders(markdownText, options) {
    const taskDefinitionPath = options.taskDefinitionPath !== ""
        ? options.taskDefinitionPath
        : options.milestoneOverviewPath !== undefined
            ? node_path_1.default.posix.join(node_path_1.default.posix.dirname(options.milestoneOverviewPath), "tasks", options.taskSlug, "task-definition.md")
            : node_path_1.default.posix.join(node_path_1.default.posix.dirname(options.sliceOverviewPath), "tasks", options.taskSlug, "task-definition.md");
    const replacements = new Map([
        [
            "{{slice_overview}}",
            canonicalNavigationMarkdownLink(taskDefinitionPath, options.sliceOverviewPath)
        ]
    ]);
    if (options.phaseOverviewPath !== undefined) {
        replacements.set("{{phase_overview}}", canonicalNavigationMarkdownLink(taskDefinitionPath, options.phaseOverviewPath));
    }
    if (options.milestoneOverviewPath !== undefined) {
        replacements.set("{{milestone_overview}}", canonicalNavigationMarkdownLink(taskDefinitionPath, options.milestoneOverviewPath));
    }
    const newline = markdownText.includes("\r\n") ? "\r\n" : "\n";
    const lines = markdownText.split(/\r?\n/u);
    let inNavigation = false;
    return lines.map((line) => {
        if (line === "## Navigation") {
            inNavigation = true;
            return line;
        }
        if (inNavigation && line.startsWith("## ")) {
            inNavigation = false;
        }
        if (!inNavigation) {
            return line;
        }
        let nextLine = line;
        for (const [placeholder, replacement] of replacements) {
            nextLine = nextLine.split(placeholder).join(replacement);
        }
        return nextLine;
    }).join(newline);
}
function canonicalNavigationMarkdownLink(sourceArtifactPath, targetArtifactPath) {
    const normalizedTarget = (0, paths_1.parseRepositoryRelativePath)(targetArtifactPath).normalizedPath;
    const relativeDestination = node_path_1.default.posix.relative(node_path_1.default.posix.dirname(sourceArtifactPath), normalizedTarget);
    return `[${normalizedTarget}](${relativeDestination === "" ? node_path_1.default.posix.basename(normalizedTarget) : relativeDestination})`;
}
function buildStandardTaskReplacements(options) {
    const validationCommands = options.scaffoldEvidence.validationCommands;
    const rollback = options.scaffoldEvidence.rollback.join(" ");
    const behavior = options.taskDescription === ""
        ? `Implement the \`${options.taskSlug}\` task within the parent milestone contract.`
        : (0, authoring_support_1.sentenceCase)(options.taskDescription);
    return {
        "{{objective}}": behavior,
        "{{upstream_context}}": (0, authoring_support_1.list)([
            options.milestoneOverviewPath,
            options.phaseOverviewPath,
            options.sliceOverviewPath,
            ...options.upstreamSpecs.map((entry) => entry.ref),
            options.milestonePurpose === "" ? undefined : `Parent milestone purpose: ${options.milestonePurpose}`,
            ...options.scaffoldEvidence.dependencies
        ]),
        "{{target_paths}}": (0, authoring_support_1.list)(options.scaffoldEvidence.targetPaths),
        "{{current_behavior}}": options.acceptanceScopedScaffold.currentBehavior,
        "{{desired_behavior}}": options.acceptanceScopedScaffold.desiredBehavior,
        "{{runtime_delta}}": options.executionMode === "contract"
            ? "Not applicable. This contract prerequisite carries inherited acceptance IDs and frozen contract evidence only."
            : [
                `- Runtime target files: ${options.scaffoldEvidence.targetPaths.map((entry) => `\`${entry}\``).join(", ")}.`,
                `- Expected behavior change: ${behavior}`,
                `- Verification commands with expected evidence: ${validationCommands.map((entry) => `\`${entry}\``).join(", ")}.`,
                `- Rollback path: ${rollback}`
            ].join("\n"),
        "{{acceptance_criteria}}": (0, authoring_support_1.listOrPending)(options.acceptanceScopedScaffold.acceptanceCriteria),
        "{{validation_commands}}": validationCommands.length === 0
            ? "```sh\n# Pending: parent milestone did not declare concrete validation commands\n```"
            : ["```sh", ...validationCommands, "```"].join("\n"),
        "{{rollback_recovery}}": rollback,
        "{{risks}}": (0, authoring_support_1.listOrPending)(options.milestoneRisks.slice(0, 4).map((risk) => `Parent milestone risk to manage: ${risk}`)),
        "{{dependencies}}": (0, authoring_support_1.listOrPending)([
            options.milestoneOverviewPath,
            ...options.scaffoldEvidence.dependencies
        ]),
        "{{constraints}}": (0, authoring_support_1.listOrPending)([
            ...options.milestoneScope.slice(0, 4).map((scopeItem) => `Stay within parent milestone scope: ${scopeItem}`),
            "Keep implementation changes inside declared task target paths unless a justified deviation is recorded."
        ]),
        "{{lifecycle_closure_expectations}}": "Complete the paired implementation summary with changed paths, validation evidence, acceptance results, deviations, and follow-up work before milestone reconciliation.",
        "{{open_questions}}": "- None currently."
    };
}
