// tools/export-gherkin.ts — SPEC-613: Export spec BDD criteria as Cucumber-compatible .feature file.
import { readFile, writeFile } from 'node:fs/promises';
import { specStore } from '../storage/index.js';
import { exportCriteriaAsFeature } from '../engine/gherkin/index.js';
function errorResult(message) {
    return {
        content: [{ type: 'text', text: message }],
        isError: true,
    };
}
function extractLeanYamlCriteria(specContent) {
    const match = /^---\n([\s\S]*?)\n---/.exec(specContent);
    if (!match) {
        return [];
    }
    const frontmatter = match[1] ?? '';
    const criteriaMatch = /\ncriteria:\n([\s\S]*?)(?=\n[a-zA-Z_]+:|$)/.exec('\n' + frontmatter);
    if (!criteriaMatch) {
        return [];
    }
    const block = criteriaMatch[1] ?? '';
    const texts = [];
    for (const line of block.split('\n')) {
        const textMatch = /^\s*-\s*text:\s*"((?:[^"\\]|\\.)*)"/.exec(line);
        if (textMatch?.[1] !== undefined) {
            texts.push(textMatch[1].replace(/\\"/g, '"'));
        }
    }
    return texts;
}
function extractMarkdownCriteria(specContent) {
    const criteria = [];
    let inCriteria = false;
    let currentLines = [];
    const flush = () => {
        if (currentLines.length > 0) {
            criteria.push(currentLines.join('\n').trim());
            currentLines = [];
        }
    };
    for (const line of specContent.split('\n')) {
        if (/acceptance\s+criteria/i.test(line) || /criterios?\s+de\s+aceptaci/i.test(line)) {
            inCriteria = true;
            continue;
        }
        if (!inCriteria) {
            continue;
        }
        if (/^#{1,3}\s/.test(line) && !/acceptance|criterio/i.test(line)) {
            flush();
            break;
        }
        const checkboxMatch = /^\s*[-*]\s*\[.\]\s*(.*)$/.exec(line);
        if (checkboxMatch) {
            flush();
            currentLines.push((checkboxMatch[1] ?? '').trim());
            continue;
        }
        if (/^\s{2,}\S/.test(line) && currentLines.length > 0) {
            currentLines.push(line.trim());
        }
    }
    flush();
    return criteria;
}
function extractCriteriaFromSpec(specContent) {
    const leanCriteria = extractLeanYamlCriteria(specContent);
    if (leanCriteria.length > 0) {
        return leanCriteria;
    }
    return extractMarkdownCriteria(specContent);
}
export async function handleExportGherkin(args) {
    const { projectId, specId, outputPath } = args;
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return errorResult(`Spec '${specId}' not found in project '${projectId}'`);
    }
    if (!spec.specPath) {
        return errorResult(`Spec '${specId}' has no specPath — cannot export criteria`);
    }
    let specContent;
    try {
        specContent = await readFile(spec.specPath, 'utf-8');
    }
    catch (err) {
        return errorResult(`Cannot read spec file at '${spec.specPath}': ${String(err)}`);
    }
    const criteria = extractCriteriaFromSpec(specContent);
    if (criteria.length === 0) {
        return errorResult(`No criteria found in spec '${specId}'`);
    }
    const featureContent = exportCriteriaAsFeature(spec.title, criteria);
    await writeFile(outputPath, featureContent, 'utf-8');
    const text = [
        `# Exported Gherkin — ${specId}`,
        '',
        `Wrote ${criteria.length} criteria as .feature file to \`${outputPath}\`.`,
    ].join('\n');
    return {
        content: [{ type: 'text', text }],
        structuredContent: {
            specId,
            outputPath,
            criteriaCount: criteria.length,
        },
    };
}
//# sourceMappingURL=export-gherkin.js.map