"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 os = __importStar(require("os"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
describe('Phase 4: Team Collaboration', () => {
    let tmpHome;
    let originalUserProfile;
    let closeDb;
    let detectKnowledgeSilos;
    let calculateBusFactor;
    let getTeamHealth;
    let generateOnboardingDoc;
    let generateSprintRetro;
    let generateHandoff;
    let suggestKnowledgeTransfer;
    let composeTeamStyle;
    beforeAll(() => {
        originalUserProfile = process.env.USERPROFILE;
        tmpHome = path.join(os.tmpdir(), 'fivo-cell-phase4-' + Date.now());
        process.env.USERPROFILE = tmpHome;
        fs.mkdirSync(tmpHome, { recursive: true });
        const db = require('../walls/06-memory/database/database');
        closeDb = db.closeDb;
        closeDb();
        const tc = require('../walls/04-team/collab/team-collaboration');
        detectKnowledgeSilos = tc.detectKnowledgeSilos;
        calculateBusFactor = tc.calculateBusFactor;
        getTeamHealth = tc.getTeamHealth;
        generateOnboardingDoc = tc.generateOnboardingDoc;
        generateSprintRetro = tc.generateSprintRetro;
        generateHandoff = tc.generateHandoff;
        suggestKnowledgeTransfer = tc.suggestKnowledgeTransfer;
        composeTeamStyle = tc.composeTeamStyle;
    });
    beforeEach(() => {
        const { getDb } = require('../walls/06-memory/database/database');
        const db = getDb();
        db.prepare('DELETE FROM silos').run();
        db.prepare('DELETE FROM collaborators').run();
        db.prepare('DELETE FROM patterns').run();
        db.prepare('DELETE FROM signals').run();
        db.prepare('DELETE FROM decisions').run();
        db.prepare('DELETE FROM error_log').run();
    });
    afterAll(() => {
        if (originalUserProfile !== undefined) {
            process.env.USERPROFILE = originalUserProfile;
        }
        else {
            delete process.env.USERPROFILE;
        }
        closeDb();
        try {
            fs.rmSync(tmpHome, { recursive: true, force: true });
        }
        catch { }
    });
    describe('detectKnowledgeSilos', () => {
        it('returns empty array when no data', () => {
            const silos = detectKnowledgeSilos();
            expect(Array.isArray(silos)).toBe(true);
        });
        it('detects silos from silos table', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO silos (name, members, knowledge_area, risk_level, bus_factor) VALUES (?, ?, ?, ?, ?)')
                .run('Database Expert', JSON.stringify(['alice']), 'PostgreSQL', 'high', 1);
            const silos = detectKnowledgeSilos();
            expect(silos.length).toBeGreaterThan(0);
            const found = silos.find(s => s.knowledgeArea === 'PostgreSQL');
            expect(found).toBeDefined();
            expect(found.busFactor).toBe(1);
            expect(found.riskLevel).toBe('high');
        });
        it('detects single-expert silos from collaborators', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO collaborators (name, commit_count, skills) VALUES (?, ?, ?)')
                .run('bob', 50, JSON.stringify(['Rust', 'WebAssembly']));
            db.prepare('INSERT INTO collaborators (name, commit_count, skills) VALUES (?, ?, ?)')
                .run('alice', 30, JSON.stringify(['Rust']));
            const silos = detectKnowledgeSilos();
            // WebAssembly is known only to bob → silo
            const wasmSilo = silos.find(s => s.knowledgeArea === 'WebAssembly');
            expect(wasmSilo).toBeDefined();
            expect(wasmSilo.members).toEqual(['bob']);
        });
    });
    describe('calculateBusFactor', () => {
        it('returns report with overall score 0 when no collaborators', () => {
            const report = calculateBusFactor();
            expect(report.overallScore).toBe(0);
            expect(report.members).toEqual([]);
        });
        it('calculates score based on commits + collaboration', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO collaborators (name, commit_count, collaboration_score, skills) VALUES (?, ?, ?, ?)')
                .run('alice', 100, 0.8, JSON.stringify(['TS', 'React']));
            db.prepare('INSERT INTO collaborators (name, commit_count, collaboration_score, skills) VALUES (?, ?, ?, ?)')
                .run('bob', 50, 0.5, JSON.stringify(['Python']));
            const report = calculateBusFactor();
            expect(report.members.length).toBe(2);
            expect(report.overallScore).toBeGreaterThan(0);
            // Alice has higher score
            expect(report.members[0].name).toBe('alice');
        });
    });
    describe('getTeamHealth', () => {
        it('returns health object with score', () => {
            const health = getTeamHealth();
            expect(typeof health.score).toBe('number');
            expect(typeof health.busFactor).toBe('number');
            expect(typeof health.siloCount).toBe('number');
            expect(Array.isArray(health.recommendations)).toBe(true);
        });
        it('penalizes high silo count', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            for (let i = 0; i < 3; i++) {
                db.prepare('INSERT INTO silos (name, members, knowledge_area, risk_level, bus_factor) VALUES (?, ?, ?, ?, ?)')
                    .run(`Silo ${i}`, JSON.stringify([`person${i}`]), `area${i}`, 'high', 1);
            }
            const health = getTeamHealth();
            expect(health.siloCount).toBeGreaterThanOrEqual(3);
            expect(health.score).toBeLessThan(100);
        });
    });
    describe('generateOnboardingDoc', () => {
        it('generates onboarding doc with team name and stack', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO patterns (id, project, category, rule, confidence, language) VALUES (?, ?, ?, ?, ?, ?)')
                .run('p-onb-1', 'test-onboard-4', 'naming_style', 'camelCase', 0.9, 'typescript');
            const doc = generateOnboardingDoc('TestTeam', 'test-onboard-4');
            expect(doc.teamName).toBe('TestTeam');
            expect(doc.generatedAt).toBeDefined();
            expect(Array.isArray(doc.stack)).toBe(true);
            expect(Array.isArray(doc.firstWeekTasks)).toBe(true);
            expect(Array.isArray(doc.whoToAsk)).toBe(true);
        });
    });
    describe('generateSprintRetro', () => {
        it('generates retro for the period', () => {
            const retro = generateSprintRetro(7, 'test-retro-4');
            expect(retro.period).toBeDefined();
            expect(typeof retro.commits).toBe('number');
            expect(Array.isArray(retro.topContributors)).toBe(true);
        });
    });
    describe('generateHandoff', () => {
        it('generates handoff context between two people', () => {
            const handoff = generateHandoff('alice', 'bob', 'test-handoff-4');
            expect(handoff.from).toBe('alice');
            expect(handoff.to).toBe('bob');
            expect(handoff.project).toBe('test-handoff-4');
            expect(Array.isArray(handoff.currentTasks)).toBe(true);
            expect(Array.isArray(handoff.blockers)).toBe(true);
        });
    });
    describe('suggestKnowledgeTransfer', () => {
        it('suggests transfer from single-expert silos', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO collaborators (name, commit_count, skills) VALUES (?, ?, ?)')
                .run('expert', 100, JSON.stringify(['Kubernetes', 'Helm']));
            db.prepare('INSERT INTO collaborators (name, commit_count, skills) VALUES (?, ?, ?)')
                .run('learner1', 30, JSON.stringify(['TypeScript']));
            const suggestions = suggestKnowledgeTransfer();
            // Kubernetes is single-expert → suggest transfer
            const k8s = suggestions.find(s => s.area === 'Kubernetes');
            expect(k8s).toBeDefined();
            expect(k8s.from).toBe('expert');
            expect(k8s.to).not.toBe('expert');
        });
    });
    describe('composeTeamStyle', () => {
        it('returns style with languages and patterns', () => {
            const { getDb } = require('../walls/06-memory/database/database');
            const db = getDb();
            db.prepare('INSERT INTO patterns (id, project, category, rule, confidence, language) VALUES (?, ?, ?, ?, ?, ?)')
                .run('p-style-1', 'test-style-4', 'naming_style', 'camelCase', 0.8, 'typescript');
            const style = composeTeamStyle('test-style-4');
            expect(Array.isArray(style.languages)).toBe(true);
            expect(Array.isArray(style.patterns)).toBe(true);
            expect(typeof style.testCoverage).toBe('string');
        });
    });
});
//# sourceMappingURL=team-collaboration.test.js.map