"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ALLOWED_FIELDS = void 0;
exports.validatePrivacy = validatePrivacy;
exports.sanitizePatternData = sanitizePatternData;
exports.registerCommunityPattern = registerCommunityPattern;
exports.getCommunityPatterns = getCommunityPatterns;
exports.ingestCommunityOutcomes = ingestCommunityOutcomes;
exports.getCommunityStats = getCommunityStats;
exports.computeRankings = computeRankings;
exports.computeTrends = computeTrends;
exports.computeClusters = computeClusters;
exports.generatePlaybooks = generatePlaybooks;
exports.computeBenchmarks = computeBenchmarks;
exports.takeSnapshot = takeSnapshot;
exports.getEvolution = getEvolution;
exports.getEvolutionTrend = getEvolutionTrend;
exports.computeReputation = computeReputation;
exports.getTopReputation = getTopReputation;
exports.generateInsights = generateInsights;
exports.getCommunityRankings = getCommunityRankings;
exports.getCommunityTrends = getCommunityTrends;
exports.getCommunityPlaybooks = getCommunityPlaybooks;
exports.getCommunityBenchmarks = getCommunityBenchmarks;
exports.getCommunityInsights = getCommunityInsights;
exports.getCommunityClusters = getCommunityClusters;
exports.resetCommunity = resetCommunity;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
// ═══════════════════════════════════════════════════════════════
// STORAGE
// ═══════════════════════════════════════════════════════════════
const STORE_PATH = path.join(os.homedir(), '.fivo', 'cell', 'community-intelligence.json');
function ensureDir() {
    const dir = path.dirname(STORE_PATH);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}
