"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeIDETables = initializeIDETables;
exports.recordDebugSession = recordDebugSession;
exports.getDebugStyle = getDebugStyle;
exports.recordPromptEntry = recordPromptEntry;
exports.getPromptStyle = getPromptStyle;
exports.recordFocusBlock = recordFocusBlock;
exports.recordTabSwitch = recordTabSwitch;
exports.getFocusAnalysis = getFocusAnalysis;
exports.recordCopyPaste = recordCopyPaste;
exports.recordRefactor = recordRefactor;
exports.recordStuck = recordStuck;
exports.getCopyPasteInsights = getCopyPasteInsights;
exports.getRefactorInsights = getRefactorInsights;
exports.getStuckInsights = getStuckInsights;
exports.getIDEInsights = getIDEInsights;
const database_1 = require("../../06-memory/database/database");
// ─── Storage ─────────────────────────────────────────────────────────────────
function initializeIDETables() {
    const db = (0, database_1.getDb)();
    db.exec(`
    CREATE TABLE IF NOT EXISTS debug_sessions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      file TEXT NOT NULL,
      method TEXT NOT NULL,
      duration_ms INTEGER NOT NULL,
      resolved INTEGER DEFAULT 0,
      resolution_time_ms INTEGER
    );

    CREATE TABLE IF NOT EXISTS prompt_entries (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      tool TEXT NOT NULL,
      prompt_length INTEGER NOT NULL,
      word_count INTEGER NOT NULL,
      has_code_block INTEGER DEFAULT 0,
      has_context_ref INTEGER DEFAULT 0,
      iteration_count INTEGER DEFAULT 1,
      accepted INTEGER DEFAULT 1,
      response_quality INTEGER DEFAULT 50
    );

    CREATE TABLE IF NOT EXISTS focus_blocks (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      file TEXT NOT NULL,
      duration_ms INTEGER NOT NULL,
      switch_count INTEGER DEFAULT 0,
      type TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS tab_switches (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      from_file TEXT NOT NULL,
      to_file TEXT NOT NULL,
      context_switch_cost_ms INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS copy_paste_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      source TEXT NOT NULL,
      source_url TEXT,
      content_length INTEGER NOT NULL,
      file TEXT NOT NULL,
      knowledge_gap INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS refactor_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      file TEXT NOT NULL,
      type TEXT NOT NULL,
      lines_changed INTEGER DEFAULT 0,
      ai_assisted INTEGER DEFAULT 0
    );

    CREATE TABLE IF NOT EXISTS stuck_events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp TEXT NOT NULL,
      file TEXT NOT NULL,
      stuck_duration_ms INTEGER NOT NULL,
      resolved INTEGER DEFAULT 0,
      sought_help INTEGER DEFAULT 0,
      help_source TEXT
    );
  `);
}
// ─── Debug Tracker ───────────────────────────────────────────────────────────
function recordDebugSession(file, method, durationMs, resolved = false, resolutionTimeMs = null) {
    const db = (0, database_1.getDb)();
    const result = db.prepare('INSERT INTO debug_sessions (timestamp, file, method, duration_ms, resolved, resolution_time_ms) VALUES (?, ?, ?, ?, ?, ?)').run(new Date().toISOString(), file, method, durationMs, resolved ? 1 : 0, resolutionTimeMs);
    return Number(result.lastInsertRowid);
}
function getDebugStyle() {
    const db = (0, database_1.getDb)();
    const total = db.prepare('SELECT COUNT(*) as count FROM debug_sessions').get();
    const methods = db.prepare('SELECT method, COUNT(*) as count FROM debug_sessions GROUP BY method ORDER BY count DESC').all();
    const methodBreakdown = {};
    for (const m of methods) {
        methodBreakdown[m.method] = m.count;
    }
    const preferredMethod = methods[0]?.method || 'console.log';
    const consoleLogCount = methodBreakdown['console.log'] || 0;
    const debuggerCount = (methodBreakdown['debugger'] || 0) + (methodBreakdown['breakpoint'] || 0);
    const consoleLogPercent = total.count > 0 ? Math.round((consoleLogCount / total.count) * 100) : 0;
    const debuggerPercent = total.count > 0 ? Math.round((debuggerCount / total.count) * 100) : 0;
    const avgRes = db.prepare('SELECT AVG(resolution_time_ms) as avg FROM debug_sessions WHERE resolved = 1 AND resolution_time_ms IS NOT NULL').get();
    const avgResolutionTimeMs = avgRes.avg || 0;
    const efficiencyScore = debuggerPercent > 30 ? 85 : consoleLogPercent > 70 ? 60 : 70;
    const recommendation = consoleLogPercent > 70
        ? 'Console.log heavy (' + consoleLogPercent + '%). Consider formal debugger for complex bugs — 40% faster resolution.'
        : debuggerPercent > 50
            ? 'Good debugger usage. Maintain balanced approach.'
            : 'Mixed debugging style. Keep experimenting.';
    return {
        totalSessions: total.count,
        methodBreakdown,
        preferredMethod,
        consoleLogPercent,
        debuggerPercent,
        avgResolutionTimeMs: Math.round(avgResolutionTimeMs),
        efficiencyScore,
        recommendation,
    };
}
// ─── Prompt Style ────────────────────────────────────────────────────────────
function recordPromptEntry(tool, promptLength, wordCount, hasCodeBlock, hasContextRef, iterationCount = 1, accepted = true, responseQuality = 50) {
    const db = (0, database_1.getDb)();
    const result = db.prepare('INSERT INTO prompt_entries (timestamp, tool, prompt_length, word_count, has_code_block, has_context_ref, iteration_count, accepted, response_quality) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(new Date().toISOString(), tool, promptLength, wordCount, hasCodeBlock ? 1 : 0, hasContextRef ? 1 : 0, iterationCount, accepted ? 1 : 0, responseQuality);
    return Number(result.lastInsertRowid);
}
function getPromptStyle() {
    const db = (0, database_1.getDb)();
    const total = db.prepare('SELECT COUNT(*) as count FROM prompt_entries').get();
    const avgWords = db.prepare('SELECT AVG(word_count) as avg FROM prompt_entries').get();
    const avgIterations = db.prepare('SELECT AVG(iteration_count) as avg FROM prompt_entries').get();
    const accepted = db.prepare('SELECT COUNT(*) as count FROM prompt_entries WHERE accepted = 1').get();
    const codeFirst = db.prepare('SELECT COUNT(*) as count FROM prompt_entries WHERE has_code_block = 1').get();
    const contextFirst = db.prepare('SELECT COUNT(*) as count FROM prompt_entries WHERE has_context_ref = 1').get();
    const structureBreakdown = {};
    if (total.count > 0) {
        structureBreakdown['code-first'] = Math.round((codeFirst.count / total.count) * 100);
        structureBreakdown['explain-first'] = 100 - structureBreakdown['code-first'];
    }
    const avgWordCount = Math.round(avgWords.avg || 0);
    const preferredStyle = avgWordCount > 60 ? 'detailed' : avgWordCount > 30 ? 'moderate' : 'concise';
    const acceptanceRate = total.count > 0 ? Math.round((accepted.count / total.count) * 100) : 0;
    let bestPromptLength = 'moderate';
    if (acceptanceRate > 80) {
        bestPromptLength = avgWordCount > 60 ? 'long-detailed' : 'short-concise';
    }
    const recommendation = acceptanceRate < 70
        ? 'Low acceptance rate (' + acceptanceRate + '%). Try longer prompts with more context.'
        : avgWordCount < 20
            ? 'Very short prompts. Adding code examples may improve results.'
            : 'Good prompt style. Keep it up.';
    return {
        totalPrompts: total.count,
        avgWordCount,
        preferredStyle,
        structureBreakdown,
        avgIterations: Math.round((avgIterations.avg || 1) * 10) / 10,
        acceptanceRate,
        bestPromptLength,
        recommendation,
    };
}
// ─── Focus & Attention ──────────────────────────────────────────────────────
function recordFocusBlock(file, durationMs, switchCount) {
    const db = (0, database_1.getDb)();
    let type = 'deep';
    if (durationMs < 60000)
        type = 'scattered';
    else if (switchCount > 5)
        type = 'shallow';
    const result = db.prepare('INSERT INTO focus_blocks (timestamp, file, duration_ms, switch_count, type) VALUES (?, ?, ?, ?, ?)').run(new Date().toISOString(), file, durationMs, switchCount, type);
    return Number(result.lastInsertRowid);
}
function recordTabSwitch(fromFile, toFile, costMs = 0) {
    const db = (0, database_1.getDb)();
    const result = db.prepare('INSERT INTO tab_switches (timestamp, from_file, to_file, context_switch_cost_ms) VALUES (?, ?, ?, ?)').run(new Date().toISOString(), fromFile, toFile, costMs);
    return Number(result.lastInsertRowid);
}
function getFocusAnalysis() {
    const db = (0, database_1.getDb)();
    const total = db.prepare('SELECT SUM(duration_ms) as total FROM focus_blocks').get();
    const deep = db.prepare("SELECT SUM(duration_ms) as total FROM focus_blocks WHERE type = 'deep'").get();
    const shallow = db.prepare("SELECT SUM(duration_ms) as total FROM focus_blocks WHERE type = 'shallow'").get();
    const totalMs = total.total || 0;
    const deepMs = deep.total || 0;
    const shallowMs = shallow.total || 0;
    const deepPercent = totalMs > 0 ? Math.round((deepMs / totalMs) * 100) : 0;
    const shallowPercent = totalMs > 0 ? Math.round((shallowMs / totalMs) * 100) : 0;
    const avgBlock = db.prepare('SELECT AVG(duration_ms) as avg FROM focus_blocks').get();
    const longest = db.prepare('SELECT MAX(duration_ms) as max FROM focus_blocks').get();
    const hourDist = db.prepare("SELECT CAST(strftime('%H', timestamp) AS INTEGER) as hour, SUM(duration_ms) as total FROM focus_blocks GROUP BY hour ORDER BY total DESC LIMIT 1").get();
    const focusScore = deepPercent > 60 ? 90 : deepPercent > 40 ? 75 : deepPercent > 20 ? 60 : 40;
    const peakFocusHour = hourDist?.hour ?? 10;
    const recommendation = deepPercent > 60
        ? 'Excellent deep work (' + deepPercent + '%). Maintain focus blocks.'
        : deepPercent > 40
            ? 'Good focus. Try to reduce tab switching during deep work.'
            : 'Shallow work dominant. Consider focus blocks — no tab switching for 1+ hour.';
    return {
        totalFocusTimeMs: totalMs,
        deepWorkPercent: deepPercent,
        shallowWorkPercent: shallowPercent,
        avgFocusBlockMs: Math.round(avgBlock.avg || 0),
        longestFocusMs: longest.max || 0,
        focusScore,
        peakFocusHour,
        recommendation,
    };
}
// ─── Copy-Paste & Refactoring ───────────────────────────────────────────────
function recordCopyPaste(source, sourceUrl, contentLength, file, knowledgeGap = false) {
    const db = (0, database_1.getDb)();
    const result = db.prepare('INSERT INTO copy_paste_events (timestamp, source, source_url, content_length, file, knowledge_gap) VALUES (?, ?, ?, ?, ?, ?)').run(new Date().toISOString(), source, sourceUrl, contentLength, file, knowledgeGap ? 1 : 0);
    return Number(result.lastInsertRowid);
}
function recordRefactor(file, type, linesChanged, aiAssisted = false) {
    const db = (0, database_1.getDb)();
    const result = db.prepare('INSERT INTO refactor_events (timestamp, file, type, lines_changed, ai_assisted) VALUES (?, ?, ?, ?, ?)').run(new Date().toISOString(), file, type, linesChanged, aiAssisted ? 1 : 0);
    return Number(result.lastInsertRowid);
}
function recordStuck(file, stuckDurationMs, resolved = false, soughtHelp = false, helpSource = null) {
    const db = (0, database_1.getDb)();
    const result = db.prepare('INSERT INTO stuck_events (timestamp, file, stuck_duration_ms, resolved, sought_help, help_source) VALUES (?, ?, ?, ?, ?, ?)').run(new Date().toISOString(), file, stuckDurationMs, resolved ? 1 : 0, soughtHelp ? 1 : 0, helpSource);
    return Number(result.lastInsertRowid);
}
function getCopyPasteInsights() {
    const db = (0, database_1.getDb)();
    return db.prepare('SELECT * FROM copy_paste_events ORDER BY timestamp DESC LIMIT 20').all();
}
function getRefactorInsights() {
    const db = (0, database_1.getDb)();
    return db.prepare('SELECT * FROM refactor_events ORDER BY timestamp DESC LIMIT 20').all();
}
function getStuckInsights() {
    const db = (0, database_1.getDb)();
    return db.prepare('SELECT * FROM stuck_events ORDER BY timestamp DESC LIMIT 20').all();
}
// ─── Combined Insights ──────────────────────────────────────────────────────
function getIDEInsights() {
    const debug = getDebugStyle();
    const prompt = getPromptStyle();
    const focus = getFocusAnalysis();
    const copyPaste = getCopyPasteInsights();
    const refactor = getRefactorInsights();
    const stuck = getStuckInsights();
    const overallScore = Math.round((debug.efficiencyScore + prompt.acceptanceRate + focus.focusScore) / 3);
    const topInsights = [];
    if (debug.consoleLogPercent > 70) {
        topInsights.push('Console.log dominant (' + debug.consoleLogPercent + '%) — consider debugger');
    }
    if (focus.deepWorkPercent < 30) {
        topInsights.push('Shallow work dominant — try focus blocks');
    }
    if (prompt.avgIterations > 3) {
        topInsights.push('High iteration count (' + prompt.avgIterations + ') — add more context');
    }
    if (copyPaste.length > 5) {
        topInsights.push(copyPaste.length + ' external copy-paste events — knowledge gaps detected');
    }
    if (stuck.length > 3) {
        topInsights.push(stuck.length + ' stuck events — seek help earlier');
    }
    return {
        debug,
        prompt,
        focus,
        copyPaste,
        refactor,
        stuck,
        overallScore,
        topInsights,
    };
}
//# sourceMappingURL=ide-intelligence.js.map