import { getSpec } from '../storage/spec-store.js';
import * as knowledgeStore from '../storage/knowledge-store.js';
import { readFile } from 'node:fs/promises';
import { atomicWriteFile } from '../engine/safety/atomic-write-file.js';
import { injectQualityGates } from '../engine/quality-gates/gate-injector.js';
import { compactResult, compactError, formatKeyValue } from './output-formatter.js';
export async function handleInjectQualityGates(projectId, specId, options) {
    const spec = await getSpec(projectId, specId);
    if (!spec) {
        return compactError(`❌ Spec '${specId}' not found`);
    }
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    const language = knowledge?.language ?? undefined;
    const framework = knowledge?.framework ?? undefined;
    const profileCategories = {
        strict: ['security', 'testing', 'architecture', 'performance'],
        standard: ['security', 'testing', 'architecture'],
        minimal: ['security', 'testing'],
    };
    const profile = options?.profile ?? 'standard';
    const categories = options?.categories ?? profileCategories[profile] ?? profileCategories.standard;
    const result = injectQualityGates({
        specType: spec.type,
        risk: spec.risk,
        language,
        framework: framework ?? undefined,
        categories,
    });
    // Append gates section to spec.md if path exists
    if (spec.specPath) {
        try {
            const content = await readFile(spec.specPath, 'utf-8');
            if (!content.includes('## Quality Gates [AUTO]')) {
                await atomicWriteFile(spec.specPath, content + result.markdownSection);
            }
        }
        catch {
            // spec.md not accessible — return gates without writing
        }
    }
    const message = result.count > 0
        ? `Injected ${result.count} quality gates into ${specId}`
        : 'No quality gates matched this spec profile';
    return compactResult(formatKeyValue({
        specId,
        injected: result.count,
        profile,
        message,
        ...Object.fromEntries(Object.entries(result.categoryCounts).map(([k, v]) => [`category:${k}`, v])),
    }, 'Quality Gates'));
}
//# sourceMappingURL=inject-quality-gates-handler.js.map