import { specStore } from '../storage/index.js';
import { readFile, mkdir } from 'node:fs/promises';
import { atomicWriteFile } from '../engine/safety/atomic-write-file.js';
import { join, basename } from 'node:path';
import { replaceSectionInSpec } from '../engine/spec-format/replace-section.js';
export async function handleExportSpec(args) {
    const { hashProjectPath } = await import('../storage/base-store.js');
    const projectId = hashProjectPath(args.projectPath);
    const spec = await specStore.getSpec(projectId, args.specId);
    if (!spec) {
        return {
            content: [{ type: 'text', text: `Spec ${args.specId} not found.` }],
            isError: true,
        };
    }
    let specContent;
    try {
        specContent = await readFile(join(args.projectPath, spec.specPath), 'utf-8');
    }
    catch {
        return {
            content: [{ type: 'text', text: `Cannot read spec file at ${spec.specPath}.` }],
            isError: true,
        };
    }
    const technicalContent = await readFile(join(args.projectPath, spec.technicalPath), 'utf-8').catch(() => '');
    const bundle = {
        version: 1,
        uuid: spec.uuid ?? crypto.randomUUID(),
        originalId: spec.id,
        originalProject: args.projectPath,
        specContent,
        technicalContent,
        exportedAt: new Date().toISOString(),
    };
    const outDir = join(args.projectPath, 'planu', 'exports');
    await mkdir(outDir, { recursive: true });
    const outPath = join(outDir, `${args.specId}.bundle.json`);
    await atomicWriteFile(outPath, JSON.stringify(bundle, null, 2));
    return {
        content: [
            {
                type: 'text',
                text: `Exported ${args.specId} (uuid: ${bundle.uuid}) to ${outPath}.\nUse import_spec in the target project to import it.`,
            },
        ],
    };
}
export async function handleImportSpec(args) {
    let raw;
    try {
        raw = await readFile(args.bundlePath, 'utf-8');
    }
    catch {
        return {
            content: [{ type: 'text', text: `Cannot read bundle at ${args.bundlePath}.` }],
            isError: true,
        };
    }
    const bundle = JSON.parse(raw);
    if (bundle.version !== 1) {
        return {
            content: [{ type: 'text', text: `Unsupported bundle version: ${String(bundle.version)}.` }],
            isError: true,
        };
    }
    const typed = bundle;
    const { hashProjectPath } = await import('../storage/base-store.js');
    const projectId = hashProjectPath(args.projectPath);
    // Check UUID collision
    const existing = await specStore.getSpecByUuid(projectId, typed.uuid);
    if (existing) {
        return {
            content: [
                {
                    type: 'text',
                    text: `Spec with uuid ${typed.uuid} already exists as ${existing.id}. Skipping import.`,
                },
            ],
        };
    }
    // Allocate new local SPEC-NNN
    const allSpecs = await specStore.listSpecs(projectId);
    const maxNum = allSpecs.reduce((max, s) => {
        const m = /^SPEC-(\d+)$/.exec(s.id);
        return m ? Math.max(max, Number(m[1])) : max;
    }, 0);
    const newId = `SPEC-${String(maxNum + 1)}`;
    // Replace ID in content, preserve uuid
    const updatedContent = typed.specContent
        .replace(/^id: SPEC-\d+/m, `id: ${newId}`)
        .replace(/^uuid: .+$/m, `uuid: ${typed.uuid}`);
    // Derive slug from original folder or ID
    const slug = `${newId.toLowerCase()}-imported-${basename(args.bundlePath, '.bundle.json').toLowerCase()}`;
    const specDir = join(args.projectPath, 'planu', 'specs', slug);
    await mkdir(specDir, { recursive: true });
    const specMdPath = join(specDir, 'spec.md');
    await atomicWriteFile(specMdPath, updatedContent);
    // SPEC-1010 PR-C: embed technical content as ## Technical section inside
    // spec.md instead of writing a standalone technical.md file.
    if (typed.technicalContent) {
        await replaceSectionInSpec(specMdPath, 'Technical', typed.technicalContent);
    }
    return {
        content: [
            {
                type: 'text',
                text: `Imported as ${newId} (uuid: ${typed.uuid}, originally ${typed.originalId}).\nFiles written to planu/specs/${slug}/.\nRun list_specs to refresh the registry.`,
            },
        ],
    };
}
//# sourceMappingURL=spec-portability-handler.js.map