"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.buildDeveloperIntelligence = buildDeveloperIntelligence;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const logger_1 = require("../../06-memory/database/logger");
const behavior_intelligence_1 = require("../../03-knowledge/decisions/behavior-intelligence");
const journey_memory_1 = require("../../03-knowledge/decisions/journey-memory");
const user_intelligence_1 = require("../../01-context/context/user-intelligence");
function buildDeveloperIntelligence(rootDir) {
    if (!fs.existsSync(path.join(rootDir, '.git')))
        return null;
    try {
        const user = (0, user_intelligence_1.buildUserProfile)(rootDir);
        const behavior = (0, behavior_intelligence_1.buildIntelligenceReport)(rootDir);
        const journey = (0, journey_memory_1.buildJourneyReport)(rootDir);
        (0, user_intelligence_1.saveUserProfile)(user);
        (0, behavior_intelligence_1.saveIntelligenceReport)(behavior);
        (0, journey_memory_1.saveJourneyReport)(journey);
        // Sync to behavioral tracker
        syncToBehavioralTracker(user, behavior, journey, rootDir);
        // Score
        const behavioralScore = calculateBehavioralScore(behavior);
        // Summaries
        const topBlindSpots = behavior.blindSpots
            .filter(b => b.severity === 'high')
            .slice(0, 5)
            .map(b => `${b.area}: ${b.description} (${b.fileCount} files)`);
        const topMistakes = behavior.mistakes
            .filter(m => m.stillHappening)
            .slice(0, 5)
            .map(m => `${m.pattern} — ${m.count}x, last: ${m.lastOccurrence}`);
        const topStrengths = buildStrengths(behavior, user);
        const timeSummary = timeSummaryText(behavior.timePatterns);
        const journeySummary = journeySummaryText(journey);
        return {
            user, behavior, journey,
            behavioralScore, topBlindSpots, topMistakes, topStrengths,
            timeSummary, journeySummary,
            generatedAt: new Date().toISOString(),
        };
    }
    catch (err) {
        logger_1.logger.error(`Developer intelligence failed: ${String(err)}`);
        return null;
    }
}
// ─── Sync to Behavioral Tracker ──────────────────────────────────────
function syncToBehavioralTracker(user, behavior, journey, rootDir) {
    try {
        const { logError, logDecision, logContext } = require('./behavioral-tracker');
        const projectName = path.basename(rootDir);
        // Log blind spots as errors
        for (const bs of behavior.blindSpots.slice(0, 10)) {
            logError({
                project: projectName,
                file: bs.files[0] || '',
                errorType: `blind_spot_${bs.area}`,
                errorMessage: `${bs.description} — severity: ${bs.severity}, files: ${bs.fileCount}`,
                line: 0,
            });
        }
        // Log repeat mistakes as errors
        for (const m of behavior.mistakes.filter(m => m.stillHappening).slice(0, 10)) {
            logError({
                project: projectName,
                file: m.files[0] || '',
                errorType: `repeat_${m.category}`,
                errorMessage: `${m.pattern} — ${m.count} occurrences, last: ${m.lastOccurrence}`,
                line: 0,
            });
        }
        // Log decisions
        for (const d of behavior.decisions.slice(0, 20)) {
            logDecision({
                project: projectName,
                file: '',
                decision: `${d.type}: ${d.message}`,
                approach: d.from ? `${d.from} → ${d.to || 'removed'}` : (d.to || ''),
                worked: true,
            });
        }
        // Log current context
        const timeSummary = timeSummaryText(behavior.timePatterns);
        logContext({
            project: projectName,
            task: `Git intelligence: ${behavior.projectCount} projects, ${behavior.totalFiles} files. ${timeSummary}`,
            files: [],
        });
    }
    catch { /* behavioral tracker may not be ready */ }
}
// ─── Helpers ─────────────────────────────────────────────────────────
function timeSummaryText(tp) {
    const parts = [];
    if (tp.bestHours)
        parts.push(`Best hours: ${tp.bestHours}`);
    if (tp.mostProductiveDay)
        parts.push(`Most productive: ${tp.mostProductiveDay}`);
    if (tp.bugIntroductionTimes.length > 0) {
        parts.push(`${tp.bugIntroductionTimes.length} bugs found`);
    }
    return parts.join(' | ') || 'time data unavailable';
}
function journeySummaryText(jr) {
    const parts = [];
    if (jr.skills.length > 0) {
        const mastered = jr.skills.filter(s => s.currentLevel === 'mastered' || s.currentLevel === 'proficient');
        if (mastered.length > 0)
            parts.push(`Mastered: ${mastered.map(s => s.area).join(', ')}`);
        const learning = jr.skills.filter(s => s.currentLevel === 'beginner');
        if (learning.length > 0)
            parts.push(`Learning: ${learning.map(s => s.area).join(', ')}`);
    }
    if (jr.timeline.length > 0) {
        parts.push(`${jr.timeline.length} milestone events`);
    }
    return parts.join(' | ') || 'journey data building...';
}
function calculateBehavioralScore(behavior) {
    let score = 50;
    // Fewer high-severity blind spots = better
    const highBlinds = behavior.blindSpots.filter(b => b.severity === 'high').length;
    score -= Math.min(20, highBlinds * 4);
    // Fewer repeat mistakes = better
    score -= Math.min(15, behavior.mistakes.filter(m => m.stillHappening).length * 3);
    // More tech mastery = better
    score += Math.min(15, behavior.techMastery.filter(t => t.assessment === 'mastered').length * 3);
    return Math.max(0, Math.min(100, score));
}
function buildStrengths(behavior, _user) {
    const strengths = [];
    const mastered = behavior.techMastery.filter(t => t.assessment === 'mastered' || t.assessment === 'proficient');
    if (mastered.length > 0)
        strengths.push(`Strong in: ${mastered.map(t => t.language).join(', ')}`);
    if (behavior.blindSpots.filter(b => b.severity === 'high').length === 0) {
        strengths.push('No high-severity blind spots detected');
    }
    if (behavior.problemSolving.fileOrganization === 'many-small-files') {
        strengths.push('Clean file organization — small focused files');
    }
    if (behavior.problemSolving.comments.ratio > 0.5) {
        strengths.push('Well-documented code (good JSDoc ratio)');
    }
    return strengths;
}
//# sourceMappingURL=developer-intelligence.js.map