"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compressContext = compressContext;
exports.compressToMinimal = compressToMinimal;
exports.compressForAITool = compressForAITool;
exports.formatCompressedContext = formatCompressedContext;
exports.estimateTokens = estimateTokens;
const database_1 = require("../database/database");
function compressContext(options) {
    const db = (0, database_1.getDb)();
    const mode = options.mode || 'compact';
    const maxWords = options.maxWords || getDefaultMaxWords(mode);
    const days = options.days || getDefaultDays(mode);
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const sections = [];
    // Overview
    const totalRow = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ?').get(options.project);
    const recentRow = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND created_at >= ?').get(options.project, since);
    sections.push({
        type: 'overview',
        title: 'Overview',
        content: `${totalRow.c} total memories, ${recentRow.c} in last ${days}d`,
        wordCount: 12,
        importance: 10,
        compressed: true,
    });
    // Recent high-importance events
    const recentEvents = db.prepare(`
    SELECT type, summary, importance, topic, created_at FROM memory_events
    WHERE project = ? AND created_at >= ?
    ORDER BY importance DESC, created_at DESC
    LIMIT ?
  `).all(options.project, since, mode === 'compact' ? 10 : 25);
    if (recentEvents.length > 0) {
        const lines = recentEvents.map(e => {
            const age = formatAge(e.created_at);
            const topic = e.topic ? `[${e.topic}]` : '';
            return `- [${e.type}]${topic} ${e.summary.slice(0, 100)} (${age})`;
        });
        sections.push({
            type: 'recent',
            title: 'Recent Activity',
            content: lines.join('\n'),
            wordCount: lines.length * 8,
            importance: 9,
            compressed: true,
        });
    }
    // Decisions
    const decisions = db.prepare(`
    SELECT summary, topic, created_at FROM memory_events
    WHERE project = ? AND type = 'decision' AND created_at >= ?
    ORDER BY importance DESC, created_at DESC LIMIT ?
  `).all(options.project, since, mode === 'compact' ? 5 : 15);
    if (decisions.length > 0) {
        const lines = decisions.map(d => `- ${d.summary.slice(0, 120)}`);
        sections.push({
            type: 'decisions',
            title: 'Key Decisions',
            content: lines.join('\n'),
            wordCount: lines.length * 6,
            importance: 9,
            compressed: true,
        });
    }
    // Errors
    const errors = db.prepare(`
    SELECT summary, topic, importance, created_at FROM memory_events
    WHERE project = ? AND type = 'error' AND created_at >= ?
    ORDER BY importance DESC, created_at DESC LIMIT ?
  `).all(options.project, since, mode === 'compact' ? 5 : 15);
    if (errors.length > 0) {
        const lines = errors.map(e => `- [${e.importance}/10] ${e.summary.slice(0, 100)}`);
        sections.push({
            type: 'errors',
            title: 'Errors',
            content: lines.join('\n'),
            wordCount: lines.length * 6,
            importance: 8,
            compressed: true,
        });
    }
    // Fixes
    const fixes = db.prepare(`
    SELECT summary, topic, created_at FROM memory_events
    WHERE project = ? AND type = 'fix' AND created_at >= ?
    ORDER BY importance DESC, created_at DESC LIMIT ?
  `).all(options.project, since, mode === 'compact' ? 5 : 15);
    if (fixes.length > 0) {
        const lines = fixes.map(f => `- ${f.summary.slice(0, 100)}`);
        sections.push({
            type: 'fixes',
            title: 'Fixes Applied',
            content: lines.join('\n'),
            wordCount: lines.length * 5,
            importance: 7,
            compressed: true,
        });
    }
    // Patterns
    if (mode === 'full') {
        const patterns = db.prepare(`
      SELECT pattern, category, importance, confidence FROM memory_patterns
      WHERE project = ?
      ORDER BY importance DESC, confidence DESC LIMIT 10
    `).all(options.project);
        if (patterns.length > 0) {
            const lines = patterns.map(p => `- [${p.category}] ${p.pattern.slice(0, 80)} (imp:${p.importance} conf:${p.confidence})`);
            sections.push({
                type: 'patterns',
                title: 'Learned Patterns',
                content: lines.join('\n'),
                wordCount: lines.length * 8,
                importance: 7,
                compressed: true,
            });
        }
    }
    // Handoff
    if (options.includeHandoff !== false) {
        try {
            const { getCurrentHandoff } = require('../handoff/handoff-store');
            const handoff = getCurrentHandoff(options.project);
            if (handoff?.content) {
                const handoffContent = handoff.content.slice(0, 500);
                sections.push({
                    type: 'handoff',
                    title: 'Current Handoff',
                    content: handoffContent,
                    wordCount: handoffContent.split(/\s+/).length,
                    importance: 8,
                    compressed: handoff.content.length > 500,
                });
            }
        }
        catch { }
    }
    // Recommendations
    if (options.includeRecommendations !== false && mode !== 'compact') {
        try {
            const { generateSmartRecommendations } = require('./smart-recommendations');
            const recs = generateSmartRecommendations(options.project);
            if (recs.length > 0) {
                const lines = recs.slice(0, 5).map((r) => `- [${r.priority}] ${r.title}`);
                sections.push({
                    type: 'recommendations',
                    title: 'Recommendations',
                    content: lines.join('\n'),
                    wordCount: lines.length * 6,
                    importance: 6,
                    compressed: true,
                });
            }
        }
        catch { }
    }
    // Topic filter
    if (options.topic) {
        const topicEvents = db.prepare(`
      SELECT type, summary, importance, created_at FROM memory_events
      WHERE project = ? AND topic LIKE ? AND created_at >= ?
      ORDER BY importance DESC, created_at DESC LIMIT 20
    `).all(options.project, `%${options.topic}%`, since);
        if (topicEvents.length > 0) {
            const lines = topicEvents.map(e => `- [${e.type}] ${e.summary.slice(0, 100)}`);
            sections.push({
                type: 'topics',
                title: `Topic: ${options.topic}`,
                content: lines.join('\n'),
                wordCount: lines.length * 8,
                importance: 8,
                compressed: true,
            });
        }
    }
    // Limit sections
    const maxSections = options.maxSections || getDefaultMaxSections(mode);
    const sorted = sections.sort((a, b) => b.importance - a.importance).slice(0, maxSections);
    // Trim to max words
    let totalWords = 0;
    const trimmed = [];
    for (const s of sorted) {
        if (totalWords + s.wordCount > maxWords)
            break;
        trimmed.push(s);
        totalWords += s.wordCount;
    }
    const tokenEstimate = Math.ceil(totalWords * 1.3);
    const summary = `${trimmed.length} sections, ~${tokenEstimate} tokens`;
    return {
        project: options.project,
        mode,
        tokenEstimate,
        sections: trimmed,
        compressedAt: new Date().toISOString(),
        summary,
    };
}
function compressToMinimal(project) {
    return compressContext({ project, mode: 'compact', maxWords: 500, maxSections: 3, includeHandoff: false, includeRecommendations: false, includeFiles: false });
}
function compressForAITool(project, tool) {
    const profiles = {
        cursor: { mode: 'compact', maxWords: 1500, maxSections: 5, includeHandoff: true, includeRecommendations: false },
        copilot: { mode: 'compact', maxWords: 1000, maxSections: 4, includeHandoff: true, includeRecommendations: false },
        'claude-code': { mode: 'full', maxWords: 4000, maxSections: 8, includeHandoff: true, includeRecommendations: true },
        'opencode': { mode: 'full', maxWords: 3000, maxSections: 7, includeHandoff: true, includeRecommendations: true },
        windsurf: { mode: 'compact', maxWords: 2000, maxSections: 5, includeHandoff: true, includeRecommendations: false },
        aider: { mode: 'compact', maxWords: 1500, maxSections: 5, includeHandoff: true, includeRecommendations: false },
    };
    const opts = profiles[tool] || profiles['opencode'];
    return compressContext({ project, ...opts });
}
function formatCompressedContext(ctx) {
    const lines = [];
    lines.push(`## Context (${ctx.mode}) — ${ctx.project}`);
    lines.push(`> ${ctx.summary}\n`);
    for (const s of ctx.sections) {
        lines.push(`### ${s.title}`);
        lines.push(s.content);
        lines.push('');
    }
    return lines.join('\n');
}
function estimateTokens(text) {
    return Math.ceil(text.split(/\s+/).length * 1.3);
}
function getDefaultMaxWords(mode) {
    switch (mode) {
        case 'compact': return 1500;
        case 'full': return 5000;
        case 'topic': return 2000;
        default: return 1500;
    }
}
function getDefaultDays(mode) {
    switch (mode) {
        case 'compact': return 7;
        case 'full': return 30;
        case 'topic': return 14;
        default: return 7;
    }
}
function getDefaultMaxSections(mode) {
    switch (mode) {
        case 'compact': return 5;
        case 'full': return 10;
        case 'topic': return 6;
        default: return 5;
    }
}
function formatAge(dateStr) {
    const ms = Date.now() - new Date(dateStr).getTime();
    const hours = Math.round(ms / 3600000);
    if (hours < 1)
        return 'just now';
    if (hours < 24)
        return `${hours}h`;
    const days = Math.round(hours / 24);
    if (days < 7)
        return `${days}d`;
    const weeks = Math.round(days / 7);
    return `${weeks}w`;
}
//# sourceMappingURL=context-compression.js.map