// engine/spec-migrator/fold-technical.ts — SPEC-752
// Folds legacy technical.md body into spec.md's ## Technical section, then deletes technical.md.
// Uses the same pattern as unified-migration.ts (SPEC-630).
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { atomicWriteFile } from '../safety/atomic-write-file.js';
import { safeUnlink } from './git-aware-fs.js';
/**
 * Fold technical.md content into spec.md under a `## Technical` section.
 * Idempotent: returns already_unified if spec.md already has `## Technical`.
 * On success: writes unified spec.md and deletes technical.md.
 *
 * @param specDir      Absolute path to the spec directory.
 * @param projectPath  Project root for git-aware unlink (optional).
 */
export async function foldTechnicalIntoSpec(specDir, projectPath) {
    const specPath = join(specDir, 'spec.md');
    const techPath = join(specDir, 'technical.md');
    try {
        const specContent = await readFile(specPath, 'utf-8');
        // Idempotency check: already has ## Technical section.
        // SPEC-1008: also delete any residual technical.md so the spec dir ends
        // up in the canonical single-file layout. Previously the early-return
        // left the legacy file behind forever.
        if (/\n## Technical(\n|$)/.test(specContent)) {
            try {
                if (projectPath) {
                    await safeUnlink(projectPath, techPath);
                }
                else {
                    const { unlink } = await import('node:fs/promises');
                    await unlink(techPath);
                }
            }
            catch {
                /* technical.md already absent — nothing to clean up */
            }
            return { ok: true, reason: 'already_unified' };
        }
        // Try reading technical.md
        let techContent;
        try {
            techContent = await readFile(techPath, 'utf-8');
        }
        catch {
            return { ok: false, reason: 'no_technical_md' };
        }
        // Strip YAML frontmatter from technical.md before appending
        const techBody = techContent.replace(/^---\n[\s\S]*?\n---\n?/, '').trim();
        const unified = `${specContent.trimEnd()}\n\n## Technical\n\n${techBody}\n`;
        const before = Buffer.byteLength(specContent, 'utf-8');
        const after = Buffer.byteLength(unified, 'utf-8');
        await atomicWriteFile(specPath, unified);
        if (projectPath) {
            await safeUnlink(projectPath, techPath);
        }
        else {
            const { unlink } = await import('node:fs/promises');
            await unlink(techPath);
        }
        return { ok: true, reason: 'ok', byteDelta: after - before };
    }
    catch (err) {
        return { ok: false, reason: 'error', error: String(err) };
    }
}
//# sourceMappingURL=fold-technical.js.map