// resources/patterns.ts — Learned patterns resource
// Returns all learned patterns across projects from the data store.
import { readFile } from 'node:fs/promises';
import { glob } from 'glob';
import { t } from '../i18n/index.js';
/**
 * Scan the data/projects/ directory for pattern JSON files.
 * Patterns are stored in data/projects/{projectId}/patterns.json
 */
async function loadAllPatterns() {
    const allPatterns = [];
    try {
        const patternFiles = await glob('data/projects/*/patterns.json');
        for (const file of patternFiles) {
            try {
                const raw = await readFile(file, 'utf-8');
                const patterns = JSON.parse(raw);
                if (Array.isArray(patterns)) {
                    allPatterns.push(...patterns);
                }
            }
            catch {
                // Skip malformed files
            }
        }
    }
    catch {
        // No patterns directory yet — that is fine
    }
    return allPatterns;
}
/**
 * MCP resource handler for planu://patterns
 */
export async function handlePatternsResource() {
    const patterns = await loadAllPatterns();
    if (patterns.length === 0) {
        return JSON.stringify({
            count: 0,
            message: t('resources.patterns.notFound'),
            patterns: [],
            byType: {},
        }, null, 2);
    }
    const byType = {};
    for (const p of patterns) {
        byType[p.type] = (byType[p.type] ?? 0) + 1;
    }
    return JSON.stringify({
        count: patterns.length,
        byType,
        patterns: patterns.map((p) => ({
            id: p.id,
            type: p.type,
            pattern: p.pattern,
            source: p.source,
            confidence: p.confidence,
            usageCount: p.usageCount,
            learnedAt: p.learnedAt,
        })),
    }, null, 2);
}
export const patternsResourceDefinition = {
    uri: 'planu://patterns',
    name: 'Learned Patterns',
    description: t('resources.patterns.description'),
    mimeType: 'application/json',
};
//# sourceMappingURL=patterns.js.map