"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.sharePatternToMemory = sharePatternToMemory;
exports.getSharedPatterns = getSharedPatterns;
exports.getCompatiblePatterns = getCompatiblePatterns;
exports.getCrossProjectInsights = getCrossProjectInsights;
exports.getCrossProjectStats = getCrossProjectStats;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const database_1 = require("../database/database");
function getCrossProjectDir(projectDir) {
    return path.join(projectDir, '.cell', 'cross-project');
}
function ensureDir(dir) {
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}
function sharePatternToMemory(projectDir, pattern) {
    const project = path.basename(projectDir);
    const db = (0, database_1.getDb)();
    const result = db.prepare(`
    INSERT INTO memory_patterns (project, category, pattern, language, framework, success_rate, shared_at)
    VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
  `).run(project, pattern.category, pattern.rule, pattern.language || null, pattern.framework || null, pattern.successRate || 0.5);
    const id = String(result.lastInsertRowid);
    // Also save to cross-project directory for portability
    const dir = getCrossProjectDir(projectDir);
    ensureDir(dir);
    const filePath = path.join(dir, `${id}.json`);
    fs.writeFileSync(filePath, JSON.stringify({
        id,
        sourceProject: project,
        ...pattern,
        sharedAt: new Date().toISOString(),
    }, null, 2));
    return id;
}
function getSharedPatterns(projectDir, category) {
    const db = (0, database_1.getDb)();
    const project = path.basename(projectDir);
    if (category) {
        return db.prepare('SELECT * FROM memory_patterns WHERE project = ? AND category = ? ORDER BY shared_at DESC').all(project, category);
    }
    return db.prepare('SELECT * FROM memory_patterns WHERE project = ? ORDER BY shared_at DESC').all(project);
}
function getCompatiblePatterns(targetProject, targetStack) {
    const db = (0, database_1.getDb)();
    const allPatterns = db.prepare('SELECT * FROM memory_patterns ORDER BY success_rate DESC').all();
    return allPatterns
        .filter(p => p.sourceProject !== targetProject)
        .map(p => ({
        ...p,
        _compatibility: calculateCompatibility(p, targetStack),
    }))
        .filter((p) => p._compatibility > 0.3)
        .sort((a, b) => b._compatibility - a._compatibility)
        .slice(0, 20);
}
function calculateCompatibility(pattern, targetStack) {
    let score = 0.3; // base score
    // Language/framework match
    if (pattern.language && targetStack.some(s => s.toLowerCase().includes(pattern.language.toLowerCase()))) {
        score += 0.4;
    }
    if (pattern.framework && targetStack.some(s => s.toLowerCase().includes(pattern.framework.toLowerCase()))) {
        score += 0.3;
    }
    // Success rate boost
    score += pattern.successRate * 0.2;
    return Math.min(score, 1.0);
}
function getCrossProjectInsights(projectDir, allProjectDirs) {
    const targetProject = path.basename(projectDir);
    const targetStack = getProjectStack(projectDir);
    const compatiblePatterns = getCompatiblePatterns(targetProject, targetStack).map(p => ({
        pattern: p.pattern,
        compatibility: calculateCompatibility(p, targetStack),
        reason: `From ${p.sourceProject} (${p.language || 'unknown'})`,
    }));
    // Find shared errors across projects
    const db = (0, database_1.getDb)();
    const sharedErrors = db.prepare(`
    SELECT summary as error, COUNT(DISTINCT project) as project_count,
           GROUP_CONCAT(DISTINCT project) as projects
    FROM memory_events
    WHERE type = 'error'
    GROUP BY summary
    HAVING project_count >= 2
    ORDER BY project_count DESC
    LIMIT 10
  `).all();
    // Find shared decisions
    const sharedDecisions = db.prepare(`
    SELECT summary as decision, project,
           COALESCE(
             (SELECT summary FROM memory_events WHERE type = 'fix' AND topic IS NOT NULL LIMIT 1),
             'unknown'
           ) as outcome
    FROM memory_events
    WHERE type = 'decision'
    ORDER BY importance DESC
    LIMIT 10
  `).all();
    return {
        sourceProject: targetProject,
        targetProject,
        compatiblePatterns,
        sharedErrors: sharedErrors.map(e => ({
            error: e.error,
            count: e.project_count,
            projects: e.projects.split(','),
        })),
        sharedDecisions,
    };
}
function getProjectStack(projectDir) {
    const stack = [];
    try {
        const pkgPath = path.join(projectDir, 'package.json');
        if (fs.existsSync(pkgPath)) {
            const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
            const deps = { ...pkg.dependencies, ...pkg.devDependencies };
            if (deps.react || deps['react-dom'])
                stack.push('React');
            if (deps.vue)
                stack.push('Vue');
            if (deps.angular || deps['@angular/core'])
                stack.push('Angular');
            if (deps.express)
                stack.push('Express');
            if (deps.next)
                stack.push('Next.js');
            if (deps.nuxt)
                stack.push('Nuxt');
            if (deps.typescript)
                stack.push('TypeScript');
            if (deps.jest || deps.vitest)
                stack.push('testing');
            if (deps.prisma || deps.typeorm || deps.sequelize)
                stack.push('ORM');
            if (deps.mongoose || deps.mongodb)
                stack.push('MongoDB');
            if (deps.pg || deps.mysql2 || deps.better_sqlite3)
                stack.push('SQL');
        }
    }
    catch { }
    return stack;
}
function getCrossProjectStats() {
    const db = (0, database_1.getDb)();
    const totalRow = db.prepare('SELECT COUNT(*) as c FROM memory_patterns').get();
    const projectsRow = db.prepare('SELECT COUNT(DISTINCT project) as c FROM memory_patterns').get();
    const categories = db.prepare(`
    SELECT category, COUNT(*) as c FROM memory_patterns GROUP BY category ORDER BY c DESC LIMIT 10
  `).all();
    const projects = db.prepare(`
    SELECT project, COUNT(*) as c FROM memory_patterns GROUP BY project ORDER BY c DESC LIMIT 10
  `).all();
    return {
        totalPatterns: totalRow.c,
        totalProjects: projectsRow.c,
        topCategories: categories.map(c => ({ category: c.category, count: c.c })),
        topProjects: projects.map(p => ({ project: p.project, count: p.c })),
    };
}
//# sourceMappingURL=cross-project-memory.js.map