// tools/export-spec.ts — MCP tool handler for export_spec (SPEC-097)
import { readFile, mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { specStore, knowledgeStore } from '../storage/index.js';
import { hashProjectPath } from '../storage/base-store.js';
import { exportToSpecKit } from '../engine/spec-kit-exporter.js';
import { stripFrontmatter } from '../engine/frontmatter-parser.js';
async function readFileContent(filePath) {
    try {
        const raw = await readFile(filePath, 'utf-8');
        return stripFrontmatter(raw);
    }
    catch {
        return undefined;
    }
}
function toSlug(title) {
    return title
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-|-$/g, '');
}
function extractFilePlan(specContent) {
    const lines = specContent.split('\n');
    const files = [];
    let inCodeBlock = false;
    let inFilePlan = false;
    for (const line of lines) {
        if (/^#{1,3}\s+file\s+plan/i.test(line)) {
            inFilePlan = true;
            continue;
        }
        if (inFilePlan && /^#{1,3}\s+/.test(line) && !/file\s+plan/i.test(line)) {
            // Next heading after file plan but not a sub-heading of file plan
            if (!line.startsWith('####') && !line.includes('New files') && !line.includes('Modified')) {
                inFilePlan = false;
                continue;
            }
        }
        if (inFilePlan && line.startsWith('```')) {
            inCodeBlock = !inCodeBlock;
            continue;
        }
        if (inFilePlan && inCodeBlock && line.trim()) {
            files.push(line.trim());
        }
    }
    return files;
}
export async function handleExportSpec(params) {
    const projectId = hashProjectPath(params.projectPath);
    const spec = await specStore.getSpec(projectId, params.specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: `Spec "${params.specId}" not found.` }],
            isError: true,
        };
    }
    // Read spec content from disk
    const specContent = await readFileContent(spec.specPath);
    if (!specContent) {
        return {
            content: [{ type: 'text', text: `Cannot read spec file at "${spec.specPath}".` }],
            isError: true,
        };
    }
    // Read optional technical content
    const technicalContent = spec.technicalPath
        ? await readFileContent(spec.technicalPath)
        : undefined;
    // Read optional constitution
    const constitution = await knowledgeStore.getConstitution(projectId);
    const constitutionStr = constitution
        ? constitution.principles
            .map((p) => `- **${p.category}** (${p.enforceLevel}): ${p.principle}`)
            .join('\n')
        : undefined;
    // Extract file plan from spec content
    const filePlan = extractFilePlan(specContent);
    // Generate spec-kit output
    const result = exportToSpecKit(spec, specContent, {
        technicalContent,
        constitution: constitutionStr,
        filePlan: filePlan.length > 0 ? filePlan : undefined,
    });
    // Write to output directory
    const slug = toSlug(spec.title);
    const outputDir = params.outputDir ?? join(params.projectPath, 'planu', 'exports', slug);
    await mkdir(outputDir, { recursive: true });
    const specMdPath = join(outputDir, 'spec.md');
    const planMdPath = join(outputDir, 'plan.md');
    const tasksMdPath = join(outputDir, 'tasks.md');
    await Promise.all([
        writeFile(specMdPath, result.specMd, 'utf-8'),
        writeFile(planMdPath, result.planMd, 'utf-8'),
        writeFile(tasksMdPath, result.tasksMd, 'utf-8'),
    ]);
    return {
        content: [
            {
                type: 'text',
                text: JSON.stringify({
                    message: `Exported ${params.specId} to spec-kit format`,
                    format: 'spec-kit',
                    outputDir,
                    files: [specMdPath, planMdPath, tasksMdPath],
                }, null, 2),
            },
        ],
    };
}
//# sourceMappingURL=export-spec.js.map