"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KnowledgeGraphEngine = void 0;
const cell_store_1 = require("../../06-memory/stores/cell-store");
class KnowledgeGraphEngine {
    store;
    data;
    constructor(cellDir) {
        this.store = new cell_store_1.CellStore(cellDir);
        this.data = this.store.read('knowledge.json', 'personal') || {
            version: 1, updated: Date.now(),
            technologies: [],
            session: { currentFiles: [], lastContext: '', openProblems: [], pendingDecisions: [], experiments: [], startTime: Date.now(), history: [], decisions: [] },
            projects: [],
        };
    }
    detectTechnologies(code, filePath) {
        let detected = 0;
        const techMap = {
            React: { category: 'frontend', match: /from\s+['"]react['"]|import.*\breact\b/i },
            Vue: { category: 'frontend', match: /from\s+['"]vue['"]/i },
            Angular: { category: 'frontend', match: /@angular/i },
            Express: { category: 'backend', match: /from\s+['"]express['"]|\brequire\s*\(['"]express['"]\)/i },
            Prisma: { category: 'database', match: /@prisma\/client/i },
            TypeORM: { category: 'database', match: /from\s+['"]typeorm['"]/i },
            Mongoose: { category: 'database', match: /from\s+['"]mongoose['"]/i },
            TypeScript: { category: 'language', match: /:\s*\w+|<[A-Z]\w*>|interface\s+|type\s+\w+\s*=/ },
            Zod: { category: 'tool', match: /\bfrom\s+['"]zod['"]/i },
            Tailwind: { category: 'tool', match: /\bclassName\s*:?\s*['"](?:flex|grid|text-|bg-)/ },
            Jest: { category: 'tool', match: /\bjest\.(?:fn|mock|spy|describe|it\s*\()/i },
            Vitest: { category: 'tool', match: /\bvitest\b|from\s+['"]vitest['"]/i },
            Playwright: { category: 'tool', match: /\bplaywright\b|from\s+['"]@playwright/i },
            Docker: { category: 'tool', match: /FROM\s+\w+|docker-compose/i },
        };
        for (const [name, config] of Object.entries(techMap)) {
            if (config.match.test(code)) {
                const existing = this.data.technologies.find(t => t.name === name);
                if (existing) {
                    existing.uses++;
                    existing.lastUsed = Date.now();
                }
                else {
                    this.data.technologies.push({
                        name, category: config.category,
                        proficiency: 'learning', confidence: 0.5,
                        firstUsed: Date.now(), lastUsed: Date.now(), uses: 1,
                    });
                    detected++;
                }
            }
        }
        return { detected };
    }
    updateProficiency(name, hasErrors) {
        const tech = this.data.technologies.find(t => t.name === name);
        if (!tech)
            return;
        tech.confidence = hasErrors
            ? tech.confidence * 0.8
            : tech.confidence + (1 - tech.confidence) * 0.3;
        if (tech.confidence > 0.75)
            tech.proficiency = 'strong';
        else if (tech.confidence > 0.4)
            tech.proficiency = 'learning';
        else if (tech.confidence > 0.2)
            tech.proficiency = 'weak';
        else
            tech.proficiency = 'avoided';
        this.save();
    }
    updateSession(filePath, action) {
        if (filePath) {
            if (!this.data.session.currentFiles.includes(filePath))
                this.data.session.currentFiles.push(filePath);
            if (this.data.session.currentFiles.length > 10)
                this.data.session.currentFiles = this.data.session.currentFiles.slice(-10);
            if (action) {
                this.data.session.history.push({ file: filePath, action, timestamp: Date.now() });
                if (this.data.session.history.length > 50)
                    this.data.session.history = this.data.session.history.slice(-50);
            }
            // Build context chain
            const recentHistory = this.data.session.history.slice(-5);
            this.data.session.lastContext = recentHistory
                .map(h => `${h.action} in ${h.file}`)
                .join(' → ');
            this.data.session.startTime = Date.now();
        }
        this.data.updated = Date.now();
        this.save();
    }
    addOpenProblem(problem) {
        if (!this.data.session.openProblems.includes(problem))
            this.data.session.openProblems.push(problem);
        this.save();
    }
    addPendingDecision(choice, alternatives) {
        const id = `dec_${Date.now()}`;
        this.data.session.decisions.push({ id, choice, alternatives, timestamp: Date.now(), resolved: false });
        this.data.session.pendingDecisions.push(choice);
        this.save();
    }
    resolveDecision(choice) {
        const dec = this.data.session.decisions.find(d => d.choice === choice && !d.resolved);
        if (dec) {
            dec.resolved = true;
            this.data.session.pendingDecisions = this.data.session.pendingDecisions.filter(p => p !== choice);
        }
        this.save();
    }
    addExperiment(experiment) {
        if (!this.data.session.experiments.includes(experiment))
            this.data.session.experiments.push(experiment);
        this.save();
    }
    getSessionContext() {
        const s = this.data.session;
        const parts = [];
        if (s.currentFiles.length > 0)
            parts.push(`Files: ${s.currentFiles.join(', ')}`);
        if (s.lastContext)
            parts.push(`Context: ${s.lastContext}`);
        if (s.openProblems.length > 0)
            parts.push(`Problems: ${s.openProblems.join(', ')}`);
        if (s.pendingDecisions.length > 0)
            parts.push(`Decisions: ${s.pendingDecisions.join(', ')}`);
        if (s.experiments.length > 0)
            parts.push(`Experiments: ${s.experiments.join(', ')}`);
        return parts.join('\n');
    }
    recordProject(name, stack) {
        const existing = this.data.projects.find(p => p.name === name);
        if (existing) {
            existing.stack = [...new Set([...existing.stack, ...stack])];
            existing.patternsFound++;
        }
        else {
            this.data.projects.push({ name, stack, detectedAt: Date.now(), patternsFound: 1, confidence: 0.5 });
        }
        this.save();
    }
    getSummary() {
        const lines = [];
        if (this.data.technologies.length === 0 && this.data.projects.length === 0)
            return [];
        const strong = this.data.technologies.filter(t => t.proficiency === 'strong');
        const learning = this.data.technologies.filter(t => t.proficiency === 'learning');
        const weak = this.data.technologies.filter(t => t.proficiency === 'weak');
        if (strong.length > 0)
            lines.push(`Strong: ${strong.map(t => t.name).join(', ')}`);
        if (learning.length > 0)
            lines.push(`Learning: ${learning.map(t => t.name).join(', ')}`);
        if (weak.length > 0)
            lines.push(`⚠️  Weak areas: ${weak.map(t => t.name).join(', ')}`);
        if (this.data.projects.length > 0)
            lines.push(`Projects: ${this.data.projects.map(p => `${p.name} (${p.stack.slice(0, 3).join(',')})`).join(', ')}`);
        const s = this.data.session;
        if (s.currentFiles.length > 0)
            lines.push(`Session: ${s.currentFiles.length} files open, ${s.history.length} actions`);
        if (s.lastContext)
            lines.push(`Last: ${s.lastContext.slice(0, 60)}`);
        if (s.openProblems.length > 0)
            lines.push(`Open: ${s.openProblems.slice(0, 2).join(', ')}`);
        if (s.pendingDecisions.length > 0)
            lines.push(`Decisions: ${s.pendingDecisions.length} pending`);
        if (s.experiments.length > 0)
            lines.push(`Experiments: ${s.experiments.slice(0, 2).join(', ')}`);
        return lines;
    }
    save() {
        this.data.updated = Date.now();
        this.store.write('knowledge.json', this.data, 'personal');
    }
}
exports.KnowledgeGraphEngine = KnowledgeGraphEngine;
//# sourceMappingURL=knowledge-graph-engine.js.map