// engine/release/postmortem-generator.ts — SPEC-737: Post-mortem skeleton writer
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { hashProjectPath, projectDataDir } from '../../storage/base-store.js';
// ---------------------------------------------------------------------------
// Template path
// ---------------------------------------------------------------------------
function templatePath() {
    // Walk up from this file to find templates/postmortem.md
    return join(new URL(import.meta.url).pathname, '../../../../templates/postmortem.md');
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
 * Write a post-mortem skeleton to external Planu project data.
 * Returns the path of the written file.
 */
export async function writePostmortem(input) {
    const { version, reason, smokeTestOutput, transitionLogEntries = [], projectRoot = '.' } = input;
    const isoNow = new Date().toISOString();
    const tsSlug = isoNow.replace(/[:.]/g, '-').replace('T', '_').slice(0, 19);
    const filename = `${version}-${tsSlug}.md`;
    const outDir = join(projectDataDir(hashProjectPath(projectRoot)), 'research', 'postmortems');
    const outPath = join(outDir, filename);
    // Load template
    let template;
    try {
        template = await readFile(templatePath(), 'utf-8');
    }
    catch {
        // Fallback template if file not found
        template = `# Post-mortem: @planu/cli {{version}}\n\n**Date:** {{iso-date}}\n\n## Summary\n\n## Timeline\n\n{{auto-populated from transition-log last 5 entries}}\n\n## Detection\n\n{{auto-populated with smoke-test output}}\n\n## Mitigation\n- npm dist-tag removed at {{ts}}\n- git tag deleted at {{ts}}\n`;
    }
    // Populate template
    const timelineSection = transitionLogEntries.length > 0
        ? transitionLogEntries
            .slice(-5)
            .map((e, i) => `${i + 1}. ${e}`)
            .join('\n')
        : '*(no transition-log entries available)*';
    const detectionSection = smokeTestOutput
        ? `Triggered by smoke test failure:\n\`\`\`\n${smokeTestOutput}\n\`\`\``
        : `Reason: ${reason}`;
    const ts = isoNow;
    const populated = template
        .replace(/\{\{version\}\}/g, version)
        .replace(/\{\{iso-date\}\}/g, isoNow.slice(0, 10))
        .replace(/\{\{severity\}\}/g, 'high')
        .replace(/\{\{owner-or-tbd\}\}/g, 'TBD')
        .replace(/\{\{auto-populated from transition-log last 5 entries\}\}/g, timelineSection)
        .replace(/\{\{auto-populated with smoke-test output\}\}/g, detectionSection)
        .replace(/\{\{ts\}\}/g, ts);
    await mkdir(outDir, { recursive: true });
    await writeFile(outPath, populated, 'utf-8');
    return outPath;
}
//# sourceMappingURL=postmortem-generator.js.map