"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderTaskDefinitionMarkdown = renderTaskDefinitionMarkdown;
exports.renderImplementationSummaryMarkdown = renderImplementationSummaryMarkdown;
exports.renderLightweightTaskDefinitionMarkdown = renderLightweightTaskDefinitionMarkdown;
exports.renderLightweightImplementationSummaryMarkdown = renderLightweightImplementationSummaryMarkdown;
exports.renderFromTemplate = renderFromTemplate;
exports.renderFromTemplateUnsafe = renderFromTemplateUnsafe;
const node_fs_1 = __importDefault(require("node:fs"));
const errors_1 = require("../../errors");
const path_resolution_1 = require("../../templates/path-resolution");
const front_matter_utils_1 = require("../front-matter-utils");
const policy_resolution_1 = require("../policy-resolution");
const runtime_acceptance_1 = require("../runtime-acceptance");
const workflow_provenance_1 = require("../workflow-provenance");
const authoring_support_1 = require("./authoring-support");
const navigation_1 = require("./navigation");
const projection_1 = require("./projection");
function renderTaskDefinitionMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/task-definition.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Task definition template is missing.", ["Expected template at .day-shift/templates/task-definition.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: "",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        phase: options.phase,
        milestone: options.milestone,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        phaseOverviewPath: options.phaseOverviewPath,
        milestoneOverviewPath: options.milestoneOverviewPath,
        taskDefinitionPath: "",
        upstreamSpecs: options.upstreamSpecs,
        executionMode: options.executionMode,
        governedPolicy: options.governedPolicy,
        runtimeAcceptance: options.runtimeAcceptance,
        generatedAt: options.generatedAt,
        workflowCliCommand: options.workflowCliCommand,
        replacements: (0, navigation_1.buildStandardTaskReplacements)(options)
    });
}
function renderImplementationSummaryMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/implementation-summary.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Implementation summary template is missing.", ["Expected template at .day-shift/templates/implementation-summary.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: " Implementation Summary",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        phase: options.phase,
        milestone: options.milestone,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        phaseOverviewPath: options.phaseOverviewPath,
        milestoneOverviewPath: options.milestoneOverviewPath,
        taskDefinitionPath: options.taskDefinitionPath,
        upstreamSpecs: options.upstreamSpecs,
        executionMode: options.executionMode,
        governedPolicy: options.governedPolicy,
        runtimeAcceptance: options.runtimeAcceptance,
        generatedAt: options.generatedAt,
        workflowCliCommand: options.workflowCliCommand
    });
}
function renderLightweightTaskDefinitionMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/lightweight-task-definition.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Lightweight task definition template is missing.", ["Expected template at .day-shift/templates/lightweight-task-definition.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: "",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        taskDefinitionPath: "",
        upstreamSpecs: options.upstreamSpecs,
        governedPolicy: options.governedPolicy,
        generatedAt: options.generatedAt,
        workflowCliCommand: `day-shift task new --lightweight --slice-overview ${options.sliceOverviewPath} --task-slug ${options.taskSlug}`
    });
}
function renderLightweightImplementationSummaryMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/lightweight-implementation-summary.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Lightweight implementation summary template is missing.", ["Expected template at .day-shift/templates/lightweight-implementation-summary.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: " Implementation Summary",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        taskDefinitionPath: options.taskDefinitionPath,
        upstreamSpecs: options.upstreamSpecs,
        governedPolicy: options.governedPolicy,
        generatedAt: options.generatedAt,
        workflowCliCommand: `day-shift task new --lightweight --slice-overview ${options.sliceOverviewPath} --task-slug ${options.taskSlug}`
    });
}
function renderFromTemplate(templateText, options) {
    try {
        return renderFromTemplateUnsafe(templateText, options);
    }
    catch (error) {
        if (error instanceof TypeError) {
            throw (0, errors_1.createInvalidConfigError)("Task artifact template metadata updates were rejected.", [error.message], [{
                    code: "TASK_METADATA_UPDATE_BLOCKED",
                    message: error.message,
                    severity: "error"
                }]);
        }
        throw error;
    }
}
function renderFromTemplateUnsafe(templateText, options) {
    const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(options.workflowCliCommand ?? `day-shift task new --milestone-overview ${options.milestoneOverviewPath} --task-slug ${options.taskSlug}`);
    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 = templateText;
    const runtimeAcceptance = options.runtimeAcceptance ?? null;
    const effectiveAgentMode = options.governedPolicy === null
        || options.governedPolicy === undefined
        ? (0, policy_resolution_1.resolveAgentMode)({}).value
        : (0, policy_resolution_1.resolveAgentMode)({ parent: options.governedPolicy.defaultAgentMode }).value;
    const effectiveEvidenceProfile = runtimeAcceptance === null
        && options.governedPolicy !== null
        && options.governedPolicy !== undefined
        ? (0, policy_resolution_1.resolveEvidenceProfile)({
            parent: options.governedPolicy.defaultEvidenceProfile
        }).value
        : (0, policy_resolution_1.resolveEvidenceProfile)({
            task: options.executionMode ?? "runtime"
        }).value;
    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 = {
        "{{task}}": options.taskSlug,
        "{{task_title}}": options.taskTitle,
        "{{workflow_level}}": "governed",
        "{{agent_mode}}": effectiveAgentMode,
        "{{evidence_profile}}": effectiveEvidenceProfile,
        "{{created_at}}": options.generatedAt,
        "{{updated_at}}": options.generatedAt,
        "{{objective}}": "Pending. Document the specific implementation objective before starting work.",
        "{{upstream_context}}": "- Pending. Add upstream context references before implementation.",
        "{{target_paths}}": "- Pending. Add implementation target paths before implementation.",
        "{{current_behavior}}": "Pending. Describe current behavior before implementation.",
        "{{desired_behavior}}": "Pending. Describe desired behavior before implementation.",
        "{{runtime_delta}}": "Pending. Because evidence_profile defaults to `runtime`, replace this section before implementation with runtime target files, expected behavior change, verification commands with expected evidence, and rollback path. Switch evidence_profile to `contract` only for contract-only evidence work, or to `hybrid` when the task must carry both runtime implementation evidence and contract evidence to complete the milestone.",
        "{{acceptance_criteria}}": "- Pending. Add acceptance criteria before implementation.",
        "{{validation_commands}}": "```sh\n# Pending\n```",
        "{{rollback_recovery}}": "Pending. Describe rollback or recovery approach before implementation.",
        "{{risks}}": "- Pending. Capture implementation risks before execution.",
        "{{dependencies}}": "- Pending. Add repository-relative artifact dependency paths before implementation.",
        "{{constraints}}": "- Pending. Add scope constraints before implementation.",
        "{{assumptions}}": "- None currently. Add reviewable planning assumptions when they are needed.",
        "{{lifecycle_closure_expectations}}": "Pending. Specify closure evidence before implementation.",
        "{{open_questions}}": "- None currently.",
        "{{summary}}": "Pending. This implementation summary is initialized as the stable execution artifact for the task.",
        "{{changed_paths}}": "None yet. Populate this section when implementation begins and verify the intended task-scoped code changes landed.",
        "{{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.",
        "{{scope_classification}}": "Not started. Expected scope is limited to this task's declared implementation seams.",
        "{{deviations}}": "None yet.",
        "{{risks_and_follow_ups}}": "Residual risk remains until executable behavior, changed-file verification, and validation evidence are recorded."
    };
    for (const [token, replacement] of Object.entries({
        ...replacementMap,
        ...(options.replacements ?? {})
    })) {
        text = text.split(token).join(replacement);
    }
    text = (0, front_matter_utils_1.applyNonArtifactFrontMatterFieldUpdates)(text, {
        workflow_provenance: workflowProvenance.workflowProvenance,
        workflow_cli_command: workflowProvenance.workflowCliCommand,
        workflow_manual_exception: ""
    }, {
        family: "template",
        allowedKeys: ["workflow_provenance", "workflow_cli_command", "workflow_manual_exception"],
        requiredKeys: ["workflow_provenance", "workflow_cli_command", "workflow_manual_exception"]
    });
    const transitionUpdates = {
        slice: options.slice,
        task: options.taskSlug,
        planning_depth: options.planningDepth
    };
    if (options.phase !== undefined) {
        transitionUpdates.phase = options.phase;
    }
    if (options.milestone !== undefined) {
        transitionUpdates.milestone = options.milestone;
    }
    text = (0, front_matter_utils_1.applyStatusAndPlanningFieldTransition)(text, transitionUpdates);
    const upstreamUpdates = {
        "upstream.slice_overview": options.sliceOverviewPath
    };
    const repositoryRelativePathKeys = [
        "upstream.slice_overview"
    ];
    if (options.phaseOverviewPath !== undefined) {
        upstreamUpdates["upstream.phase_overview"] = options.phaseOverviewPath;
        repositoryRelativePathKeys.push("upstream.phase_overview");
    }
    if (options.milestoneOverviewPath !== undefined) {
        upstreamUpdates["upstream.milestone_overview"] = options.milestoneOverviewPath;
        repositoryRelativePathKeys.push("upstream.milestone_overview");
    }
    if (options.taskDefinitionPath !== "") {
        upstreamUpdates["upstream.task_definition"] = options.taskDefinitionPath;
        repositoryRelativePathKeys.push("upstream.task_definition");
    }
    text = (0, front_matter_utils_1.applyPlanningFrontMatterFieldUpdates)(text, upstreamUpdates, {
        repositoryRelativePathKeys
    });
    text = (0, runtime_acceptance_1.injectRuntimeAcceptanceFrontMatter)(text, runtimeAcceptance);
    const runtimeAttributionRequired = (0, projection_1.taskRuntimeAttributionRequired)(effectiveEvidenceProfile, runtimeAcceptance);
    text = (0, authoring_support_1.injectRuntimeAttributionRequiredFrontMatter)(text, runtimeAttributionRequired);
    text = (0, navigation_1.materializeTaskNavigationPlaceholders)(text, options);
    (0, authoring_support_1.assertPlanningAuthoringCompliance)(options.taskDefinitionPath === "" ? "task_definition" : "implementation_summary", text);
    return text.replace("# " + options.taskTitle + options.titleSuffix + options.titleSuffix, "# " + options.taskTitle + options.titleSuffix);
}
