"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.teamPush = teamPush;
exports.teamPull = teamPull;
exports.teamStatus = teamStatus;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
const database_1 = require("../../06-memory/database/database");
const CELL_TEAM_DIR = path.join(os.homedir(), '.fivo', 'cell', 'team');
// ─── Git Operations ──────────────────────────────────────────────────────
function gitCmd(cmd, cwd) {
    try {
        return (0, child_process_1.execSync)(`git ${cmd}`, {
            cwd: cwd || process.cwd(),
            encoding: 'utf-8',
            timeout: 30000,
            stdio: ['pipe', 'pipe', 'pipe'],
        }).trim();
    }
    catch {
        return '';
    }
}
function ensureGitRepo() {
    return fs.existsSync(path.join(process.cwd(), '.git'));
}
// ─── Team Data Paths ─────────────────────────────────────────────────────
function teamDir(repoRoot) {
    return path.join(repoRoot, '.cell', 'team');
}
function ensureTeamDir(repoRoot) {
    const dir = teamDir(repoRoot);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}
function readTeamJson(file) {
    try {
        return JSON.parse(fs.readFileSync(file, 'utf-8'));
    }
    catch {
        return null;
    }
}
function writeTeamJson(file, data) {
    fs.writeFileSync(file, JSON.stringify(data, null, 2), 'utf-8');
}
// ─── Push: Save personal data to repo team folder ────────────────────────
function teamPush(name, role = 'developer') {
    if (!ensureGitRepo())
        return { success: false, message: 'Not a git repository. Run inside a git project.' };
    const repoRoot = process.cwd();
    ensureTeamDir(repoRoot);
    try {
        // Read personal patterns
        const profile = readTeamJson(path.join(CELL_TEAM_DIR, '..', 'personal', 'profile.json'));
        const style = readTeamJson(path.join(CELL_TEAM_DIR, '..', 'personal', 'style.json'));
        // Save member data
        const memberFile = path.join(teamDir(repoRoot), 'members', `${name}.json`);
        const memberDir = path.dirname(memberFile);
        if (!fs.existsSync(memberDir))
            fs.mkdirSync(memberDir, { recursive: true });
        writeTeamJson(memberFile, {
            name,
            role,
            profile: profile ? { namingStyle: profile.namingStyle, strengths: profile.strengths } : null,
            style: style ? { patterns: style.patterns } : null,
            pushedAt: new Date().toISOString(),
        });
        // Save shared patterns
        const patternsFile = path.join(teamDir(repoRoot), 'patterns', `${name}.json`);
        const patternsDir = path.dirname(patternsFile);
        if (!fs.existsSync(patternsDir))
            fs.mkdirSync(patternsDir, { recursive: true });
        // Get patterns from DB
        const db = (0, database_1.getDb)();
        const patterns = db.prepare('SELECT pattern_type, pattern_value, category, count FROM code_patterns WHERE project = ? LIMIT 30')
            .all(path.basename(repoRoot));
        writeTeamJson(patternsFile, {
            member: name,
            patterns: patterns.map((p) => ({ type: p.pattern_type, value: p.pattern_value, category: p.category, count: p.count })),
            pushedAt: new Date().toISOString(),
        });
        // Git add + commit + push
        const teamPath = path.join(repoRoot, '.cell', 'team');
        gitCmd(`add "${teamPath}"`, repoRoot);
        gitCmd(`commit -m "cell: ${name} team push — patterns + profile"`, repoRoot);
        const pushResult = gitCmd('push origin HEAD', repoRoot);
        const pushed = !pushResult.includes('fatal') && !pushResult.includes('error');
        // Update global team members
        const globalMembers = readTeamJson(path.join(CELL_TEAM_DIR, 'members.json'));
        const membersList = globalMembers?.members || [];
        const existingIdx = membersList.findIndex((m) => m.name === name);
        if (existingIdx >= 0) {
            membersList[existingIdx] = { name, role, patterns: patterns.length, lastActive: new Date().toISOString() };
        }
        else {
            membersList.push({ name, role, patterns: patterns.length, lastActive: new Date().toISOString() });
        }
        writeTeamJson(path.join(CELL_TEAM_DIR, 'members.json'), { members: membersList, updatedAt: new Date().toISOString() });
        return {
            success: true,
            message: pushed
                ? `Pushed ${patterns.length} patterns for ${name} (${role}). Git synced.`
                : `Saved locally. Git push pending — check remote.`,
        };
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return { success: false, message: `Push failed: ${msg}` };
    }
}
// ─── Pull: Merge teammates data ─────────────────────────────────────────
function teamPull() {
    if (!ensureGitRepo())
        return { success: false, message: 'Not a git repository.', newMembers: 0, newPatterns: 0 };
    const repoRoot = process.cwd();
    ensureTeamDir(repoRoot);
    try {
        // Git pull
        const pullResult = gitCmd('pull origin HEAD', repoRoot);
        if (pullResult.includes('fatal')) {
            return { success: false, message: `Git pull failed: ${pullResult}`, newMembers: 0, newPatterns: 0 };
        }
        // Read all members
        const membersDir = path.join(teamDir(repoRoot), 'members');
        const patternsDir = path.join(teamDir(repoRoot), 'patterns');
        let newMembers = 0;
        let newPatterns = 0;
        if (fs.existsSync(membersDir)) {
            const memberFiles = fs.readdirSync(membersDir).filter(f => f.endsWith('.json'));
            for (const file of memberFiles) {
                const data = readTeamJson(path.join(membersDir, file));
                if (data)
                    newMembers++;
            }
        }
        if (fs.existsSync(patternsDir)) {
            const patternFiles = fs.readdirSync(patternsDir).filter(f => f.endsWith('.json'));
            for (const file of patternFiles) {
                const data = readTeamJson(path.join(patternsDir, file));
                if (data && data.patterns)
                    newPatterns += data.patterns.length;
            }
        }
        // Rebuild team intelligence
        const intel = buildTeamIntelligence(repoRoot);
        writeTeamJson(path.join(CELL_TEAM_DIR, 'intelligence.json'), intel);
        const msg = pullResult.includes('Already up to date')
            ? 'Team data up to date.'
            : `Pulled ${newMembers} members, ${newPatterns} patterns from team.`;
        return { success: true, message: msg, newMembers, newPatterns };
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        return { success: false, message: `Pull failed: ${msg}`, newMembers: 0, newPatterns: 0 };
    }
}
// ─── Team Intelligence Builder ──────────────────────────────────────────
function buildTeamIntelligence(repoRoot) {
    const membersDir = path.join(teamDir(repoRoot), 'members');
    const patternsDir = path.join(teamDir(repoRoot), 'patterns');
    const members = [];
    const allPatterns = [];
    const allBlindSpots = [];
    const knowledge = new Map();
    // Read members
    if (fs.existsSync(membersDir)) {
        const files = fs.readdirSync(membersDir).filter(f => f.endsWith('.json'));
        for (const file of files) {
            const data = readTeamJson(path.join(membersDir, file));
            if (!data)
                continue;
            const m = data;
            members.push({
                name: m.name || file.replace('.json', ''),
                role: m.role || 'developer',
                patterns: 0,
                blindSpots: 0,
                strengths: m.profile?.strengths || [],
                lastActive: m.pushedAt || 'unknown',
            });
        }
    }
    // Read and merge patterns
    if (fs.existsSync(patternsDir)) {
        const files = fs.readdirSync(patternsDir).filter(f => f.endsWith('.json'));
        for (const file of files) {
            const data = readTeamJson(path.join(patternsDir, file));
            if (!data)
                continue;
            const p = data;
            if (p.patterns) {
                for (const pat of p.patterns) {
                    const existing = allPatterns.find(ap => ap.value === pat.value);
                    if (existing) {
                        existing.count += pat.count || 1;
                    }
                    else {
                        allPatterns.push({ name: pat.type || pat.category || 'unknown', value: pat.value, count: pat.count || 1 });
                    }
                    // Knowledge map
                    if (pat.category) {
                        const expert = knowledge.get(pat.category) || [];
                        if (!expert.includes(p.member)) {
                            expert.push(p.member);
                            knowledge.set(pat.category, expert);
                        }
                    }
                }
            }
            // Update member pattern count
            const mem = members.find(m => m.name === p.member);
            if (mem && p.patterns)
                mem.patterns = p.patterns.length;
        }
    }
    // Read blind spots
    const blindsFile = path.join(CELL_TEAM_DIR, 'blindspots.json');
    const blindsData = readTeamJson(blindsFile);
    if (blindsData) {
        const bs = blindsData;
        if (bs.blindSpots)
            allBlindSpots.push(...bs.blindSpots);
    }
    // Knowledge map to array
    const knowledgeMap = [];
    for (const [area, experts] of knowledge) {
        knowledgeMap.push({ area, experts, busFactor: experts.length });
    }
    allPatterns.sort((a, b) => b.count - a.count);
    const criticalBlinds = allBlindSpots.filter(b => b.severity === 'high').length;
    const avgBusFactor = knowledgeMap.length > 0
        ? Math.round(knowledgeMap.reduce((s, k) => s + k.busFactor, 0) / knowledgeMap.length)
        : 0;
    const strongest = knowledgeMap.length > 0
        ? knowledgeMap.reduce((a, b) => a.busFactor > b.busFactor ? a : b)
        : null;
    const weakest = knowledgeMap.length > 0
        ? knowledgeMap.reduce((a, b) => a.busFactor < b.busFactor ? a : b)
        : null;
    return {
        members,
        sharedPatterns: allPatterns.slice(0, 20),
        blindSpots: allBlindSpots,
        knowledgeMap,
        summary: {
            totalMembers: members.length,
            totalPatterns: allPatterns.length,
            criticalBlindSpots: criticalBlinds,
            avgBusFactor,
            strongestArea: strongest ? `${strongest.area} (${strongest.busFactor} experts)` : 'unknown',
            weakestArea: weakest ? `${weakest.area} (${weakest.busFactor} expert${weakest.busFactor === 1 ? '' : 's'})` : 'unknown',
        },
        updatedAt: new Date().toISOString(),
    };
}
// ─── Team Status ─────────────────────────────────────────────────────────
function teamStatus() {
    const repoRoot = process.cwd();
    if (!ensureGitRepo())
        return null;
    // Try reading cached intelligence first
    const intelFile = path.join(CELL_TEAM_DIR, 'intelligence.json');
    const cached = readTeamJson(intelFile);
    if (cached)
        return cached;
    // Build fresh
    return buildTeamIntelligence(repoRoot);
}
//# sourceMappingURL=team-git.js.map