"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 });
const express_1 = require("express");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const router = (0, express_1.Router)();
// Helper — read local community packs from .cell/community/packs/
function loadPacks() {
    const dir = path.join(process.cwd(), '.cell', 'community', 'packs');
    if (!fs.existsSync(dir))
        return [];
    return fs.readdirSync(dir)
        .filter(f => f.endsWith('.json'))
        .map(f => {
        try {
            return JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'));
        }
        catch {
            return null;
        }
    })
        .filter(Boolean);
}
// Community
router.get('/community/prior', (_req, res) => {
    const packs = loadPacks();
    res.json({ patterns: packs.map(p => ({ patternId: p.id, title: p.title, category: p.category, frequency: p.downloadCount, trustScore: p.trustScore })), total: packs.length });
});
router.get('/community/v2/stats', (_req, res) => {
    const packs = loadPacks();
    const categories = {};
    let totalTrust = 0;
    for (const p of packs) {
        categories[p.category] = (categories[p.category] || 0) + 1;
        totalTrust += p.trustScore || 50;
    }
    res.json({ totalPatterns: packs.length, totalInsights: packs.length, totalBenchmarks: 0, categories, avgTrust: packs.length ? Math.round(totalTrust / packs.length) : 0 });
});
router.get('/community/v2/patterns', (req, res) => {
    const packs = loadPacks();
    const limit = parseInt(req.query.limit) || 20;
    const category = req.query.category;
    let filtered = packs;
    if (category)
        filtered = packs.filter(p => p.category === category);
    res.json({ patterns: filtered.slice(0, limit).map(p => ({ patternId: p.id, title: p.title, category: p.category, trustScore: p.trustScore, downloadCount: p.downloadCount })), total: filtered.length });
});
router.post('/community/v2/patterns/register', (req, res) => {
    const { patternId, category, language } = req.body;
    if (!patternId || !category || !language) {
        res.status(400).json({ error: 'patternId, category, language required' });
        return;
    }
    res.json({ registered: true });
});
router.post('/community/v2/outcomes/ingest', (req, res) => {
    const { outcomes } = req.body;
    if (!Array.isArray(outcomes)) {
        res.status(400).json({ error: 'outcomes array required' });
        return;
    }
    res.json({ ingested: outcomes.length });
});
router.get('/community/v2/rankings', (_req, res) => {
    const packs = loadPacks();
    const sorted = [...packs].sort((a, b) => (b.trustScore || 0) - (a.trustScore || 0));
    res.json({ rankings: sorted.slice(0, 50).map((p, i) => ({ rank: i + 1, patternId: p.id, title: p.title, category: p.category, trustScore: p.trustScore, downloadCount: p.downloadCount })) });
});
router.get('/community/v2/trends', (req, res) => {
    const packs = loadPacks();
    res.json({ trends: packs.slice(0, 10).map(p => ({ patternId: p.id, title: p.title, category: p.category, trustScore: p.trustScore, status: p.trustScore >= 80 ? 'rising' : 'stable' })) });
});
router.get('/community/v2/insights', (_req, res) => {
    const packs = loadPacks();
    const insights = packs.slice(0, 5).map(p => ({ type: 'community', key: p.category, detail: `${p.title} (trust: ${p.trustScore})` }));
    res.json({ insights });
});
router.post('/community/v2/playbooks', (_req, res) => {
    const packs = loadPacks();
    const playbooks = packs.filter(p => p.trustScore >= 70).slice(0, 5).map(p => ({ id: p.id, title: p.title, category: p.category, trustScore: p.trustScore, rules: p.rules || [] }));
    res.json({ playbooks });
});
router.post('/community/v2/benchmarks', (_req, res) => {
    const packs = loadPacks();
    const benchmarks = packs.slice(0, 10).map(p => ({ benchmarkId: p.id, category: p.category, score: p.trustScore }));
    res.json({ benchmarks });
});
router.get('/community/v2/reputation', (_req, res) => {
    res.json({ reputation: [] });
});
router.post('/community/v2/reset', (_req, res) => {
    res.json({ reset: true });
});
// Reputation
router.post('/reputation/init', (req, res) => {
    const { deviceId } = req.body;
    if (!deviceId) {
        res.status(400).json({ error: 'deviceId required' });
        return;
    }
    res.json({ deviceId, score: 0, badges: [] });
});
router.post('/reputation/contribute', (req, res) => {
    const { deviceId } = req.body;
    if (!deviceId) {
        res.status(400).json({ error: 'deviceId required' });
        return;
    }
    res.json({ deviceId, score: 0 });
});
router.get('/reputation/profile/:deviceId', (req, res) => {
    res.status(404).json({ error: 'not found' });
});
router.get('/reputation/leaderboard', (_req, res) => {
    const packs = loadPacks();
    const top = packs.filter(p => p.trustScore >= 70).slice(0, 20).map((p, i) => ({ rank: i + 1, patternId: p.id, title: p.title, score: p.trustScore }));
    res.json({ leaderboard: top });
});
router.get('/reputation/badges', (_req, res) => {
    const packs = loadPacks();
    const badges = [...new Set(packs.map(p => p.category))].map(c => ({ badge: c, description: `Active in ${c}` }));
    res.json({ badges });
});
// Playbook
router.post('/playbook/generate', (req, res) => {
    const { projectId } = req.body;
    if (!projectId) {
        res.status(400).json({ error: 'projectId required' });
        return;
    }
    res.json({ projectId, rules: [] });
});
router.get('/playbook/:projectId', (req, res) => {
    res.status(404).json({ error: 'not found' });
});
router.get('/playbook/list', (_req, res) => {
    res.json({ playbooks: [] });
});
// Marketplace
router.get('/marketplace/packages', (_req, res) => {
    res.json({ packages: [] });
});
router.get('/marketplace/search', (req, res) => {
    res.json({ results: [] });
});
router.get('/marketplace/package/:id', (req, res) => {
    res.status(404).json({ error: 'not found' });
});
router.post('/marketplace/package', (req, res) => {
    res.json({ created: true });
});
router.post('/marketplace/package/:id/download', (req, res) => {
    res.status(404).json({ error: 'not found' });
});
router.post('/marketplace/package/:id/rate', (req, res) => {
    res.json({ rated: true });
});
router.get('/marketplace/package/:id/reviews', (req, res) => {
    res.json({ reviews: [] });
});
router.get('/marketplace/stats', (_req, res) => {
    res.json({ totalPackages: 0, totalDownloads: 0 });
});
// Org
router.post('/org/create', (req, res) => {
    const { name, creatorDeviceId } = req.body;
    res.json({ id: 'org-1', name, members: [] });
});
router.get('/org/:id', (req, res) => {
    res.status(404).json({ error: 'not found' });
});
router.post('/org/:id/member/add', (req, res) => {
    res.json({ added: true });
});
router.post('/org/:id/member/remove', (req, res) => {
    res.json({ removed: true });
});
router.post('/org/:id/team/create', (req, res) => {
    res.json({ created: true });
});
router.post('/org/:id/team/:teamId/add', (req, res) => {
    res.json({ added: true });
});
router.get('/org/:id/audit', (req, res) => {
    res.json({ log: [] });
});
router.get('/orgs/list', (_req, res) => {
    res.json({ organizations: [] });
});
// Org V2
router.post('/org/v2/ensure', (req, res) => {
    res.json({ ensured: true });
});
router.post('/org/v2/team/register', (req, res) => {
    res.json({ registered: true });
});
router.post('/org/v2/outcomes/ingest', (req, res) => {
    res.json({ ingested: 0 });
});
router.get('/org/v2/:orgId/rankings', (req, res) => {
    res.json({ rankings: [] });
});
router.get('/org/v2/:orgId/team/:teamId/dna', (req, res) => {
    res.json({ dna: {} });
});
router.get('/org/v2/:orgId/teams/dna', (req, res) => {
    res.json({ teams: [] });
});
router.post('/org/v2/:orgId/benchmarks', (req, res) => {
    res.json({ benchmarks: [] });
});
router.post('/org/v2/:orgId/workflows', (req, res) => {
    res.json({ workflows: [] });
});
router.get('/org/v2/:orgId/silos', (req, res) => {
    res.json({ silos: [] });
});
router.get('/org/v2/:orgId/bus-factor', (req, res) => {
    res.json({ busFactor: 1, risks: [] });
});
router.get('/org/v2/:orgId/risks', (req, res) => {
    res.json({ risks: [] });
});
router.get('/org/v2/:orgId/playbooks', (req, res) => {
    res.json({ playbooks: [] });
});
router.get('/org/v2/:orgId/insights', (req, res) => {
    res.json({ insights: [] });
});
router.post('/org/v2/:orgId/snapshot', (req, res) => {
    res.json({ snapped: true });
});
router.post('/org/v2/:orgId/reset', (req, res) => {
    res.json({ reset: true });
});
exports.default = router;
//# sourceMappingURL=community.js.map