"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceSpecPlaceholders = replaceSpecPlaceholders;
exports.replaceImplementationSummaryUpstream = replaceImplementationSummaryUpstream;
exports.projectDirectImplementationSummaryIdentity = projectDirectImplementationSummaryIdentity;
exports.serializeImplementationSummaryUpstream = serializeImplementationSummaryUpstream;
exports.replaceAll = replaceAll;
exports.serializeWorkflowManualExceptionField = serializeWorkflowManualExceptionField;
exports.getDefaultImplementationSummarySections = getDefaultImplementationSummarySections;
// Responsibility-focused implementation extracted from the public compatibility facade.
const errors_1 = require("../../errors");
const workflow_provenance_1 = require("../workflow-provenance");
function replaceSpecPlaceholders(templateText, upstreamSpecs) {
    const upstreamSpecsBlock = upstreamSpecs
        .map((entry) => {
        const lines = [
            `    - id: ${entry.id}`,
            `      ref: ${JSON.stringify(entry.ref)}`
        ];
        if (entry.depth !== null && entry.sourceType !== null) {
            lines.splice(1, 0, `      depth: ${entry.depth}`);
            lines.push(`      source_type: ${JSON.stringify(entry.sourceType)}`);
        }
        else if (entry.revision !== null) {
            lines.push(`      revision: ${JSON.stringify(entry.revision)}`);
            if (entry.readiness !== null) {
                lines.push(`      readiness: ${JSON.stringify(entry.readiness)}`);
            }
        }
        return lines.join("\n");
    })
        .join("\n");
    return templateText.replace([
        "  specs:",
        "    - id: \"{{spec_id}}\"",
        "      depth: \"{{spec_depth}}\"",
        "      ref: \"{{spec_ref}}\"",
        "      source_type: \"{{source_type}}\""
    ].join("\n"), ["  specs:", upstreamSpecsBlock].join("\n"));
}
function replaceImplementationSummaryUpstream(templateText, context) {
    const lines = templateText.split(/\r?\n/);
    const closingIndex = lines.findIndex((line, index) => index > 0 && line === "---");
    const upstreamIndex = lines.findIndex((line, index) => index > 0 && index < closingIndex && line === "upstream:");
    if (closingIndex === -1 || upstreamIndex === -1) {
        throw new TypeError("Implementation summary template is missing canonical upstream front matter.");
    }
    let upstreamEndIndex = upstreamIndex + 1;
    while (upstreamEndIndex < closingIndex && /^\s/.test(lines[upstreamEndIndex])) {
        upstreamEndIndex += 1;
    }
    lines.splice(upstreamIndex, upstreamEndIndex - upstreamIndex, ...serializeImplementationSummaryUpstream(context));
    return lines.join("\n");
}
function projectDirectImplementationSummaryIdentity(templateText, context) {
    const lines = templateText.split(/\r?\n/);
    const closingIndex = lines.findIndex((line, index) => index > 0 && line === "---");
    if (closingIndex === -1) {
        throw new TypeError("Implementation summary template is missing valid YAML front matter.");
    }
    const projected = lines
        .filter((line, index) => index >= closingIndex || !/^(slice|phase|milestone):/.test(line));
    if (context.workflowLevel === "basic" && context.implementationOrder !== null) {
        const projectedClosingIndex = projected.findIndex((line, index) => index > 0 && line === "---");
        const taskIndex = projected.findIndex((line, index) => index > 0 && index < projectedClosingIndex && line.startsWith("task:"));
        if (taskIndex === -1) {
            throw new TypeError("Implementation summary template is missing canonical task identity front matter.");
        }
        projected.splice(taskIndex + 1, 0, "implementation_order: \"{{implementation_order}}\"");
    }
    return projected.join("\n");
}
function serializeImplementationSummaryUpstream(context) {
    const lines = ["upstream:"];
    if (context.upstreamSpecs.length === 0) {
        lines.push("  specs: []");
    }
    else {
        lines.push("  specs:");
        for (const entry of context.upstreamSpecs) {
            lines.push(`    - id: ${JSON.stringify(entry.id)}`);
            if (entry.depth !== null) {
                lines.push(`      depth: ${JSON.stringify(entry.depth)}`);
            }
            lines.push(`      ref: ${JSON.stringify(entry.ref)}`);
            if (entry.sourceType !== null) {
                lines.push(`      source_type: ${JSON.stringify(entry.sourceType)}`);
            }
            if (entry.revision !== null) {
                lines.push(`      revision: ${JSON.stringify(entry.revision)}`);
            }
            if (entry.readiness !== null) {
                lines.push(`      readiness: ${JSON.stringify(entry.readiness)}`);
            }
        }
    }
    if (context.workflowLevel === "structured") {
        lines.push(`  work_overview: ${JSON.stringify(context.sliceOverviewPath)}`);
    }
    else if (context.workflowLevel !== "basic") {
        lines.push(`  slice_overview: ${JSON.stringify(context.sliceOverviewPath)}`);
        if (context.phaseOverviewPath !== null) {
            lines.push(`  phase_overview: ${JSON.stringify(context.phaseOverviewPath)}`);
        }
        if (context.milestoneOverviewPath !== null) {
            lines.push(`  milestone_overview: ${JSON.stringify(context.milestoneOverviewPath)}`);
        }
    }
    lines.push(`  task_definition: ${JSON.stringify(context.taskDefinitionPath)}`);
    return lines;
}
function replaceAll(text, replacements) {
    let next = text;
    for (const [token, value] of Object.entries(replacements)) {
        next = next.split(token).join(value);
    }
    return next;
}
function serializeWorkflowManualExceptionField(templateText, artifactType, metadata) {
    const projection = (0, workflow_provenance_1.projectWorkflowManualExceptionField)({
        artifactType,
        workflowProvenance: metadata.workflowProvenance,
        workflowCliCommand: metadata.workflowCliCommand,
        workflowManualException: metadata.workflowManualException
    });
    if (projection.issues.length > 0) {
        throw (0, errors_1.createUsageError)("Artifact serialization rejected invalid workflow provenance before writing.", projection.issues.map((issue) => issue.message));
    }
    return templateText.replace(/^workflow_manual_exception: "\{\{workflow_manual_exception\}\}"\r?\n/m, projection.fieldLine === null ? "" : `${projection.fieldLine}\n`);
}
function getDefaultImplementationSummarySections() {
    return {
        Summary: "Pending. This implementation summary is initialized as the stable execution artifact for the task.",
        "Changed Paths": "- `repository/relative/path`",
        "Acceptance Criteria Results": "Pending review after implementation.",
        "Validation Performed": "None yet. Record validation plus any changed-file inspection used to confirm the intended edits landed without obvious errors, missing edits, or unintended drift.",
        "Validation Exceptions": "None.",
        "Scope Classification": "Not started. Expected scope is limited to this task's declared implementation seams.",
        "Runtime Evidence Boundary": "Not evaluated yet. Runtime and hybrid summaries must not claim runtime implementation without runtime changed paths and executable validation evidence.",
        Deviations: "None yet.",
        "Risks and Follow-Ups": "Residual risk remains until executable behavior, changed-file verification, and validation evidence are recorded.",
        "Open Questions": "- None currently."
    };
}