function loadStore() {
    ensureDir();
    try {
        if (fs.existsSync(STORE_PATH))
            return JSON.parse(fs.readFileSync(STORE_PATH, 'utf-8'));
    }
    catch { }
    return { patterns: {}, devCount: 0, outcomeCount: 0, history: [], lastSnapshot: 0, version: 1 };
}
function saveStore(data) {
    ensureDir();
    fs.writeFileSync(STORE_PATH, JSON.stringify(data, null, 2), 'utf-8');
}
// ═══════════════════════════════════════════════════════════════
// PRIVACY GUARD
// ═══════════════════════════════════════════════════════════════
exports.ALLOWED_FIELDS = new Set([
    'patternId', 'category', 'language', 'description', 'totalDevs', 'totalUses',
    'totalSuccess', 'totalFailure', 'successRate', 'confidence', 'health',
    'firstSeen', 'lastSeen', 'trend', 'reputation',
]);
function validatePrivacy(data) {
    if (!data || typeof data !== 'object')
        return false;
    for (const key of Object.keys(data)) {
        if (!exports.ALLOWED_FIELDS.has(key))
            return false;
    }
    return true;
}
function sanitizePatternData(data) {
    const safe = {};
    for (const key of exports.ALLOWED_FIELDS) {
        if (data[key] !== undefined)
            safe[key] = data[key];
    }
    return safe;
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 1: COMMUNITY PATTERN REGISTRY
// ═══════════════════════════════════════════════════════════════
function registerCommunityPattern(patternId, category, language, description, successCount, failureCount, devId) {
    const store = loadStore();
    const total = successCount + failureCount;
    const existing = store.patterns[patternId];
    if (devId) {
        store.devCount++;
        if (existing)
            existing.totalDevs++;
    }
    if (existing) {
        existing.totalUses += total;
        existing.totalSuccess += successCount;
        existing.totalFailure += failureCount;
        existing.lastSeen = Date.now();
        existing.successRate = existing.totalUses > 0 ? existing.totalSuccess / existing.totalUses : 0;
        existing.confidence = 0.5 + existing.successRate * 0.3 + Math.min(existing.totalDevs / 100, 0.2);
        existing.health = Math.round(existing.successRate * 100);
        existing.reputation = Math.min(existing.totalDevs / 10, 10) * (existing.successRate);
        existing.trend = classifyTrend(existing.patternId, existing.totalUses, store);
    }
    else {
        store.patterns[patternId] = {
            patternId, category, language, description,
            totalDevs: devId ? 1 : 0, totalUses: total,
            totalSuccess: successCount, totalFailure: failureCount,
            successRate: total > 0 ? successCount / total : 0,
            confidence: 0.5 + (total > 0 ? successCount / total : 0) * 0.3,
            health: total > 0 ? Math.round((successCount / total) * 100) : 0,
            firstSeen: Date.now(), lastSeen: Date.now(),
            trend: 'stable', reputation: 0,
        };
    }
    store.outcomeCount += total;
    saveStore(store);
    return store.patterns[patternId];
}
function getCommunityPatterns(filters) {
    const store = loadStore();
    let entries = Object.values(store.patterns);
    if (filters?.category)
        entries = entries.filter(e => e.category === filters.category);
    if (filters?.language)
        entries = entries.filter(e => e.language === filters.language);
    if (filters?.minSuccessRate)
        entries = entries.filter(e => e.successRate >= filters.minSuccessRate);
    if (filters?.minDevs)
        entries = entries.filter(e => e.totalDevs >= filters.minDevs);
    const sortBy = filters?.sortBy || 'totalUses';
    entries.sort((a, b) => {
        if (sortBy === 'successRate')
            return b.successRate - a.successRate;
        if (sortBy === 'reputation')
            return b.reputation - a.reputation;
        if (sortBy === 'confidence')
            return b.confidence - a.confidence;
        return b.totalUses - a.totalUses;
    });
    if (filters?.limit)
        entries = entries.slice(0, filters.limit);
    return entries;
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 2: COMMUNITY OUTCOME ENGINE
// ═══════════════════════════════════════════════════════════════
function ingestCommunityOutcomes(outcomes, devId) {
    let ingested = 0;
    let updated = 0;
    for (const o of outcomes) {
        const safe = sanitizePatternData(o);
        const result = registerCommunityPattern(safe.patternId || o.patternId, safe.category || o.category, safe.language || o.language, safe.description || o.description, o.successCount, o.failureCount, devId);
        if (result)
            updated++;
        ingested++;
    }
    return { ingested, updated };
}
function getCommunityStats() {
    const store = loadStore();
    const entries = Object.values(store.patterns);
    const avgSuccessRate = entries.length > 0 ? entries.reduce((s, e) => s + e.successRate, 0) / entries.length : 0;
    const avgConfidence = entries.length > 0 ? entries.reduce((s, e) => s + e.confidence, 0) / entries.length : 0;
    return {
        totalPatterns: entries.length, totalDevs: store.devCount, totalOutcomes: store.outcomeCount,
        avgSuccessRate, avgConfidence,
    };
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 3: COMMUNITY RANKINGS
// ═══════════════════════════════════════════════════════════════
function computeRankings() {
    const store = loadStore();
    const entries = Object.values(store.patterns);
    const byCategory = new Map();
    for (const e of entries) {
        if (!byCategory.has(e.category))
            byCategory.set(e.category, []);
        byCategory.get(e.category).push(e);
    }
    const rankings = [];
    for (const [category, catEntries] of byCategory) {
        const scored = catEntries.map(e => ({
            patternId: e.patternId, score: e.successRate * 0.4 + e.reputation * 0.3 + Math.min(e.totalUses / 100, 1) * 0.3,
            successRate: e.successRate, totalUses: e.totalUses,
        }));
        scored.sort((a, b) => b.score - a.score);
        const top = scored.slice(0, 20).map((s, i) => ({ ...s, rank: i + 1 }));
        rankings.push({ category, entries: top });
    }
    return rankings.sort((a, b) => b.entries.length - a.entries.length);
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 4: COMMUNITY TRENDS
// ═══════════════════════════════════════════════════════════════
function classifyTrend(patternId, currentUsage, store) {
    const snapshots = store.history;
    if (snapshots.length < 2)
        return 'stable';
    const prev = snapshots[snapshots.length - 1];
    const prevPattern = prev.rankings.flatMap(r => r.entries).find(e => e.patternId === patternId);
    const prevUsage = prevPattern?.totalUses || 0;
    if (prevUsage === 0)
        return currentUsage > 10 ? 'rising' : 'stable';
    const ratio = currentUsage / prevUsage;
    if (ratio > 2)
        return 'exploding';
    if (ratio > 1.2)
        return 'rising';
    if (ratio < 0.5)
        return 'declining';
    return 'stable';
}
function computeTrends() {
    const store = loadStore();
    const snapshots = store.history;
    const prevSnapshot = snapshots.length >= 2 ? snapshots[snapshots.length - 2] : null;
    const currentSnapshot = snapshots.length >= 1 ? snapshots[snapshots.length - 1] : null;
    if (!prevSnapshot || !currentSnapshot) {
        return Object.values(store.patterns).map(p => ({
            patternId: p.patternId,
            direction: p.trend,
            currentUsage: p.totalUses,
            previousUsage: p.totalUses,
            changePct: 0,
            period: 'initial',
        }));
    }
    const prevMap = new Map(prevSnapshot.rankings.flatMap(r => r.entries).map(e => [e.patternId, e]));
    return Object.values(store.patterns).map(p => {
        const prev = prevMap.get(p.patternId);
        const prevUsage = prev?.totalUses || 0;
        const changePct = prevUsage > 0 ? Math.round(((p.totalUses - prevUsage) / prevUsage) * 100) : 0;
        const direction = changePct > 100 ? 'exploding' : changePct > 20 ? 'rising' : changePct < -50 ? 'declining' : 'stable';
        return {
            patternId: p.patternId, direction, currentUsage: p.totalUses,
            previousUsage: prevUsage, changePct, period: 'since_last_snapshot',
        };
    }).sort((a, b) => b.changePct - a.changePct);
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 5: COMMUNITY SIMILARITY CLUSTERS
// ═══════════════════════════════════════════════════════════════
function computeClusters(developerProfiles) {
    const clusters = [];
    // Language clusters
    const langGroups = new Map();
    for (const prof of developerProfiles) {
        for (const [lang, count] of Object.entries(prof.languages)) {
            if (count < 1)
                continue;
            if (!langGroups.has(lang))
                langGroups.set(lang, { devs: 0, successRates: [], cats: new Set() });
            const g = langGroups.get(lang);
            g.devs++;
            g.successRates.push(prof.successRate);
            for (const c of prof.topCategories)
                g.cats.add(c);
        }
    }
    for (const [lang, group] of langGroups) {
        if (group.devs < 2)
            continue;
        const avgSuccess = group.successRates.reduce((s, r) => s + r, 0) / group.successRates.length;
        clusters.push({
            clusterId: `lang:${lang}`, label: `${lang} Developers`, size: group.devs,
            commonLanguages: [lang], commonCategories: [...group.cats].slice(0, 5),
            avgSuccessRate: Math.round(avgSuccess * 100) / 100, topPatterns: [],
        });
    }
    // Category clusters
    const catGroups = new Map();
    for (const prof of developerProfiles) {
        for (const cat of prof.topCategories) {
            if (!catGroups.has(cat))
                catGroups.set(cat, { devs: 0, successRates: [], langs: new Set() });
            const g = catGroups.get(cat);
            g.devs++;
            g.successRates.push(prof.successRate);
            for (const [lang] of Object.entries(prof.languages))
                g.langs.add(lang);
        }
    }
    for (const [cat, group] of catGroups) {
        if (group.devs < 2)
            continue;
        const avgSuccess = group.successRates.reduce((s, r) => s + r, 0) / group.successRates.length;
        clusters.push({
            clusterId: `cat:${cat}`, label: `Focus: ${cat}`, size: group.devs,
            commonLanguages: [...group.langs].slice(0, 5), commonCategories: [cat],
            avgSuccessRate: Math.round(avgSuccess * 100) / 100, topPatterns: [],
        });
    }
    return clusters.sort((a, b) => b.size - a.size);
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 6: COMMUNITY PLAYBOOKS
// ═══════════════════════════════════════════════════════════════
function generatePlaybooks(allPatterns, clusters) {
    const playbooks = [];
    for (const cluster of clusters) {
        if (cluster.size < 3)
            continue;
        const clusterPatterns = allPatterns.filter(p => cluster.commonCategories.includes(p.category));
        const topPats = clusterPatterns.sort((a, b) => (b.successRate * b.totalDevs) - (a.successRate * a.totalDevs)).slice(0, 5);
        if (topPats.length < 2)
            continue;
        const avgSuccess = topPats.reduce((s, p) => s + p.successRate, 0) / topPats.length;
        playbooks.push({
            id: `playbook:${cluster.clusterId}`,
            title: `Successful ${cluster.label} Practices`,
            steps: topPats.map(p => `${p.description} (${p.successRate * 100}% success, ${p.totalDevs} developers)`),
            avgSuccessRate: Math.round(avgSuccess * 100) / 100,
            sampleSize: cluster.size,
            commonArchitecture: cluster.commonCategories[0] || 'general',
            commonLanguage: cluster.commonLanguages[0] || 'any',
        });
    }
    return playbooks;
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 7: COMMUNITY BENCHMARK ENGINE
// ═══════════════════════════════════════════════════════════════
function computeBenchmarks(developerStats) {
    const community = getCommunityStats();
    const allPatterns = Object.values(loadStore().patterns);
    const successRates = allPatterns.map(p => p.successRate).sort((a, b) => a - b);
    const total = successRates.length;
    const p50 = total > 0 ? successRates[Math.floor(total * 0.5)] || 0 : 0;
    const p90 = total > 0 ? successRates[Math.floor(total * 0.9)] || 0 : 0;
    const communityAvg = community.avgSuccessRate;
    return [
        {
            metric: 'Success Rate', developerValue: developerStats.successRate,
            communityAvg, communityP50: p50, communityP90: p90,
            percentile: communityAvg > 0 ? Math.round((developerStats.successRate / communityAvg) * 100) : 0,
            sampleSize: community.totalPatterns,
        },
        {
            metric: 'Pattern Usage', developerValue: developerStats.patternsUsed,
            communityAvg: community.totalPatterns > 0 ? community.totalOutcomes / community.totalPatterns : 0,
            communityP50: 0, communityP90: 0,
            percentile: 0, sampleSize: community.totalDevs,
        },
    ];
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 8: COMMUNITY KNOWLEDGE EVOLUTION
// ═══════════════════════════════════════════════════════════════
function takeSnapshot() {
    const store = loadStore();
    const rankings = computeRankings();
    const trends = computeTrends();
    const snapshot = {
        snapshotId: `snap_${Date.now()}`,
        timestamp: Date.now(),
        totalPatterns: Object.keys(store.patterns).length,
        totalDevs: store.devCount,
        totalOutcomes: store.outcomeCount,
        rankings,
        topTrends: trends.slice(0, 20),
        clusters: [],
        playbooks: [],
        insights: [],
    };
    store.history.push(snapshot);
    if (store.history.length > 100)
        store.history = store.history.slice(-100);
    store.lastSnapshot = Date.now();
    store.version++;
    saveStore(store);
    return snapshot;
}
function getEvolution(lookbackDays = 30) {
    const store = loadStore();
    const cutoff = Date.now() - lookbackDays * 86400000;
    return store.history.filter(s => s.timestamp >= cutoff);
}
function getEvolutionTrend(patternId) {
    const store = loadStore();
    return store.history.map(s => {
        const pattern = store.patterns[patternId];
        return {
            timestamp: s.timestamp,
            successRate: pattern?.successRate || 0,
            usage: pattern?.totalUses || 0,
        };
    }).filter(e => e.usage > 0);
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 9: REPUTATION ENGINE
// ═══════════════════════════════════════════════════════════════
function computeReputation(patternId) {
    const store = loadStore();
    const entry = store.patterns[patternId];
    if (!entry)
        return 0;
    const devFactor = Math.min(entry.totalDevs / 100, 1);
    const successFactor = entry.successRate;
    const usageFactor = Math.min(entry.totalUses / 1000, 1);
    return Math.round((devFactor * 0.3 + successFactor * 0.5 + usageFactor * 0.2) * 100) / 100;
}
function getTopReputation(limit = 20) {
    const store = loadStore();
    return Object.values(store.patterns)
        .map(e => ({ ...e, reputation: computeReputation(e.patternId) }))
        .sort((a, b) => b.reputation - a.reputation)
        .slice(0, limit);
}
// ═══════════════════════════════════════════════════════════════
// SYSTEM 10: COMMUNITY INSIGHTS
// ═══════════════════════════════════════════════════════════════
function generateInsights() {
    const store = loadStore();
    const entries = Object.values(store.patterns);
    const insights = [];
    // High success patterns
    const highSuccess = entries.filter(e => e.totalDevs >= 5 && e.successRate >= 0.85);
    if (highSuccess.length >= 3) {
        const top = highSuccess.sort((a, b) => b.totalDevs - a.totalDevs).slice(0, 5);
        insights.push({
            title: 'Most Reliable Community Patterns',
            description: `${top.length} patterns with 85%+ success rate across ${top.reduce((s, p) => s + p.totalDevs, 0)} developers`,
            evidence: top.map(p => `${p.description}: ${Math.round(p.successRate * 100)}% success (${p.totalDevs} devs, ${p.totalUses} uses)`),
            sampleSize: top.reduce((s, p) => s + p.totalDevs, 0), impact: 'high', category: 'reliability',
        });
    }
    // Most-used patterns
    const mostUsed = entries.filter(e => e.totalUses >= 100).sort((a, b) => b.totalUses - a.totalUses).slice(0, 5);
    if (mostUsed.length >= 3) {
        insights.push({
            title: 'Most Adopted Patterns Across Community',
            description: `${mostUsed.length} patterns adopted by ${mostUsed.reduce((s, p) => s + p.totalDevs, 0)}+ developers`,
            evidence: mostUsed.map(p => `${p.description}: ${p.totalUses} uses across ${p.totalDevs} developers (${Math.round(p.successRate * 100)}% success)`),
            sampleSize: mostUsed.reduce((s, p) => s + p.totalDevs, 0), impact: 'high', category: 'adoption',
        });
    }
    // Failing patterns
    const failing = entries.filter(e => e.totalDevs >= 3 && e.successRate <= 0.3);
    if (failing.length >= 2) {
        insights.push({
            title: 'Patterns With Below-Average Success',
            description: `${failing.length} patterns with ≤30% success rate — consider alternatives`,
            evidence: failing.slice(0, 5).map(p => `${p.description}: ${Math.round(p.successRate * 100)}% success (${p.totalDevs} devs, ${p.totalUses} uses)`),
            sampleSize: failing.reduce((s, p) => s + p.totalDevs, 0), impact: 'high', category: 'warning',
        });
    }
    // Language-specific
    const byLang = new Map();
    for (const e of entries) {
        if (!byLang.has(e.language))
            byLang.set(e.language, []);
        byLang.get(e.language).push(e);
    }
    for (const [lang, langEntries] of byLang) {
        if (langEntries.length < 5)
            continue;
        const avgLangSuccess = langEntries.reduce((s, p) => s + p.successRate, 0) / langEntries.length;
        const best = langEntries.sort((a, b) => b.successRate - a.successRate)[0];
        insights.push({
            title: `Best ${lang} Pattern`,
            description: `In ${lang}, "${best.description}" has ${Math.round(best.successRate * 100)}% success rate`,
            evidence: [`${best.patternId}: ${Math.round(best.successRate * 100)}% success, ${best.totalDevs} developers, ${best.totalUses} uses`],
            sampleSize: best.totalDevs, impact: 'medium', category: 'language',
        });
    }
    return insights;
}
// ═══════════════════════════════════════════════════════════════
// COMMUNITY APIs
// ═══════════════════════════════════════════════════════════════
function getCommunityRankings(limit = 10) {
    return computeRankings().slice(0, limit);
}
function getCommunityTrends(limit = 20) {
    return computeTrends().slice(0, limit);
}
function getCommunityPlaybooks(developerProfiles) {
    const store = loadStore();
    const clusters = computeClusters(developerProfiles);
    const allPatterns = Object.values(store.patterns);
    return generatePlaybooks(allPatterns, clusters);
}
function getCommunityBenchmarks(developerStats) {
    return computeBenchmarks(developerStats);
}
function getCommunityInsights() {
    return generateInsights();
}
function getCommunityClusters(developerProfiles) {
    return computeClusters(developerProfiles);
}
function resetCommunity() {
    saveStore({ patterns: {}, devCount: 0, outcomeCount: 0, history: [], lastSnapshot: 0, version: 1 });
}
//# sourceMappingURL=community-intelligence.js.map