// tools/import-gherkin.ts — SPEC-613: Import .feature files and append scenarios as BDD criteria.
import { readFile, readdir } from 'node:fs/promises';
import { atomicWriteFile } from '../engine/safety/atomic-write-file.js';
import { join } from 'node:path';
import { specStore } from '../storage/index.js';
import { parseGherkin, scenariosToCriteria } from '../engine/gherkin/index.js';
async function collectGherkinTexts(input) {
    const texts = [];
    if (input.gherkinText) {
        texts.push(input.gherkinText);
    }
    if (input.featureFilePath) {
        texts.push(await readFile(input.featureFilePath, 'utf-8'));
    }
    if (input.featureDir) {
        const entries = await readdir(input.featureDir, { withFileTypes: true });
        for (const entry of entries) {
            if (entry.isFile() && entry.name.endsWith('.feature')) {
                const full = join(input.featureDir, entry.name);
                texts.push(await readFile(full, 'utf-8'));
            }
        }
    }
    return texts;
}
function errorResult(message) {
    return {
        content: [{ type: 'text', text: message }],
        isError: true,
    };
}
function appendCriteriaToSpec(specContent, criteria) {
    const isLean = /^---\n[\s\S]*?criteria:\n/m.test(specContent);
    if (isLean) {
        const yamlCriteria = criteria
            .map((c) => `  - text: "${c.replace(/\n/g, ' ').replace(/"/g, '\\"')}"\n    done: false`)
            .join('\n');
        const historyIdx = specContent.indexOf('history:');
        if (historyIdx !== -1) {
            return specContent.slice(0, historyIdx) + yamlCriteria + '\n' + specContent.slice(historyIdx);
        }
        const closingIdx = specContent.indexOf('---', 4);
        if (closingIdx !== -1) {
            return specContent.slice(0, closingIdx) + yamlCriteria + '\n' + specContent.slice(closingIdx);
        }
    }
    const acHeader = '## Acceptance Criteria';
    const appendedLines = criteria.map((c) => `- [ ] ${c.replace(/\n/g, '\n      ')}`).join('\n');
    const acIndex = specContent.indexOf(acHeader);
    if (acIndex !== -1) {
        const afterHeader = specContent.indexOf('\n', acIndex) + 1;
        return (specContent.slice(0, afterHeader) + appendedLines + '\n' + specContent.slice(afterHeader));
    }
    return specContent.trimEnd() + '\n\n' + acHeader + '\n\n' + appendedLines + '\n';
}
export async function handleImportGherkin(args) {
    const { projectId, specId, featureFilePath, gherkinText, featureDir } = args;
    if (!featureFilePath && !gherkinText && !featureDir) {
        return errorResult(`import_gherkin requires one of: featureFilePath, gherkinText, or featureDir`);
    }
    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 import criteria`);
    }
    let texts;
    try {
        texts = await collectGherkinTexts(args);
    }
    catch (err) {
        return errorResult(`Failed to read Gherkin input: ${String(err)}`);
    }
    if (texts.length === 0) {
        return errorResult(`No Gherkin content found in provided inputs`);
    }
    const allCriteria = [];
    for (const text of texts) {
        const feature = parseGherkin(text);
        allCriteria.push(...scenariosToCriteria(feature));
    }
    if (allCriteria.length === 0) {
        return errorResult(`No scenarios found in provided Gherkin content`);
    }
    let specContent;
    try {
        specContent = await readFile(spec.specPath, 'utf-8');
    }
    catch (err) {
        return errorResult(`Cannot read spec file at '${spec.specPath}': ${String(err)}`);
    }
    const updated = appendCriteriaToSpec(specContent, allCriteria);
    await atomicWriteFile(spec.specPath, updated);
    const text = [
        `# Imported Gherkin — ${specId}`,
        '',
        `Appended **${allCriteria.length}** BDD criteria to \`${spec.specPath}\`.`,
    ].join('\n');
    return {
        content: [{ type: 'text', text }],
        structuredContent: {
            specId,
            appendedCount: allCriteria.length,
            appendedCriteria: allCriteria,
            updatedFilePath: spec.specPath,
        },
    };
}
//# sourceMappingURL=import-gherkin.js.map