// engine/impact-detector/index.ts — SPEC-586: Orchestrate impact detection on spec:approved
import { readFile, writeFile } from 'node:fs/promises';
import { detectsNewToolRegistration, buildToolRegistrationCriteria } from './tool-registration.js';
import { predictTestBreaks } from './test-break-predictor.js';
async function readFileSafe(p) {
    try {
        return await readFile(p, 'utf-8');
    }
    catch {
        return '';
    }
}
async function injectCriteriaIntoSpec(specPath, criteria) {
    let content = await readFileSafe(specPath);
    if (!content) {
        return;
    }
    const isLean = /^---\n[\s\S]*?criteria:\n/m.test(content);
    if (isLean) {
        const yamlCriteria = criteria
            .map((c) => `  - text: "${c.text.replace(/"/g, '\\"')}"\n    done: false`)
            .join('\n');
        const historyIdx = content.indexOf('history:');
        if (historyIdx !== -1) {
            content = content.slice(0, historyIdx) + yamlCriteria + '\n' + content.slice(historyIdx);
        }
        else {
            const closingIdx = content.indexOf('---', 4);
            if (closingIdx !== -1) {
                content = content.slice(0, closingIdx) + yamlCriteria + '\n' + content.slice(closingIdx);
            }
            else {
                content += '\n' + yamlCriteria;
            }
        }
    }
    else {
        const injected = criteria.map((c) => `- [ ] ${c.text}`).join('\n');
        const acHeader = '## Acceptance Criteria';
        const idx = content.indexOf(acHeader);
        if (idx !== -1) {
            const afterHeader = content.indexOf('\n', idx) + 1;
            content = content.slice(0, afterHeader) + injected + '\n' + content.slice(afterHeader);
        }
        else {
            content += `\n\n${acHeader}\n\n${injected}\n`;
        }
    }
    await writeFile(specPath, content, 'utf-8');
}
export async function runImpactDetector(input) {
    const { specId, specPath, technicalPath, projectPath } = input;
    const [specBody, technicalMd] = await Promise.all([
        readFileSafe(specPath),
        readFileSafe(technicalPath),
    ]);
    const detectedNewTool = detectsNewToolRegistration(specBody, technicalMd);
    const injectedCriteria = detectedNewTool ? buildToolRegistrationCriteria() : [];
    if (injectedCriteria.length > 0) {
        await injectCriteriaIntoSpec(specPath, injectedCriteria).catch((err) => {
            const msg = err instanceof Error ? err.message : String(err);
            console.error(`[impact-detector] Failed to inject criteria for ${specId}:`, msg);
        });
    }
    if (detectedNewTool) {
        predictTestBreaks(projectPath).catch(() => {
            /* best-effort */
        });
    }
    return {
        specId,
        detectedNewTool,
        injectedCriteria,
    };
}
//# sourceMappingURL=index.js.map