import { ti } from '../i18n/index.js';
import { specStore } from '../storage/index.js';
import { analyzeAcGaps } from '../engine/ac-gap-detector.js';
import { readFile } from 'node:fs/promises';
import { stripFrontmatter } from '../engine/frontmatter-parser.js';
import { compactResult, formatKeyValue } from './output-formatter.js';
import { readSpecTechnicalSection } from '../engine/spec-format/read-technical-section.js';
/**
 * Safely reads a markdown file, returning empty string on failure.
 */
async function safeReadMarkdown(filePath) {
    try {
        const raw = await readFile(filePath, 'utf-8');
        return stripFrontmatter(raw);
    }
    catch {
        return '';
    }
}
/**
 * Handles the detect_ac_gaps tool: loads the spec, reads its markdown files,
 * runs the AC gap analyzer, and returns a formatted report.
 */
export async function handleDetectAcGaps(params) {
    const { projectId, specId, categories, minPriority } = params;
    try {
        const spec = await specStore.getSpec(projectId, specId);
        if (!spec) {
            return {
                content: [{ type: 'text', text: ti('spec.notFound', { id: specId }) }],
                isError: true,
            };
        }
        const [specText, technicalRaw] = await Promise.all([
            safeReadMarkdown(spec.specPath),
            readSpecTechnicalSection(spec),
        ]);
        const technicalText = stripFrontmatter(technicalRaw);
        const report = analyzeAcGaps(specId, specText, technicalText, categories, minPriority);
        const result = {
            specId: report.specId,
            existingAcCount: report.existingAcCount,
            coverageScore: report.coverageScore,
            gapCount: report.gaps.length,
            gaps: report.gaps,
            analyzedAt: report.analyzedAt,
            message: report.gaps.length === 0
                ? ti('tools.detect_ac_gaps.noGaps', { specId })
                : ti('tools.detect_ac_gaps.success', {
                    specId,
                    count: String(report.gaps.length),
                }),
        };
        return compactResult(formatKeyValue({
            specId: result.specId,
            existingAcCount: result.existingAcCount,
            coverageScore: result.coverageScore,
            gapCount: result.gaps.length,
            analyzedAt: result.analyzedAt,
            message: result.message,
        }, 'AC Gap Analysis') +
            (result.gaps.length > 0
                ? `\n\n**Gaps**: ${result.gaps.map((g) => g.suggestion).join('; ')}`
                : ''));
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: ti('errors.internalError', { message }) }],
            isError: true,
        };
    }
}
//# sourceMappingURL=detect-ac-gaps.js.map