"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordInteraction = recordInteraction;
exports.getModelProfiles = getModelProfiles;
exports.compareTools = compareTools;
exports.suggestTool = suggestTool;
exports.recordPrompt = recordPrompt;
exports.suggestPrompt = suggestPrompt;
exports.buildToolSpecificContext = buildToolSpecificContext;
exports.getModelHistory = getModelHistory;
const database_1 = require("../../06-memory/database/database");
// ─── Model Profile Builder ───────────────────────────────────────────────────
function recordInteraction(params) {
    (0, database_1.initializeDatabase)();
    const db = (0, database_1.getDb)();
    const now = new Date().toISOString();
    const result = db.prepare(`INSERT INTO model_interactions (model_name, task_type, suggestion, accepted, rejection_reason, time_to_accept_ms, project, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(params.modelName, params.taskType, params.suggestion, params.accepted ? 1 : 0, params.rejectionReason || null, params.timeToAcceptMs || null, params.project, now);
    updateModelProfile(params.modelName, params.taskType);
    return Number(result.lastInsertRowid);
}
function updateModelProfile(modelName, taskType) {
    const db = (0, database_1.getDb)();
    const stats = db.prepare("SELECT COUNT(*) as total, SUM(CASE WHEN accepted = 1 THEN 1 ELSE 0 END) as accepted, SUM(CASE WHEN accepted = 0 THEN 1 ELSE 0 END) as rejected, AVG(time_to_accept_ms) as avg_time FROM model_interactions WHERE model_name = ? AND task_type = ?").get(modelName, taskType);
    if (!stats || stats.total === 0)
        return;
    const acceptanceRate = stats.total > 0 ? (stats.accepted || 0) / stats.total : 0;
    const rejectionRate = stats.total > 0 ? (stats.rejected || 0) / stats.total : 0;
    const bestCases = db.prepare("SELECT task_type, COUNT(*) as cnt FROM model_interactions WHERE model_name = ? AND accepted = 1 GROUP BY task_type ORDER BY cnt DESC LIMIT 3").all(modelName);
    const worstCases = db.prepare("SELECT task_type, COUNT(*) as cnt FROM model_interactions WHERE model_name = ? AND accepted = 0 GROUP BY task_type ORDER BY cnt DESC LIMIT 3").all(modelName);
    db.prepare(`INSERT OR REPLACE INTO model_profiles (model_name, task_type, acceptance_rate, rejection_rate, avg_time_ms, best_use_cases, worst_use_cases)
     VALUES (?, ?, ?, ?, ?, ?, ?)`).run(modelName, taskType, Math.round(acceptanceRate * 100) / 100, Math.round(rejectionRate * 100) / 100, Math.round(stats.avg_time || 0), JSON.stringify(bestCases.map(b => b.task_type)), JSON.stringify(worstCases.map(w => w.task_type)));
}
function getModelProfiles() {
    (0, database_1.initializeDatabase)();
    const db = (0, database_1.getDb)();
    const rows = db.prepare('SELECT mp.*, (SELECT COUNT(*) FROM model_interactions mi WHERE mi.model_name = mp.model_name) as total_interactions FROM model_profiles mp ORDER BY acceptance_rate DESC').all();
    return rows.map(r => ({
        id: Number(r.id),
        modelName: String(r.model_name || ''),
        taskType: String(r.task_type || ''),
        acceptanceRate: Number(r.acceptance_rate || 0),
        rejectionRate: Number(r.rejection_rate || 0),
        avgTimeMs: Number(r.avg_time_ms || 0),
        bestUseCases: safeJson(String(r.best_use_cases || '[]')) || [],
        worstUseCases: safeJson(String(r.worst_use_cases || '[]')) || [],
        totalInteractions: Number(r.total_interactions || 0),
        createdAt: String(r.created_at || ''),
    }));
}
// ─── Tool Performance Analyzer ───────────────────────────────────────────────
function compareTools() {
    const db = (0, database_1.getDb)();
    const tools = db.prepare('SELECT tool_name, COUNT(*) as sessions FROM sessions GROUP BY tool_name ORDER BY sessions DESC').all();
    const comparisons = [];
    for (const tool of tools) {
        const sessions = db.prepare('SELECT files_touched, key_decisions, start_time, end_time FROM sessions WHERE tool_name = ? AND end_time IS NOT NULL').all(tool.tool_name);
        let totalMinutes = 0;
        let totalFiles = 0;
        let totalDecisions = 0;
        for (const s of sessions) {
            const start = new Date(s.start_time).getTime();
            const end = new Date(s.end_time).getTime();
            totalMinutes += (end - start) / (1000 * 60);
            try {
                totalFiles += JSON.parse(s.files_touched).length;
                totalDecisions += JSON.parse(s.key_decisions).length;
            }
            catch { /* skip */ }
        }
        const decisions = db.prepare("SELECT technology, was_right FROM decisions WHERE project IN (SELECT DISTINCT project FROM sessions WHERE tool_name = ?)").all(tool.tool_name);
        const rightCount = decisions.filter(d => d.was_right === 1).length;
        const acceptanceRate = decisions.length > 0 ? rightCount / decisions.length : 0.5;
        const taskTypes = db.prepare("SELECT task_type, COUNT(*) as cnt, SUM(CASE WHEN accepted = 1 THEN 1 ELSE 0 END) as acc FROM model_interactions WHERE model_name = ? GROUP BY task_type").all(tool.tool_name);
        const taskBreakdown = taskTypes.map(t => ({
            task: t.task_type,
            count: t.cnt,
            successRate: t.cnt > 0 ? Math.round((t.acc / t.cnt) * 100) / 100 : 0,
        }));
        const bestTasks = taskBreakdown.filter(t => t.successRate >= 0.7).map(t => t.task);
        const worstTasks = taskBreakdown.filter(t => t.successRate < 0.4).map(t => t.task);
        let recommendation = '';
        if (acceptanceRate >= 0.7)
            recommendation = `${tool.tool_name} is a strong choice — ${Math.round(acceptanceRate * 100)}% decision success rate.`;
        else if (acceptanceRate >= 0.5)
            recommendation = `${tool.tool_name} is decent — ${Math.round(acceptanceRate * 100)}% success. Consider alternatives for critical tasks.`;
        else
            recommendation = `${tool.tool_name} has a ${Math.round(acceptanceRate * 100)}% success rate. Consider switching tools for better results.`;
        comparisons.push({
            tool: tool.tool_name,
            totalSessions: tool.sessions,
            acceptanceRate: Math.round(acceptanceRate * 100) / 100,
            avgSessionMinutes: sessions.length > 0 ? Math.round(totalMinutes / sessions.length) : 0,
            taskBreakdown,
            bestFor: bestTasks,
            worstFor: worstTasks,
            recommendation,
        });
    }
    return comparisons.sort((a, b) => b.acceptanceRate - a.acceptanceRate);
}
function suggestTool(taskType) {
    const db = (0, database_1.getDb)();
    const suggestions = [];
    const toolStats = db.prepare("SELECT model_name, COUNT(*) as total, SUM(CASE WHEN accepted = 1 THEN 1 ELSE 0 END) as accepted FROM model_interactions WHERE task_type = ? GROUP BY model_name").all(taskType);
    for (const t of toolStats) {
        if (t.total < 1)
            continue;
        const successRate = t.total > 0 ? t.accepted / t.total : 0;
        suggestions.push({
            tool: t.model_name,
            confidence: Math.min(0.95, 0.3 + t.total * 0.05),
            reason: successRate >= 0.7
                ? `${t.model_name} has ${Math.round(successRate * 100)}% success rate for ${taskType}`
                : `${t.model_name} has only ${Math.round(successRate * 100)}% success for ${taskType} — consider alternatives`,
            successRate: Math.round(successRate * 100) / 100,
            basedOnSessions: t.total,
        });
    }
    if (suggestions.length === 0) {
        const allTools = db.prepare('SELECT tool_name, COUNT(*) as sessions FROM sessions GROUP BY tool_name ORDER BY sessions DESC').all();
        for (const tool of allTools) {
            suggestions.push({
                tool: tool.tool_name,
                confidence: 0.2,
                reason: `No specific data for "${taskType}" with ${tool.tool_name} — using general session data`,
                successRate: 0.5,
                basedOnSessions: tool.sessions,
            });
        }
    }
    return suggestions.sort((a, b) => b.confidence - a.confidence);
}
// ─── Prompt Optimizer ────────────────────────────────────────────────────────
function recordPrompt(params) {
    const db = (0, database_1.getDb)();
    const now = new Date().toISOString();
    const existing = db.prepare('SELECT id, success_rate, use_count, avg_iterations FROM prompt_history WHERE model_name = ? AND task_type = ? AND prompt_pattern = ?').get(params.modelName, params.taskType, params.promptPattern);
    if (existing) {
        const newCount = existing.use_count + 1;
        const newSuccessRate = ((existing.success_rate * existing.use_count) + (params.success ? 1 : 0)) / newCount;
        const newAvgIterations = ((existing.avg_iterations * existing.use_count) + params.iterations) / newCount;
        db.prepare('UPDATE prompt_history SET success_rate = ?, use_count = ?, avg_iterations = ? WHERE id = ?').run(Math.round(newSuccessRate * 100) / 100, newCount, Math.round(newAvgIterations * 10) / 10, existing.id);
        return existing.id;
    }
    const result = db.prepare('INSERT INTO prompt_history (model_name, task_type, prompt_pattern, success_rate, use_count, avg_iterations, project) VALUES (?, ?, ?, ?, ?, ?, ?)').run(params.modelName, params.taskType, params.promptPattern, params.success ? 1 : 0, 1, params.iterations, params.project);
    return Number(result.lastInsertRowid);
}
function suggestPrompt(taskType, modelName) {
    const db = (0, database_1.getDb)();
    const query = modelName
        ? 'SELECT * FROM prompt_history WHERE task_type = ? AND model_name = ? ORDER BY success_rate DESC, use_count DESC LIMIT 5'
        : 'SELECT * FROM prompt_history WHERE task_type = ? ORDER BY success_rate DESC, use_count DESC LIMIT 5';
    const params = modelName ? [taskType, modelName] : [taskType];
    const rows = db.prepare(query).all(...params);
    return rows.map(r => ({
        pattern: String(r.prompt_pattern || ''),
        tool: String(r.model_name || ''),
        confidence: Number(r.success_rate || 0),
        successRate: Number(r.success_rate || 0),
        example: `Used ${r.use_count} times, ${Math.round(Number(r.avg_iterations || 0))} avg iterations`,
    }));
}
// ─── Model-Specific @Cell ────────────────────────────────────────────────────
function buildToolSpecificContext(toolName) {
    const db = (0, database_1.getDb)();
    const lines = [];
    const profile = db.prepare('SELECT * FROM model_profiles WHERE model_name = ? ORDER BY acceptance_rate DESC LIMIT 1').get(toolName);
    if (profile) {
        const bestCases = (safeJson(String(profile.best_use_cases || '[]')) || []);
        const worstCases = (safeJson(String(profile.worst_use_cases || '[]')) || []);
        const accRate = Number(profile.acceptance_rate || 0);
        lines.push(`## ${toolName} Profile`);
        lines.push(`- Acceptance rate: ${Math.round(accRate * 100)}%`);
        if (bestCases.length > 0)
            lines.push(`- Best for: ${bestCases.join(', ')}`);
        if (worstCases.length > 0)
            lines.push(`- Avoid for: ${worstCases.join(', ')}`);
    }
    const recentSessions = db.prepare("SELECT key_decisions, context_snapshot, start_time FROM sessions WHERE tool_name = ? ORDER BY start_time DESC LIMIT 3").all(toolName);
    if (recentSessions.length > 0) {
        lines.push(`\n## Recent ${toolName} History`);
        for (const s of recentSessions) {
            const decisions = safeJson(String(s.key_decisions)) || [];
            if (decisions.length > 0) {
                lines.push(`- ${decisions.slice(0, 2).join('; ')}`);
            }
        }
    }
    const toolRight = db.prepare("SELECT technology, was_right FROM decisions WHERE project IN (SELECT DISTINCT project FROM sessions WHERE tool_name = ?) ORDER BY created_at DESC LIMIT 10").all(toolName);
    if (toolRight.length > 0) {
        const rightCount = toolRight.filter(d => d.was_right === 1).length;
        lines.push(`\n## Decision Success with ${toolName}`);
        lines.push(`- ${rightCount}/${toolRight.length} decisions were correct (${Math.round((rightCount / toolRight.length) * 100)}%)`);
    }
    return lines.join('\n') || `No specific data yet for ${toolName}. Use it more to build a profile.`;
}
// ─── History ─────────────────────────────────────────────────────────────────
function getModelHistory() {
    const db = (0, database_1.getDb)();
    const rows = db.prepare(`SELECT tool_name,
      COUNT(*) as sessions_count,
      SUM(CASE WHEN files_touched != '[]' THEN 1 ELSE 0 END) as files_sessions,
      SUM(CASE WHEN key_decisions != '[]' THEN 1 ELSE 0 END) as decision_sessions,
      AVG(strftime('%s', end_time) - strftime('%s', start_time)) / 60 as avg_min,
      MAX(start_time) as last_used
     FROM sessions WHERE end_time IS NOT NULL GROUP BY tool_name ORDER BY sessions_count DESC`).all();
    return rows.map(r => ({
        tool: String(r.tool_name || ''),
        taskType: 'general',
        sessionsCount: Number(r.sessions_count || 0),
        totalFilesTouched: Number(r.files_sessions || 0),
        totalDecisions: Number(r.decision_sessions || 0),
        avgSessionMinutes: Math.round(Number(r.avg_min || 0)),
        lastUsed: String(r.last_used || ''),
    }));
}
// ─── Utility ─────────────────────────────────────────────────────────────────
function safeJson(val) {
    if (!val || val === '[]' || val === '{}')
        return null;
    try {
        return JSON.parse(val);
    }
    catch {
        return val;
    }
}
//# sourceMappingURL=cross-model-memory.js.map