"use strict";
// community-supreme.ts — Supreme Community Intelligence Layer
// Pattern marketplace, reputation, trends, playbook generation, privacy-first sharing.
// Additive layer — reads from existing community DB tables, adds supreme insights.
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildCommunitySupremeContext = buildCommunitySupremeContext;
exports.formatCommunityContext = formatCommunityContext;
const database_1 = require("../../06-memory/database/database");
function loadSharedPatterns() {
    try {
        const db = (0, database_1.getDb)();
        const rows = db.prepare(`SELECT pattern_id, anonymous_id, category, language, framework, rule, success_rate as qualityScore, usage_count as adoptionCount, votes, shared_at
       FROM community_patterns ORDER BY usage_count DESC LIMIT 20`).all();
        return rows.map((r) => ({
            id: String(r.pattern_id || ''),
            title: r.rule || r.pattern_id || 'Unknown pattern',
            category: r.category || 'general',
            description: r.rule || '',
            language: r.language || 'unknown',
            framework: r.framework || 'none',
            qualityScore: Math.round((r.qualityScore || 0.5) * 100),
            usefulnessScore: 50,
            adoptionCount: r.adoptionCount || 0,
            upvotes: r.votes > 0 ? r.votes : 0,
            downvotes: r.votes < 0 ? Math.abs(r.votes) : 0,
            sharedBy: r.anonymous_id || 'anonymous',
            sharedAt: r.shared_at || new Date().toISOString(),
            tags: [],
        }));
    }
    catch {
        return [];
    }
}
function detectTrends(patterns) {
    const trends = [];
    const categoryMap = new Map();
    for (const p of patterns) {
        const cat = categoryMap.get(p.category) || [];
        cat.push(p);
        categoryMap.set(p.category, cat);
    }
    for (const [category, pats] of categoryMap) {
        if (pats.length < 2)
            continue;
        const avgQuality = pats.reduce((a, p) => a + p.qualityScore, 0) / pats.length;
        const totalAdoptions = pats.reduce((a, p) => a + p.adoptionCount, 0);
        trends.push({
            topic: `${category} patterns`,
            category,
            growthRate: avgQuality >= 70 ? 'rising_fast' : avgQuality >= 50 ? 'stable' : 'declining',
            patternCount: pats.length,
            recentAdoptions: totalAdoptions,
            firstSeenWeeksAgo: 4,
            description: `${pats.length} ${category} patterns shared, avg quality: ${Math.round(avgQuality)}/100`,
        });
    }
    return trends.sort((a, b) => b.patternCount - a.patternCount);
}
function generateRecommendations(teamPatterns, communityPatterns) {
    const recommendations = [];
    const teamSet = new Set(teamPatterns.map(p => p.toLowerCase()));
    for (const cp of communityPatterns) {
        if (teamSet.has(cp.title.toLowerCase()))
            continue;
        if (cp.qualityScore < 60)
            continue;
        recommendations.push({
            forPattern: teamPatterns[0] || 'current setup',
            suggestedPattern: cp.title,
            category: cp.category,
            confidence: cp.qualityScore,
            reason: `Community-rated ${cp.qualityScore}/100. Used by ${cp.adoptionCount} projects. ${cp.description.substring(0, 50)}`,
            adoptionRate: cp.adoptionCount > 50 ? 'high' : cp.adoptionCount > 10 ? 'medium' : 'low',
        });
    }
    return recommendations.sort((a, b) => b.confidence - a.confidence).slice(0, 5);
}
function generatePlaybook(patterns, category) {
    const relevant = patterns.filter(p => p.category === category);
    const top = relevant.sort((a, b) => b.qualityScore - a.qualityScore).slice(0, 5);
    const sections = [
        {
            heading: 'Why This Category Matters',
            content: `${category} is one of the most error-prone areas in software development. The community has shared ${relevant.length} patterns in this category.`,
            patterns: relevant.slice(0, 3).map(p => p.title),
            tips: ['Review the top 3 patterns before starting', 'Consider edge cases early', 'Write tests for the critical path'],
        },
        {
            heading: 'Most Trusted Patterns',
            content: top.map(p => `${p.title}: Quality ${p.qualityScore}/100, ${p.adoptionCount} adoptions\n   ${p.description.substring(0, 100)}`).join('\n\n'),
            patterns: top.map(p => p.title),
            tips: top.map(p => `Study ${p.title} before implementing your own ${category} solution`),
        },
        {
            heading: 'Common Mistakes',
            content: 'The community flagged these anti-patterns in public knowledge.',
            patterns: [],
            tips: [
                'Don\'t skip error handling in critical paths',
                'Don\'t hardcode configuration values',
                'Don\'t ignore community-tested approaches',
            ],
        },
    ];
    return {
        title: `${category.charAt(0).toUpperCase() + category.slice(1)} Best Practices Playbook`,
        category,
        generatedFor: `teams implementing ${category} functionality`,
        generateAt: new Date().toISOString(),
        sections,
        summary: `${relevant.length} community patterns analyzed. Top recommendation: ${top[0]?.title || 'review community patterns'}.`,
    };
}
function calculateReputation() {
    try {
        const db = (0, database_1.getDb)();
        const contributors = db.prepare(`SELECT anonymous_id, COUNT(*) as total, AVG(success_rate) as avg_quality,
              SUM(CASE WHEN votes > 0 THEN votes ELSE 0 END) as upvotes,
              SUM(CASE WHEN votes < 0 THEN ABS(votes) ELSE 0 END) as downvotes
       FROM community_patterns
       GROUP BY anonymous_id
       ORDER BY SUM(CASE WHEN votes > 0 THEN votes ELSE 0 END) DESC
       LIMIT 10`).all();
        return contributors.map((c) => {
            const score = Math.min(100, Math.round(((c.avg_quality || 0.5) * 100) * 0.4 + (Math.min(c.upvotes || 0, 100) * 0.4) + (c.total * 5 * 0.2)));
            return {
                contributorId: c.anonymous_id || 'anonymous',
                totalPatterns: c.total || 0,
                averageQuality: Math.round((c.avg_quality || 0.5) * 100),
                totalUpvotes: c.upvotes || 0,
                totalDownvotes: c.downvotes || 0,
                trustLevel: score >= 75 ? 'expert' : score >= 50 ? 'established' : 'emerging',
                badges: generateBadges(c.total, c.upvotes || 0, Math.round((c.avg_quality || 0.5) * 100)),
                score,
            };
        });
    }
    catch {
        return [];
    }
}
function generateBadges(total, upvotes, avgQuality) {
    const badges = [];
    if (total >= 5)
        badges.push('Prolific Contributor');
    if (total >= 10)
        badges.push('Pattern Library Builder');
    if (upvotes >= 50)
        badges.push('Highly Voted');
    if (upvotes >= 100)
        badges.push('Community Favorite');
    if (avgQuality >= 80)
        badges.push('Quality Master');
    if (avgQuality >= 90)
        badges.push('Elite Quality');
    return badges;
}
function checkPrivacy() {
    return {
        canShare: true,
        risks: [
            'File paths may contain project names',
            'Code snippets may contain company-specific logic',
        ],
        sensitiveDataDetected: ['file_paths', 'commit_messages'],
        anonymizationApplied: true,
        consentRequired: false,
        safeToShareFields: ['pattern description', 'category', 'language', 'framework', 'quality score'],
    };
}
function getCommunityHealth(patterns, trends) {
    return {
        totalPatterns: patterns.length,
        activeContributors: new Set(patterns.map(p => p.sharedBy)).size,
        averageQuality: patterns.length > 0 ? Math.round(patterns.reduce((a, p) => a + p.qualityScore, 0) / patterns.length) : 0,
        trendingCategories: trends.filter(t => t.growthRate === 'rising_fast').map(t => t.category),
        growth: patterns.length > 10 ? 'growing' : 'stable',
    };
}
function buildCommunitySupremeContext() {
    const patterns = loadSharedPatterns();
    const trends = detectTrends(patterns);
    const teamPatterns = []; // Will be filled from team analysis
    const recommendations = generateRecommendations(teamPatterns, patterns);
    const playbook = patterns.length > 0 ? generatePlaybook(patterns, trends[0]?.category || 'general') : null;
    const privacyCheck = checkPrivacy();
    const communityHealth = getCommunityHealth(patterns, trends);
    return {
        trendingPatterns: trends,
        recommendedPatterns: recommendations,
        topSharedPatterns: patterns.slice(0, 5),
        playbook,
        privacyCheck,
        communityHealth,
    };
}
function formatCommunityContext(ctx) {
    const lines = [];
    lines.push('🌍 COMMUNITY');
    if (ctx.communityHealth.totalPatterns === 0) {
        lines.push('   Community patterns not yet available — share your first pattern to seed the network.');
        return lines.join('\n');
    }
    lines.push(`   ${ctx.communityHealth.totalPatterns} patterns shared by ${ctx.communityHealth.activeContributors} contributors`);
    lines.push(`   Health: ${ctx.communityHealth.growth}, avg quality: ${ctx.communityHealth.averageQuality}/100`);
    if (ctx.trendingPatterns.length > 0) {
        lines.push(`   Trending: ${ctx.trendingPatterns.slice(0, 3).map(t => t.category).join(', ')}`);
    }
    if (ctx.recommendedPatterns.length > 0) {
        lines.push('');
        const top = ctx.recommendedPatterns[0];
        lines.push(`   💡 Try: "${top.suggestedPattern}"`);
        lines.push(`      ${top.reason.substring(0, 60)}`);
    }
    if (ctx.playbook) {
        lines.push(`   📖 Playbook: ${ctx.playbook.title} (${ctx.playbook.sections.length} sections)`);
    }
    return lines.join('\n');
}
//# sourceMappingURL=community-supreme.js.map