"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateEnrichedSummary = generateEnrichedSummary;
exports.saveEnrichedSummary = saveEnrichedSummary;
exports.getEnrichedSummaries = getEnrichedSummaries;
const database_1 = require("../database/database");
const ai_bridge_1 = require("../../03-knowledge/decisions/ai-bridge");
function generateEnrichedSummary(project, period = 'daily') {
    const db = (0, database_1.getDb)();
    const now = new Date();
    const dateStr = now.toISOString().slice(0, 10);
    const days = period === 'weekly' ? 7 : 1;
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const events = db.prepare(`
    SELECT type, summary, importance, topic, created_at
    FROM memory_events
    WHERE project = ? AND created_at >= ?
    ORDER BY importance DESC, created_at DESC
  `).all(project, since);
    const totalEvents = events.length;
    const avgImportance = totalEvents > 0
        ? Math.round(events.reduce((s, e) => s + e.importance, 0) / totalEvents * 10) / 10
        : 0;
    // Collect topics
    const topicMap = new Map();
    for (const e of events) {
        if (e.topic)
            topicMap.set(e.topic, (topicMap.get(e.topic) || 0) + 1);
    }
    const topTopics = [...topicMap.entries()]
        .sort((a, b) => b[1] - a[1])
        .slice(0, 5)
        .map(([t]) => t);
    // Collect decisions
    const keyDecisions = events
        .filter(e => e.type === 'decision')
        .slice(0, 5)
        .map(e => e.summary);
    // Collect errors
    const errors = events
        .filter(e => e.type === 'error')
        .slice(0, 5)
        .map(e => e.summary);
    // By type
    const byType = {};
    for (const e of events)
        byType[e.type] = (byType[e.type] || 0) + 1;
    // Generate AI prompt
    const aiPrompt = buildSummaryPrompt(project, period, dateStr, events, topTopics, keyDecisions, errors);
    return {
        project,
        period,
        date: dateStr,
        totalEvents,
        avgImportance,
        topTopics,
        keyDecisions,
        errors,
        byType,
        aiPrompt,
        saved: false,
    };
}
function saveEnrichedSummary(summary) {
    const db = (0, database_1.getDb)();
    // Save to memory_summaries table
    db.prepare(`
    INSERT INTO memory_summaries (project, summary_type, period, content, event_count, date, total_events, avg_importance, top_topics, key_decisions, errors, by_type, ai_prompt)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(summary.project, `memory-${summary.period}`, summary.period, summary.aiPrompt, summary.totalEvents, summary.date, summary.totalEvents, summary.avgImportance, JSON.stringify(summary.topTopics), JSON.stringify(summary.keyDecisions), JSON.stringify(summary.errors), JSON.stringify(summary.byType), summary.aiPrompt);
    // Save AI insight via ai-bridge
    const insightContent = formatSummaryAsInsight(summary);
    (0, ai_bridge_1.saveAIInsight)(summary.project, `memory-summary-${summary.period}`, insightContent);
    summary.saved = true;
}
function getEnrichedSummaries(project, limit = 10) {
    const db = (0, database_1.getDb)();
    return db.prepare(`
    SELECT date, period, total_events as totalEvents, avg_importance as avgImportance
    FROM memory_summaries
    WHERE project = ?
    ORDER BY date DESC
    LIMIT ?
  `).all(project, limit);
}
function buildSummaryPrompt(project, period, date, events, topTopics, keyDecisions, errors) {
    const eventSample = events.slice(0, 30).map(e => `- [IMP:${e.importance}] ${e.type}: ${e.summary}${e.topic ? ` (topic: ${e.topic})` : ''}`).join('\n');
    return `Analyze this ${period} memory summary for project "${project}".

DATE: ${date}
TOTAL EVENTS: ${events.length}
TOP TOPICS: ${topTopics.join(', ') || 'none'}

KEY DECISIONS:
${keyDecisions.map(d => `- ${d}`).join('\n') || '- none'}

ERRORS:
${errors.map(e => `- ${e}`).join('\n') || '- none'}

EVENT SAMPLE (by importance):
${eventSample}

TASK:
1. Summarize what was accomplished this ${period}
2. Identify patterns in errors or decisions
3. Suggest focus areas for next ${period}
4. Rate overall productivity (1-10) with brief reasoning
5. List any risks or blockers detected

Answer in concise markdown. No code snippets.`;
}
function formatSummaryAsInsight(summary) {
    const lines = [
        `# ${summary.period.charAt(0).toUpperCase() + summary.period.slice(1)} Memory Summary`,
        `Generated: ${summary.date}`,
        `Project: ${summary.project}`,
        '',
        `## Stats`,
        `- Total events: ${summary.totalEvents}`,
        `- Avg importance: ${summary.avgImportance}`,
        `- Top topics: ${summary.topTopics.join(', ') || 'none'}`,
        '',
    ];
    if (summary.keyDecisions.length > 0) {
        lines.push('## Key Decisions');
        for (const d of summary.keyDecisions)
            lines.push(`- ${d}`);
        lines.push('');
    }
    if (summary.errors.length > 0) {
        lines.push('## Errors');
        for (const e of summary.errors)
            lines.push(`- ${e}`);
        lines.push('');
    }
    if (Object.keys(summary.byType).length > 0) {
        lines.push('## By Type');
        for (const [type, count] of Object.entries(summary.byType).sort((a, b) => b[1] - a[1])) {
            lines.push(`- ${type}: ${count}`);
        }
    }
    return lines.join('\n');
}
//# sourceMappingURL=ai-memory-summarizer.js.map