// tools/semantic-search-handler.ts — Handler for semantic_search tool.
// SPEC-075 AC-07: Generates TF-IDF embedding of query, searches backend.
import { getOrCreateBackend } from '../storage/vector-store/backend-factory.js';
import { TFIDFEngine } from '../engine/vector-store/tfidf.js';
/**
 * Handle a semantic_search request.
 * Embeds the query with TF-IDF, then searches the vector backend.
 */
export async function handleSemanticSearch(args) {
    const { projectId, query, scope = 'all', topK = 5, threshold = 0.3 } = args;
    if (!projectId) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Error: No project ID provided. Run init_project first.',
                },
            ],
            isError: true,
        };
    }
    const backend = await getOrCreateBackend(projectId);
    // Build a TF-IDF engine from existing documents so IDF is accurate
    const type = scope === 'all' ? undefined : scope;
    const allDocs = await backend.getAll(type);
    if (allDocs.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: `No documents found in scope "${scope}". Add specs, patterns, or knowledge first.`,
                },
            ],
        };
    }
    // Build TF-IDF from existing corpus
    const tfidf = new TFIDFEngine();
    for (const doc of allDocs) {
        tfidf.addDocument(doc.content);
    }
    // Embed the query
    const queryEmbedding = tfidf.embed(query);
    // Search
    const results = await backend.searchSimilar(queryEmbedding, topK, threshold, type);
    if (results.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: `No results found for "${query}" in scope "${scope}" with threshold ${String(threshold)}. Try a lower threshold or broader scope.`,
                },
            ],
        };
    }
    const formatted = results.map((r, i) => {
        const truncated = r.entry.content.length > 200 ? `${r.entry.content.slice(0, 200)}...` : r.entry.content;
        return [
            `${String(i + 1)}. [${r.entry.type}] ${r.entry.id}`,
            `   Similarity: ${r.similarity.toFixed(3)}`,
            `   ${truncated}`,
        ].join('\n');
    });
    return {
        content: [
            {
                type: 'text',
                text: `Found ${String(results.length)} results for "${query}":\n\n${formatted.join('\n\n')}`,
            },
        ],
    };
}
//# sourceMappingURL=semantic-search-handler.js.map