"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderScaffoldEvidenceLines = renderScaffoldEvidenceLines;
exports.renderMilestonePurpose = renderMilestonePurpose;
exports.renderMilestoneScope = renderMilestoneScope;
exports.renderMilestoneTaskCandidates = renderMilestoneTaskCandidates;
exports.resolveMilestoneTaskCandidateSlug = resolveMilestoneTaskCandidateSlug;
exports.renderMilestoneAcceptanceCriteria = renderMilestoneAcceptanceCriteria;
exports.renderMilestoneDependencies = renderMilestoneDependencies;
exports.renderMilestoneRisks = renderMilestoneRisks;
exports.renderMilestoneValidationFocus = renderMilestoneValidationFocus;
exports.listOrFallback = listOrFallback;
exports.sentenceCase = sentenceCase;
exports.verbPolicySafeProse = verbPolicySafeProse;
exports.trimTerminalPunctuation = trimTerminalPunctuation;
exports.ensureTerminalPunctuation = ensureTerminalPunctuation;
exports.truncateSlug = truncateSlug;
exports.renderMilestoneReconciliationMarkdown = renderMilestoneReconciliationMarkdown;
exports.assertPlanningAuthoringCompliance = assertPlanningAuthoringCompliance;
const node_fs_1 = __importDefault(require("node:fs"));
const errors_1 = require("../../errors");
const path_resolution_1 = require("../../templates/path-resolution");
const authoring_policy_1 = require("../authoring-policy");
function renderScaffoldEvidenceLines(evidence, authored) {
    return authored.tasks.flatMap((task) => [
        `- \`${task.slug}\`:`,
        ...(task.criterionIds.length === 0
            ? []
            : [`  - criterion_ids: ${task.criterionIds.join(", ")}`]),
        ...(task.sharedCriterionIds.length === 0
            ? []
            : [`  - shared_criterion_ids: ${task.sharedCriterionIds.join(", ")}`]),
        ...task.acceptanceCriteria.map((entry) => `  - acceptance: ${verbPolicySafeProse(entry)}`),
        ...(task.currentBehavior === null
            ? []
            : [`  - current_behavior: ${verbPolicySafeProse(task.currentBehavior)}`]),
        `  - desired_behavior: ${verbPolicySafeProse(task.desiredBehavior || task.description)}`,
        ...(task.ownership.length > 0 ? task.ownership : evidence.ownership).map((entry) => `  - ownership: ${verbPolicySafeProse(entry)}`),
        ...(task.dependencies.length > 0 ? task.dependencies : evidence.dependencies)
            .map((entry) => `  - dependency: ${entry}`),
        ...(task.targetPaths.length > 0 ? task.targetPaths : evidence.targetPaths)
            .map((entry) => `  - target: ${entry}`),
        ...(task.adapterPaths.length > 0 ? task.adapterPaths : evidence.adapterPaths)
            .map((entry) => `  - adapter: ${entry}`),
        ...(task.validationCommands.length > 0
            ? task.validationCommands
            : evidence.validationCommands).map((entry) => `  - validation: ${entry}`),
        ...(task.rollback.length > 0 ? task.rollback : evidence.rollback)
            .map((entry) => `  - rollback: ${entry}`)
    ]);
}
function renderMilestonePurpose(options) {
    if (options.milestoneDescription !== "") {
        return `Implement the \`${options.milestoneSlug}\` milestone: ${sentenceCase(verbPolicySafeProse(options.milestoneDescription))}`;
    }
    if (options.phasePurpose !== "") {
        return `Advance phase \`${options.phase}\` by completing the \`${options.milestoneSlug}\` milestone within the parent phase purpose: ${verbPolicySafeProse(options.phasePurpose)}`;
    }
    return `Complete the \`${options.milestoneSlug}\` milestone with explicit scope, validation evidence, and traceability to the parent phase.`;
}
function renderMilestoneScope(options) {
    const normalizedDescription = normalizeMilestoneScopeIntent(options.milestoneDescription);
    const ownershipAlreadyDeclaresOutcome = normalizedDescription !== ""
        && options.scaffoldEvidence.ownership.some((item) => normalizeMilestoneScopeIntent(item) === normalizedDescription);
    const scoped = [
        options.milestoneDescription === "" || ownershipAlreadyDeclaresOutcome
            ? undefined
            : `Deliver the declared milestone outcome: ${verbPolicySafeProse(options.milestoneDescription)}`,
        ...options.scaffoldEvidence.ownership.map((item) => `Own the child-specific implementation boundary: ${verbPolicySafeProse(item)}`)
    ].filter((item) => item !== undefined);
    return listOrFallback(scoped, [
        "Keep milestone work bounded to the parent phase declaration and directly related implementation surfaces.",
        "Preserve parent and source traceability in generated planning artifacts."
    ]);
}
function normalizeMilestoneScopeIntent(value) {
    return value.trim().replace(/[.!?]+$/u, "").toLocaleLowerCase();
}
function renderMilestoneTaskCandidates(tasks) {
    return tasks.map((task) => `- \`${task.slug}\`: ${ensureTerminalPunctuation(verbPolicySafeProse(task.description))}`);
}
function resolveMilestoneTaskCandidateSlug(milestoneSlug) {
    const baseSlug = milestoneSlug.replace(/^\d{2}-/, "");
    return truncateSlug(baseSlug.startsWith("implement-")
        ? `01-${baseSlug}`
        : `01-implement-${baseSlug}`);
}
function renderMilestoneAcceptanceCriteria(options) {
    const criteria = [
        options.milestoneDescription === "" ? undefined : `The generated work satisfies the declared milestone outcome: ${verbPolicySafeProse(options.milestoneDescription)}`,
        ...options.milestoneAcceptanceCriteria.map((item) => verbPolicySafeProse(item))
    ].filter((item) => item !== undefined);
    return listOrFallback(criteria, [
        "Milestone task outcomes are traceable to the parent phase declaration.",
        "Validation evidence covers the milestone behavior without broadening the phase scope."
    ]);
}
function renderMilestoneDependencies(options) {
    return listOrFallback(options.scaffoldEvidence.dependencies, ["No repository artifact dependency beyond the authored milestone contract."]);
}
function renderMilestoneRisks(options) {
    return listOrFallback(options.phaseRisks.slice(0, 4).map((item) => `Parent phase risk to manage: ${item}`), ["Implementation may reveal additional contract gaps that should be recorded as discovered work instead of silently broadening scope."]);
}
function renderMilestoneValidationFocus(options) {
    return listOrFallback(options.scaffoldEvidence.validationCommands.map((item) => `Run the child-specific validation command: ${item}`), ["Run focused validation for generated planning artifacts and changed implementation surfaces."]);
}
function listOrFallback(items, fallback) {
    const normalized = items
        .map((item) => item.trim())
        .filter((item, index, allItems) => item !== "" && allItems.indexOf(item) === index);
    return (normalized.length === 0 ? fallback : normalized).map((item) => `- ${item}`);
}
function sentenceCase(value) {
    if (value === "") {
        return value;
    }
    return `${value[0].toLowerCase()}${value.slice(1)}`;
}
function verbPolicySafeProse(value) {
    return value.replace(/\bdefine\b/gi, (match) => {
        return match[0] === match[0].toUpperCase() ? "Specify" : "specify";
    });
}
function trimTerminalPunctuation(value) {
    return value.replace(/[.!?]+\s*$/, "");
}
function ensureTerminalPunctuation(value) {
    const normalized = value.trim();
    if (normalized === "")
        return normalized;
    return /[.!?]$/u.test(normalized) ? normalized : `${normalized}.`;
}
function truncateSlug(value) {
    const parts = value.split("-");
    while (parts.join("-").length > 72 && parts.length > 4) {
        parts.splice(parts.length - 2, 1);
    }
    return parts.join("-");
}
function renderMilestoneReconciliationMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/milestone-reconciliation.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Milestone reconciliation template is missing.", ["Expected template at .day-shift/templates/milestone-reconciliation.md"]);
    }
    const upstreamSpecsBlock = options.upstreamSpecs
        .map((entry) => {
        return [
            `    - id: ${entry.id}`,
            `      depth: ${entry.depth}`,
            `      ref: ${JSON.stringify(entry.ref)}`,
            `      source_type: ${JSON.stringify(entry.sourceType)}`
        ].join("\n");
    })
        .join("\n");
    let text = node_fs_1.default.readFileSync(templatePath, "utf8");
    text = text.replace([
        "  specs:",
        "    - id: \"{{spec_id}}\"",
        "      depth: \"{{spec_depth}}\"",
        "      ref: \"{{spec_ref}}\"",
        "      source_type: \"{{source_type}}\""
    ].join("\n"), ["  specs:", upstreamSpecsBlock].join("\n"));
    const replacementMap = {
        "{{slice}}": options.slice,
        "{{phase}}": options.phase,
        "{{milestone}}": options.milestoneSlug,
        "{{planning_depth}}": options.planningDepth,
        "{{workflow_provenance}}": "cli",
        "{{workflow_cli_command}}": options.workflowCliCommand
            ?? `day-shift milestone new --phase-overview ${options.phaseOverviewPath} --milestone-slug ${options.milestoneSlug}`,
        "{{workflow_manual_exception}}": "",
        "{{slice_overview}}": options.sliceOverviewPath,
        "{{phase_overview}}": options.phaseOverviewPath,
        "{{milestone_overview}}": options.milestoneOverviewPath,
        "{{milestone_title}}": options.milestoneTitle,
        "{{review_status}}": "Pending. This reconciliation artifact is initialized as the default milestone review rollup path for completed task summaries.",
        "{{milestone_intent}}": "Review whether milestone outcomes and child task planning remain aligned with deterministic path and traceability contracts.",
        "{{completed_task_summaries}}": "- Pending. Add completed task implementation summaries as milestone execution work finishes.",
        "{{acceptance_criteria_review}}": "Pending review after task implementation summaries are available.",
        "{{planned_work}}": "- Execute and validate milestone tasks against the settled phase and milestone generation contracts.",
        "{{discovered_work}}": "None yet.",
        "{{backlog_work}}": "None yet. Record out-of-scope follow-up work here if implementation or review surfaces it.",
        "{{validation_review}}": "Pending. Summarize targeted CLI validation evidence once milestone tasks complete.",
        "{{follow_up_tasks}}": "Pending. Add concrete next tasks here only if reconciliation identifies remaining work after review.",
        "{{review_concerns}}": "Residual review risk remains until all milestone task summaries confirm executable behavior and validation evidence.",
        "{{final_notes}}": "Pending milestone review."
    };
    for (const [token, replacement] of Object.entries(replacementMap)) {
        text = text.split(token).join(replacement);
    }
    assertPlanningAuthoringCompliance("reconciliation", text);
    return text;
}
function assertPlanningAuthoringCompliance(artifactType, markdownText) {
    const issues = (0, authoring_policy_1.auditPlanningArtifactAuthoring)({
        artifactPath: `generated ${artifactType}`,
        artifactType,
        markdownText
    });
    if (issues.length > 0) {
        throw (0, errors_1.createUsageError)(`Planning authoring policy rejected generated ${artifactType} scaffold text.`, (0, authoring_policy_1.formatPlanningAuthoringIssues)(issues));
    }
}
