"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TeamEngine = void 0;
const cell_store_1 = require("../walls/06-memory/stores/cell-store");
class TeamEngine {
    store;
    data;
    constructor(cellDir) {
        this.store = new cell_store_1.CellStore(cellDir);
        this.data = this.store.read('index.json', 'team') || {
            version: 1, updated: Date.now(),
            patterns: [], knowledgeMap: [],
            dna: { qualityBar: 0, riskProfile: 'medium', avgPrCycleTime: 0,
                testCoverage: 0, refactoringAppetite: 50, docCulture: 30,
                memberCount: 1, totalPatterns: 0 },
            workflows: { avgReviewTime: 0, prsThisWeek: 0, bottlenecks: [],
                commonFailures: [], deployFrequency: 'unknown' },
        };
    }
    addPattern(name, description, category, approvedBy) {
        const id = `tp_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
        this.data.patterns.push({
            id, name, description, category, approvedBy,
            approvedAt: Date.now(), voteScore: 1, appliedCount: 0,
        });
        this.data.dna.totalPatterns = this.data.patterns.length;
        this.save();
        return { id };
    }
    votePattern(patternId, score) {
        const p = this.data.patterns.find(p => p.id === patternId);
        if (p) {
            p.voteScore += score;
            this.save();
        }
    }
    applyPattern(patternId) {
        const p = this.data.patterns.find(p => p.id === patternId);
        if (p) {
            p.appliedCount++;
            this.save();
        }
    }
    updateKnowledgeMap(module, experts) {
        const existing = this.data.knowledgeMap.find(e => e.module === module);
        if (existing) {
            existing.experts = [...new Set([...existing.experts, ...experts])];
            existing.busFactor = existing.experts.length;
            existing.lastUpdated = Date.now();
        }
        else {
            this.data.knowledgeMap.push({
                module, experts, busFactor: experts.length,
                riskScore: experts.length <= 1 ? 80 : experts.length <= 2 ? 50 : 20,
                lastUpdated: Date.now(),
            });
        }
        this.save();
    }
    setDNA(dna) {
        Object.assign(this.data.dna, dna);
        this.save();
    }
    recordWorkflow(prTime, bottleneck, failure) {
        const wf = this.data.workflows;
        const totalPRs = wf.prsThisWeek;
        wf.avgReviewTime = totalPRs > 0
            ? Math.round((wf.avgReviewTime * totalPRs + prTime) / (totalPRs + 1))
            : prTime;
        wf.prsThisWeek++;
        if (bottleneck && !wf.bottlenecks.includes(bottleneck))
            wf.bottlenecks.push(bottleneck);
        if (failure && !wf.commonFailures.includes(failure))
            wf.commonFailures.push(failure);
        this.save();
    }
    generateOnboarding() {
        const d = this.data;
        const lines = [];
        lines.push('# Team Onboarding\n');
        lines.push(`**Team size:** ${d.dna.memberCount} developers`);
        lines.push(`**Quality bar:** ${d.dna.qualityBar}% test coverage target`);
        lines.push(`**Risk profile:** ${d.dna.riskProfile}\n`);
        if (d.patterns.length > 0) {
            lines.push('## Approved Patterns');
            for (const p of d.patterns.slice(0, 5)) {
                const votes = p.voteScore > 1 ? ` (${p.voteScore} votes)` : '';
                lines.push(`- **${p.name}**${votes} — ${p.description}`);
            }
            lines.push('');
        }
        if (d.knowledgeMap.length > 0) {
            lines.push('## Knowledge Map');
            for (const k of d.knowledgeMap) {
                const risk = k.busFactor <= 1 ? ' ⚠️ Single point of failure' : k.busFactor <= 2 ? ' ⚡ Limited coverage' : ' ✅';
                lines.push(`- **${k.module}**: ${k.experts.join(', ')}${risk}`);
            }
            lines.push('');
        }
        if (d.workflows.bottlenecks.length > 0) {
            lines.push('## Known Bottlenecks');
            for (const b of d.workflows.bottlenecks)
                lines.push(`- ⚠️ ${b}`);
            lines.push('');
        }
        if (d.workflows.commonFailures.length > 0) {
            lines.push('## Common Failures');
            for (const f of d.workflows.commonFailures)
                lines.push(`- ❌ ${f}`);
            lines.push('');
        }
        lines.push('## Quick Start');
        lines.push('1. `cell run` — Initialize Cell');
        lines.push('2. `cell start` — Start daemon');
        lines.push('3. `cell team` — View team intelligence');
        lines.push('4. `cell silos` — Check knowledge gaps');
        lines.push('5. `cell review` — Review PRs with context');
        return lines.join('\n');
    }
    getSummary() {
        const d = this.data;
        if (d.patterns.length === 0 && d.knowledgeMap.length === 0)
            return [];
        const lines = [];
        lines.push(`Team: ${d.dna.memberCount} members · ${d.patterns.length} patterns · ${d.knowledgeMap.length} modules`);
        lines.push(`Quality: ${d.dna.qualityBar}% test coverage · Risk: ${d.dna.riskProfile} · PR cycle: ${d.dna.avgPrCycleTime}h`);
        const spofs = d.knowledgeMap.filter(k => k.busFactor <= 1);
        if (spofs.length > 0)
            lines.push(`⚠️  ${spofs.length} single points of failure`);
        const bottlenecks = d.workflows.bottlenecks.slice(0, 3);
        if (bottlenecks.length > 0)
            lines.push(`Bottlenecks: ${bottlenecks.join(', ')}`);
        return lines;
    }
    save() {
        this.data.updated = Date.now();
        this.store.write('index.json', this.data, 'team');
    }
}
exports.TeamEngine = TeamEngine;
//# sourceMappingURL=team-engine.js.map