import { listSpecs } from '../storage/spec-store.js';
import { hashProjectPath } from '../storage/base-store.js';
import { getAllDecisions } from '../storage/decision-store.js';
import { loadLessons } from '../storage/lessons-store.js';
import { searchDecisions, findSimilarProblems, extractLessonsFromText, detectKnowledgeGaps, buildKnowledgeSummary, } from '../engine/knowledge-base.js';
import { formatSuccess, formatError, toolResult } from './response-helpers.js';
// ---------------------------------------------------------------------------
// semantic_decision_search
// ---------------------------------------------------------------------------
export async function handleSemanticDecisionSearch(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    if (!args.query.trim()) {
        return toolResult(formatError('query is required'), undefined, true);
    }
    const projectId = hashProjectPath(args.projectPath);
    const decisions = await getAllDecisions(projectId);
    const limit = Math.min(args.limit ?? 5, 20);
    const results = searchDecisions(decisions, args.query, limit);
    const lines = [
        `Query: "${args.query}"`,
        `Found ${String(results.length)} relevant decision(s):`,
        '',
    ];
    for (const r of results) {
        lines.push(`  [score: ${r.relevanceScore.toFixed(3)}] ${r.title}`);
        lines.push(`    Spec: ${r.specId} | Reason: ${r.content.slice(0, 80)}`);
    }
    if (results.length === 0) {
        lines.push('  No matching decisions found.');
    }
    return toolResult(formatSuccess('Decision Search', lines.join('\n')), {
        results,
    });
}
// ---------------------------------------------------------------------------
// similar_problems_finder
// ---------------------------------------------------------------------------
export async function handleSimilarProblemsFinder(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    if (!args.query.trim()) {
        return toolResult(formatError('query is required'), undefined, true);
    }
    const projectId = hashProjectPath(args.projectPath);
    const specs = await listSpecs(projectId);
    const limit = Math.min(args.limit ?? 5, 20);
    const results = findSimilarProblems(specs, args.query, limit);
    const lines = [`Query: "${args.query}"`, `Found ${String(results.length)} similar spec(s):`, ''];
    for (const r of results) {
        lines.push(`  [${(r.overlapScore * 100).toFixed(0)}% match] ${r.specId}: ${r.title}`);
        lines.push(`    Matched terms: ${r.matchedTerms.join(', ')}`);
    }
    if (results.length === 0) {
        lines.push('  No similar specs found.');
    }
    return toolResult(formatSuccess('Similar Problems', lines.join('\n')), {
        results,
    });
}
// ---------------------------------------------------------------------------
// extract_lessons_from_text
// ---------------------------------------------------------------------------
export function handleExtractLessonsFromText(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    if (!args.text.trim()) {
        return toolResult(formatError('text is required'), undefined, true);
    }
    const lessons = extractLessonsFromText(args.text);
    const lines = [`Extracted ${String(lessons.length)} lesson(s) from text:`, ''];
    for (const l of lessons) {
        lines.push(`  [${l.category}] ${l.text}`);
    }
    if (lessons.length === 0) {
        lines.push('  No lesson patterns detected. Try including phrases like:');
        lines.push('  "we learned that", "the problem was", "always", "never", "avoid"');
    }
    return toolResult(formatSuccess('Extracted Lessons', lines.join('\n')), {
        lessons,
    });
}
// ---------------------------------------------------------------------------
// knowledge_gap_detector
// ---------------------------------------------------------------------------
export async function handleKnowledgeGapDetector(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const projectId = hashProjectPath(args.projectPath);
    const [specs, decisions, lessons] = await Promise.all([
        listSpecs(projectId),
        getAllDecisions(projectId),
        loadLessons(args.projectPath),
    ]);
    const gaps = detectKnowledgeGaps(specs, decisions, lessons);
    const lines = [`Knowledge gaps found: ${String(gaps.length)}`, ''];
    for (const g of gaps) {
        lines.push(`  [${g.type}] ${g.description}`);
    }
    if (gaps.length === 0) {
        lines.push('  No knowledge gaps detected. Great job documenting!');
    }
    return toolResult(formatSuccess('Knowledge Gaps', lines.join('\n')), {
        gaps,
    });
}
// ---------------------------------------------------------------------------
// knowledge_summary
// ---------------------------------------------------------------------------
export async function handleKnowledgeSummary(args) {
    if (!args.projectPath.trim()) {
        return toolResult(formatError('projectPath is required'), undefined, true);
    }
    const projectId = hashProjectPath(args.projectPath);
    const [specs, decisions, lessons] = await Promise.all([
        listSpecs(projectId),
        getAllDecisions(projectId),
        loadLessons(args.projectPath),
    ]);
    const summary = buildKnowledgeSummary(specs, decisions, lessons);
    const lines = [
        `Knowledge Summary — ${args.projectPath}`,
        '',
        `Specs: ${String(summary.totalSpecs)} | With decisions: ${String(summary.specsWithDecisions)}`,
        `Decisions: ${String(summary.totalDecisions)} | Lessons: ${String(summary.totalLessons)}`,
        summary.topCategories.length > 0
            ? `Top lesson categories: ${summary.topCategories.join(', ')}`
            : 'No lessons recorded yet.',
        `Gaps detected: ${String(summary.gaps.length)}`,
    ];
    return toolResult(formatSuccess('Knowledge Summary', lines.join('\n')), summary);
}
//# sourceMappingURL=knowledge-base-handler.js.map