// tools/learn.ts — Store learned patterns for project knowledge enrichment
// Persists architecture, convention, estimation, stack, and quality patterns
// to pattern-store for future use by estimation, auditing, and spec generation.
// SPEC-011: adds dispatchFeedbackEvent for feedback loop dispatch.
import { patternStore, knowledgeStore } from '../storage/index.js';
import { t, ti } from '../i18n/index.js';
export async function handleLearn(args) {
    const { projectId, type, pattern, source } = args;
    // 1. Validate project exists
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    if (!knowledge) {
        return {
            content: [{ type: 'text', text: t('project.notFound') }],
            isError: true,
        };
    }
    // 2. Check for existing similar pattern to prevent duplicates
    const existingPatterns = await patternStore.listPatterns(projectId);
    const duplicate = existingPatterns.find((p) => p.type === type && p.pattern.toLowerCase() === pattern.toLowerCase());
    if (duplicate) {
        // Increment usage count instead of creating a duplicate
        const updated = await patternStore.incrementPatternUsage(projectId, duplicate.id);
        return {
            content: [
                {
                    type: 'text',
                    text: `Pattern already exists (id: ${duplicate.id}). Usage count incremented to ${updated.usageCount}.`,
                },
                {
                    type: 'text',
                    text: JSON.stringify({
                        action: 'incremented',
                        patternId: duplicate.id,
                        type: duplicate.type,
                        pattern: duplicate.pattern,
                        usageCount: updated.usageCount,
                    }, null, 2),
                },
            ],
        };
    }
    // 3. Create new pattern
    const patternId = `PAT-${type.substring(0, 3).toUpperCase()}-${Date.now().toString(36).toUpperCase()}`;
    const learnedPattern = {
        id: patternId,
        projectId,
        type,
        pattern,
        source: source ?? 'user-defined',
        learnedAt: new Date().toISOString(),
        confidence: 0.8, // Initial confidence; increases with usage
        usageCount: 1,
    };
    await patternStore.addPattern(projectId, learnedPattern);
    // 4. Build output
    const output = {
        action: 'created',
        patternId,
        type,
        pattern,
        source: learnedPattern.source,
        totalPatterns: existingPatterns.length + 1,
        patternsByType: buildPatternSummary(existingPatterns, learnedPattern),
    };
    return {
        content: [
            {
                type: 'text',
                text: ti('tools.learn_pattern.success', { type, pattern }),
            },
            {
                type: 'text',
                text: JSON.stringify(output, null, 2),
            },
        ],
    };
}
function buildPatternSummary(existing, newPattern) {
    const all = [...existing, newPattern];
    const summary = {};
    for (const p of all) {
        summary[p.type] = (summary[p.type] ?? 0) + 1;
    }
    return summary;
}
/**
 * SPEC-011: Dispatch a feedback loop event to the project's feedback history.
 * Silently ignores errors so it never blocks the calling operation.
 */
export async function dispatchFeedbackEvent(projectId, event) {
    try {
        await knowledgeStore.saveFeedbackEvent(projectId, event);
    }
    catch {
        // Feedback dispatch is best-effort — never block the calling operation
    }
}
//# sourceMappingURL=learn.js.map