"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.generateCommunityReport = generateCommunityReport;
exports.sharePatterns = sharePatterns;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const database_1 = require("../../06-memory/database/database");
const CELL_DIR = path.join(os.homedir(), '.fivo', 'cell');
// ─── Community Intelligence ──────────────────────────────────────────────────
function generateCommunityReport() {
    const db = (0, database_1.getDb)();
    // ── Aggregate patterns from all scanned projects ────────────────────
    const patterns = db.prepare(`
    SELECT category, pattern_value, SUM(count) as total_count
    FROM code_patterns GROUP BY category, pattern_value
    ORDER BY total_count DESC LIMIT 30
  `).all();
    const totalPatterns = patterns.reduce((s, p) => s + p.total_count, 0);
    const communityPatterns = patterns.map(p => ({
        category: p.category,
        description: `${p.pattern_value} (${p.total_count.toLocaleString()}x)`,
        count: p.total_count,
        percentage: totalPatterns > 0 ? Math.round((p.total_count / totalPatterns) * 100) : 0,
        trend: 'stable',
    }));
    // ── Benchmarks: compare current project vs all ──────────────────────
    const benchmarks = [];
    // Blind spots benchmark
    const totalBlindSpots = db.prepare(`SELECT SUM(count) as total FROM code_patterns WHERE category = 'blind_spots'`).get();
    const yourBlindSpots = db.prepare(`SELECT COUNT(*) as cnt FROM code_patterns WHERE category = 'blind_spots'`).get();
    if (totalBlindSpots?.total && yourBlindSpots?.cnt) {
        const avg = totalBlindSpots.total / Math.max(1, yourBlindSpots.cnt);
        benchmarks.push({
            metric: 'Blind Spots',
            yourValue: yourBlindSpots.cnt,
            aggregateValue: Math.round(avg),
            percentile: Math.min(95, Math.max(5, Math.round((avg / yourBlindSpots.cnt) * 50))),
            interpretation: yourBlindSpots.cnt < avg
                ? 'Better than average — fewer blind spots detected'
                : 'More blind spots than average — focus on fixing',
        });
    }
    // Code patterns benchmark
    const totalCode = db.prepare(`SELECT SUM(count) as total FROM code_patterns WHERE category IN ('style', 'naming', 'functions', 'architecture')`).get();
    const yourCode = db.prepare(`SELECT COUNT(*) as cnt FROM code_patterns WHERE category IN ('style', 'naming', 'functions', 'architecture')`).get();
    if (totalCode?.total && yourCode?.cnt) {
        benchmarks.push({
            metric: 'Pattern Diversity',
            yourValue: yourCode.cnt,
            aggregateValue: Math.round(totalCode.total / Math.max(1, yourCode.cnt)),
            percentile: Math.min(95, Math.max(5, Math.round(yourCode.cnt / Math.max(1, totalCode.total / 10) * 50))),
            interpretation: yourCode.cnt > 100 ? 'High pattern diversity — many techniques used' : 'Focused coding style',
        });
    }
    // ── Top stacks ──────────────────────────────────────────────────────
    const stacks = db.prepare(`SELECT language, COUNT(*) as cnt FROM code_patterns WHERE category = 'architecture' GROUP BY language ORDER BY cnt DESC LIMIT 5`).all();
    const topStacks = stacks.map(s => ({ stack: s.language, count: s.cnt }));
    // ── Top blind spots ─────────────────────────────────────────────────
    const blinds = db.prepare(`SELECT pattern_value, SUM(count) as total FROM code_patterns WHERE category = 'blind_spots' GROUP BY pattern_value ORDER BY total DESC LIMIT 5`).all();
    const topBlindSpots = blinds.map(b => ({
        blindSpot: b.pattern_value,
        percentage: Math.round(b.total),
    }));
    return {
        patterns: communityPatterns,
        benchmarks,
        topStacks,
        topBlindSpots,
        generatedAt: new Date().toISOString(),
    };
}
// ─── Share (save to community file) ──────────────────────────────────────────
function sharePatterns() {
    try {
        const db = (0, database_1.getDb)();
        const patterns = db.prepare(`
      SELECT pattern_type, pattern_value, category, SUM(count) as total
      FROM code_patterns GROUP BY category, pattern_value
      ORDER BY total DESC LIMIT 100
    `).all();
        const communityFile = path.join(CELL_DIR, 'community', 'shared.json');
        const existing = readJson(communityFile) || { shares: [] };
        const share = {
            timestamp: new Date().toISOString(),
            patternCount: patterns.length,
            topCategories: [...new Set(patterns.map(p => p.category))].slice(0, 10),
            topPatterns: patterns.slice(0, 20).map(p => ({ category: p.category, value: p.pattern_value, count: p.total })),
        };
        const shares = existing.shares || [];
        shares.push(share);
        writeJson(communityFile, { shares, totalShares: shares.length, updatedAt: new Date().toISOString() });
        return { success: true, message: `Shared ${patterns.length} patterns anonymously.`, sharedCount: patterns.length };
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return { success: false, message: msg, sharedCount: 0 };
    }
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
function readJson(file) {
    try {
        return JSON.parse(fs.readFileSync(file, 'utf-8'));
    }
    catch {
        return null;
    }
}
function writeJson(file, data) {
    const dir = path.dirname(file);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(file, JSON.stringify(data, null, 2), 'utf-8');
}
//# sourceMappingURL=community-intel.js.map