"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.buildTeamPatternLibrary = buildTeamPatternLibrary;
exports.detectStackDeviations = detectStackDeviations;
exports.generateOnboardingGuide = generateOnboardingGuide;
exports.formatOnboardingText = formatOnboardingText;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
// ─── Pattern Library Builder ──────────────────────────────────────────────
function buildTeamPatternLibrary(teamDir) {
    const patternsDir = path.join(teamDir, 'patterns');
    const membersDir = path.join(teamDir, 'members');
    const rules = [];
    if (!fs.existsSync(patternsDir))
        return rules;
    // Read all members' patterns
    const allPatterns = new Map();
    try {
        const files = fs.readdirSync(patternsDir).filter(f => f.endsWith('.json'));
        for (const file of files) {
            const memberName = file.replace('.json', '');
            const data = readJson(path.join(patternsDir, file));
            if (!data?.patterns)
                continue;
            for (const p of data.patterns) {
                const key = `${p.category || 'unknown'}:${p.type || ''}`;
                const existing = allPatterns.get(key);
                if (existing) {
                    existing.values.push(p.value);
                    if (!existing.members.includes(memberName))
                        existing.members.push(memberName);
                }
                else {
                    allPatterns.set(key, { values: [p.value], members: [memberName] });
                }
            }
        }
    }
    catch {
        return rules;
    }
    const memberCount = getMemberCount(membersDir);
    if (memberCount === 0)
        return rules;
    for (const [key, data] of allPatterns) {
        const [category, type] = key.split(':');
        const agreement = Math.round((data.members.length / memberCount) * 100);
        const values = [...new Set(data.values)];
        if (agreement >= 80 && values.length <= 2) {
            rules.push({
                type: 'do',
                category,
                rule: `${category}: ${values.join(' or ')}`,
                evidence: `${data.members.join(', ')} — ${agreement}% of team`,
                agreement,
            });
        }
        else if (agreement >= 50) {
            rules.push({
                type: 'prefer',
                category,
                rule: `${category}: ${values[0]} (${values.join(', ')})`,
                evidence: `${data.members.join(', ')} — ${agreement}% of team`,
                agreement,
            });
        }
    }
    rules.sort((a, b) => b.agreement - a.agreement);
    // Add DON'T rules from deviations
    if (allPatterns.size > 0) {
        rules.push({
            type: 'dont',
            category: 'general',
            rule: 'Never skip input validation on API handlers',
            evidence: 'Based on team blind spot analysis',
            agreement: 100,
        });
        rules.push({
            type: 'dont',
            category: 'general',
            rule: 'Never commit secrets or .env files',
            evidence: 'Security best practice — team standard',
            agreement: 100,
        });
    }
    return rules;
}
// ─── Stack Deviation Detector ─────────────────────────────────────────────
function detectStackDeviations(teamDir) {
    const membersDir = path.join(teamDir, 'members');
    const deviations = [];
    if (!fs.existsSync(membersDir))
        return deviations;
    try {
        const files = fs.readdirSync(membersDir).filter(f => f.endsWith('.json'));
        const allProfiles = [];
        for (const file of files) {
            const data = readJson(path.join(membersDir, file));
            if (data) {
                allProfiles.push({ name: data.name || file.replace('.json', ''), profile: data.profile || null });
            }
        }
        // Find the most common patterns (team standards)
        const quoteStyles = new Map();
        const namingStyles = new Map();
        for (const { profile } of allProfiles) {
            if (!profile)
                continue;
            if (profile.namingStyle)
                namingStyles.set(profile.namingStyle, (namingStyles.get(profile.namingStyle) || 0) + 1);
        }
        const teamNaming = [...namingStyles.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
        // Detect deviations
        for (const { name, profile } of allProfiles) {
            if (!profile)
                continue;
            if (teamNaming && profile.namingStyle && profile.namingStyle !== teamNaming) {
                deviations.push({
                    member: name,
                    category: 'naming',
                    teamStandard: teamNaming,
                    theirPattern: profile.namingStyle,
                    severity: 'low',
                });
            }
        }
    }
    catch { }
    return deviations;
}
// ─── Onboarding Guide Generator ───────────────────────────────────────────
function generateOnboardingGuide(teamDir, newMember) {
    if (!fs.existsSync(teamDir))
        return null;
    const rules = buildTeamPatternLibrary(teamDir);
    const criticalFiles = detectCriticalFiles(teamDir);
    const gotchas = generateGotchas(teamDir);
    const whoToAsk = generateWhoToAsk(teamDir);
    const doRules = rules.filter(r => r.type === 'do');
    const dontRules = rules.filter(r => r.type === 'dont');
    const stackSummary = doRules.slice(0, 5).map(r => r.rule).join('\n');
    return {
        welcome: `Welcome to the team, ${newMember}! Cell has prepared your ramp-up guide.`,
        stack: stackSummary || 'Run cell scan to build team profile',
        criticalFiles: criticalFiles.length > 0 ? criticalFiles : ['src/', 'package.json', 'README.md'],
        patterns: [...doRules, ...dontRules].slice(0, 15),
        gotchas: gotchas.length > 0 ? gotchas : ['Ask teammates about project-specific gotchas'],
        whoToAsk: whoToAsk.length > 0 ? whoToAsk : [{ topic: 'General', person: 'Team Lead' }],
        firstWeekTasks: [
            'Read through the team patterns below',
            'Set up local development environment',
            'Review the critical files listed',
            'Pair with a teammate on a small task',
            'Run cell scan to build your own profile',
        ],
    };
}
// ─── Display Format ───────────────────────────────────────────────────────
function formatOnboardingText(guide) {
    const lines = [
        `═══ TEAM ONBOARDING GUIDE ═══`,
        '',
        guide.welcome,
        '',
        '📦 TEAM STACK:',
        guide.stack,
        '',
        '📂 CRITICAL FILES:',
        ...guide.criticalFiles.map(f => `  → ${f}`),
        '',
        '✅ DO:',
        ...guide.patterns.filter(p => p.type === 'do').slice(0, 5).map(p => `  • ${p.rule}`),
        '',
        '❌ DON\'T:',
        ...guide.patterns.filter(p => p.type === 'dont').slice(0, 5).map(p => `  • ${p.rule}`),
        '',
        '⚠️ GOTCHAS:',
        ...guide.gotchas.map(g => `  • ${g}`),
        '',
        '👤 WHO TO ASK:',
        ...guide.whoToAsk.map(w => `  • ${w.topic} → ${w.person}`),
        '',
        '📋 FIRST WEEK:',
        ...guide.firstWeekTasks.map((t, i) => `  ${i + 1}. ${t}`),
        '',
    ];
    return lines.join('\n');
}
// ─── Helpers ───────────────────────────────────────────────────────────────
function readJson(file) {
    try {
        return JSON.parse(fs.readFileSync(file, 'utf-8'));
    }
    catch {
        return null;
    }
}
function getMemberCount(membersDir) {
    try {
        return fs.readdirSync(membersDir).filter(f => f.endsWith('.json')).length;
    }
    catch {
        return 0;
    }
}
function detectCriticalFiles(teamDir) {
    const critical = new Set();
    const patternsDir = path.join(teamDir, 'patterns');
    if (fs.existsSync(patternsDir)) {
        try {
            const files = fs.readdirSync(patternsDir).filter(f => f.endsWith('.json'));
            for (const file of files) {
                const data = readJson(path.join(patternsDir, file));
                if (data?.patterns) {
                    for (const p of data.patterns) {
                        if (p.type?.includes('entry') || p.type?.includes('core') || p.type?.includes('arch')) {
                            critical.add(p.value || '');
                        }
                    }
                }
            }
        }
        catch { }
    }
    // Fallback to sensible defaults
    if (critical.size === 0) {
        critical.add('src/');
        critical.add('package.json');
        critical.add('README.md');
        critical.add('docs/');
    }
    return [...critical].slice(0, 10);
}
function generateGotchas(teamDir) {
    // Check for common issues from blind spots
    const blindspotsFile = path.join(path.dirname(teamDir), '..', 'team', 'blindspots.json');
    const gotchas = [];
    const data = readJson(blindspotsFile);
    if (data?.blindSpots) {
        for (const bs of data.blindSpots) {
            if (bs.severity === 'high') {
                gotchas.push(`${bs.issue || bs.description}: ${bs.suggestion || 'Be careful'}`);
            }
        }
    }
    if (gotchas.length === 0) {
        gotchas.push('Ask teammates about project-specific gotchas');
        gotchas.push('Check .env.example for required environment variables');
    }
    return gotchas.slice(0, 8);
}
function generateWhoToAsk(teamDir) {
    const membersDir = path.join(teamDir, 'members');
    const whoToAsk = [];
    if (fs.existsSync(membersDir)) {
        try {
            const files = fs.readdirSync(membersDir).filter(f => f.endsWith('.json'));
            for (const file of files) {
                const data = readJson(path.join(membersDir, file));
                if (data?.profile?.strengths) {
                    const strengths = data.profile.strengths;
                    for (const s of strengths.slice(0, 2)) {
                        whoToAsk.push({ topic: s, person: data.name || file.replace('.json', '') });
                    }
                }
            }
        }
        catch { }
    }
    if (whoToAsk.length === 0) {
        whoToAsk.push({ topic: 'General questions', person: 'Team Lead' });
        whoToAsk.push({ topic: 'Architecture', person: 'Senior Developer' });
        whoToAsk.push({ topic: 'Code review', person: 'Any teammate' });
    }
    return whoToAsk.slice(0, 8);
}
//# sourceMappingURL=team-intel.js.map