"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderLegacyMilestoneOverviewMarkdown = renderLegacyMilestoneOverviewMarkdown;
exports.legacyMilestoneTaskCandidateSlugs = legacyMilestoneTaskCandidateSlugs;
const governed_hierarchy_context_1 = require("./governed-hierarchy-context");
const runtime_acceptance_1 = require("./runtime-acceptance");
const workflow_provenance_1 = require("./workflow-provenance");
/**
 * Reproduces the pre-authored-scaffold milestone overview byte contract. This
 * renderer exists only to prove that a legacy artifact is untouched before the
 * explicit scaffold-recovery lane replaces it.
 */
function renderLegacyMilestoneOverviewMarkdown(options) {
    const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(options.workflowCliCommand
        ?? `day-shift milestone new --phase-overview ${options.phaseOverviewPath} --milestone-slug ${options.milestoneSlug}`);
    const upstreamSpecs = 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");
    const scaffoldEvidence = legacyMilestoneScaffoldEvidence(options);
    return (0, runtime_acceptance_1.injectRuntimeAcceptanceFrontMatter)([
        "---",
        "artifact_schema_version: 1",
        "artifact_type: milestone_overview",
        `slice: ${options.slice}`,
        `phase: ${options.phase}`,
        `milestone: ${options.milestoneSlug}`,
        `planning_depth: ${options.planningDepth}`,
        ...(0, governed_hierarchy_context_1.renderGovernedHierarchyPolicyLines)(options.governedPolicy),
        `workflow_provenance: ${workflowProvenance.workflowProvenance}`,
        `workflow_cli_command: ${JSON.stringify(workflowProvenance.workflowCliCommand)}`,
        "status: draft",
        "upstream:",
        "  specs:",
        upstreamSpecs,
        `  slice_overview: ${options.sliceOverviewPath}`,
        `  phase_overview: ${options.phaseOverviewPath}`,
        "---",
        "",
        `# ${options.milestoneTitle}`,
        "",
        "## Purpose",
        "",
        renderPurpose(options),
        "",
        "## Scope",
        "",
        ...renderScope(options),
        "",
        "## Navigation",
        "",
        `- ${options.phaseOverviewPath}`,
        `- ${options.sliceOverviewPath}`,
        "",
        "## Tasks",
        "",
        ...renderTaskCandidates(options),
        "",
        "## Acceptance Criteria",
        "",
        ...renderAcceptanceCriteria(options),
        "",
        "## Dependencies",
        "",
        ...renderDependencies(options),
        "",
        "## Risks",
        "",
        ...renderRisks(options),
        "",
        "## Validation Focus",
        "",
        ...renderValidationFocus(options),
        "",
        "## Implementation Target Paths",
        "",
        ...scaffoldEvidence.targetPaths.map((entry) => `- ${entry}`),
        "",
        "## Validation Commands",
        "",
        "```sh",
        ...scaffoldEvidence.validationCommands,
        "```",
        "",
        "## Rollback / Recovery",
        "",
        ...scaffoldEvidence.rollback.map((entry) => `- ${entry}`),
        "",
        "## Scaffold Evidence",
        "",
        ...renderScaffoldEvidenceLines(scaffoldEvidence),
        "",
        "## Open Questions",
        "",
        "- None currently.",
        ""
    ].join("\n"), options.runtimeAcceptance, { includeBreakoutPolicy: true });
}
function legacyMilestoneScaffoldEvidence(options) {
    const validationCommand = `node dist/cli/index.js validation smoke --scope planning --artifact ${options.overviewRelativePath}`;
    return {
        childKind: "milestone",
        childSlug: options.milestoneSlug,
        ownership: [
            options.milestoneDescription === ""
                ? `Milestone '${options.milestoneSlug}' planning workspace declared by '${options.phaseOverviewPath}'.`
                : options.milestoneDescription
        ],
        dependencies: [options.phaseOverviewPath],
        targetPaths: [
            options.overviewRelativePath,
            options.reconciliationRelativePath
        ],
        adapterPaths: ["src/cli/commands/milestone-new/index.ts"],
        validationCommands: [validationCommand],
        rollback: [
            `Remove the newly created '${options.overviewRelativePath}' and '${options.reconciliationRelativePath}' if scaffold validation fails.`
        ],
        requiredAdapter: true,
        adapterRequirementReasons: ["explicit-adapter-path"],
        missingEvidence: [],
        complete: true
    };
}
function renderScaffoldEvidenceLines(evidence) {
    return [
        ...evidence.ownership.map((entry) => `- ownership: ${verbPolicySafeProse(entry)}`),
        ...evidence.dependencies.map((entry) => `- dependency: ${entry}`),
        ...evidence.targetPaths.map((entry) => `- target: ${entry}`),
        ...evidence.adapterPaths.map((entry) => `- adapter: ${entry}`),
        ...evidence.validationCommands.map((entry) => `- validation: ${entry}`),
        ...evidence.rollback.map((entry) => `- rollback: ${entry}`)
    ];
}
function renderPurpose(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 renderScope(options) {
    const scoped = [
        options.milestoneDescription === ""
            ? undefined
            : `Deliver the declared milestone outcome: ${verbPolicySafeProse(options.milestoneDescription)}`,
        ...options.phaseScope.slice(0, 4)
            .map((item) => `Apply parent phase scope: ${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 renderTaskCandidates(options) {
    const [contractSlug, coverageSlug] = legacyMilestoneTaskCandidateSlugs(options.milestoneSlug);
    const behaviorNoun = options.milestoneDescription === ""
        ? "declared milestone behavior"
        : trimTerminalPunctuation(verbPolicySafeProse(options.milestoneDescription));
    return [
        `- \`${contractSlug}\`: implement parent-derived scaffold behavior for ${behaviorNoun}.`,
        `- \`${coverageSlug}\`: add focused regression coverage for ${behaviorNoun}.`
    ];
}
function legacyMilestoneTaskCandidateSlugs(milestoneSlug) {
    const baseSlug = milestoneSlug.replace(/^\d{2}-/u, "");
    return [
        truncateSlug(`01-derive-${baseSlug}-contract`),
        truncateSlug(`02-cover-${baseSlug}-behavior`)
    ];
}
function renderAcceptanceCriteria(options) {
    const criteria = [
        options.milestoneDescription === ""
            ? undefined
            : `The generated work satisfies the declared milestone outcome: ${verbPolicySafeProse(options.milestoneDescription)}`,
        ...options.phaseAcceptanceCriteria.slice(0, 4)
            .map((item) => `Parent phase criterion addressed where in scope: ${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 renderDependencies(options) {
    return listOrFallback([
        options.phaseOverviewPath,
        options.sliceOverviewPath,
        ...options.upstreamSpecs.map((entry) => entry.ref),
        ...options.phaseDependencies.slice(0, 3)
    ], [options.phaseOverviewPath]);
}
function renderRisks(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 renderValidationFocus(options) {
    return listOrFallback(options.phaseValidationFocus.slice(0, 4)
        .map((item) => `Use parent phase validation focus: ${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) {
    return value === "" ? value : `${value[0].toLowerCase()}${value.slice(1)}`;
}
function verbPolicySafeProse(value) {
    return value.replace(/\bdefine\b/giu, (match) => match[0] === match[0].toUpperCase() ? "Specify" : "specify");
}
function trimTerminalPunctuation(value) {
    return value.replace(/[.!?]+\s*$/u, "");
}
function truncateSlug(value) {
    const parts = value.split("-");
    while (parts.join("-").length > 72 && parts.length > 4) {
        parts.splice(parts.length - 2, 1);
    }
    return parts.join("-");
}
