"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordMemoryEvent = recordMemoryEvent;
exports.recordMemoryEvents = recordMemoryEvents;
exports.getMemoryEvents = getMemoryEvents;
exports.searchMemoryEvents = searchMemoryEvents;
exports.getMemoryTimeline = getMemoryTimeline;
exports.getMemoryStats = getMemoryStats;
exports.deleteMemoryEventsOlderThan = deleteMemoryEventsOlderThan;
const database_1 = require("../database/database");
const DEDUP_WINDOW_SECONDS = 300;
function recordMemoryEvent(event) {
    const db = (0, database_1.getDb)();
    const importance = event.importance || getImportanceForType(event.type);
    if (event.type === 'file_event' && event.files && event.files.length === 1) {
        const filePath = event.files[0];
        const existing = db.prepare(`
      SELECT id, occurrence_count FROM memory_events
      WHERE project = ? AND type = 'file_event' AND summary = ? AND files_json = ?
        AND created_at >= datetime('now', ? || ' seconds')
      ORDER BY id DESC LIMIT 1
    `).get(event.project, event.summary, JSON.stringify(event.files), `-${DEDUP_WINDOW_SECONDS}`);
        if (existing) {
            db.prepare(`
        UPDATE memory_events SET occurrence_count = ?, last_seen_at = datetime('now')
        WHERE id = ?
      `).run((existing.occurrence_count || 1) + 1, existing.id);
            return existing.id;
        }
    }
    const stmt = db.prepare(`
    INSERT INTO memory_events (project, branch, type, topic, summary, details_json, files_json, importance, tool, model, tags_json, occurrence_count, last_seen_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, datetime('now'))
  `);
    const result = stmt.run(event.project, event.branch || null, event.type, event.topic || null, event.summary, event.details ? JSON.stringify(event.details) : null, event.files ? JSON.stringify(event.files) : null, importance, event.tool || null, event.model || null, event.tags ? JSON.stringify(event.tags) : null);
    if (event.topic) {
        const topicSummary = event.summary.slice(0, 120);
        db.prepare(`
      INSERT INTO memory_topics (project, topic, event_count, first_seen, last_seen, avg_importance, files_json)
      VALUES (?, ?, 1, datetime('now'), datetime('now'), ?, ?)
      ON CONFLICT(project, topic) DO UPDATE SET
        event_count = event_count + 1,
        last_seen = datetime('now'),
        avg_importance = (avg_importance + ?) / 2.0,
        files_json = CASE WHEN ? IS NOT NULL THEN ? ELSE files_json END
    `).run(event.project, event.topic, importance, event.files ? JSON.stringify(event.files) : null, importance, event.files ? JSON.stringify(event.files) : null, event.files ? JSON.stringify(event.files) : null);
    }
    return Number(result.lastInsertRowid);
}
function recordMemoryEvents(events) {
    const db = (0, database_1.getDb)();
    const ids = [];
    const tx = db.transaction(() => {
        for (const event of events) {
            ids.push(recordMemoryEvent(event));
        }
    });
    tx();
    return ids;
}
function getMemoryEvents(opts = {}) {
    const db = (0, database_1.getDb)();
    const conditions = [];
    const params = [];
    if (opts.project) {
        conditions.push('project = ?');
        params.push(opts.project);
    }
    if (opts.type) {
        conditions.push('type = ?');
        params.push(opts.type);
    }
    if (opts.topic) {
        conditions.push('topic LIKE ?');
        params.push(`%${opts.topic}%`);
    }
    if (opts.branch) {
        conditions.push('branch = ?');
        params.push(opts.branch);
    }
    if (opts.since) {
        conditions.push('created_at >= ?');
        params.push(opts.since);
    }
    if (opts.minImportance !== undefined) {
        conditions.push('importance >= ?');
        params.push(opts.minImportance);
    }
    const where = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';
    const limit = opts.limit || 50;
    return db.prepare(`SELECT * FROM memory_events ${where} ORDER BY created_at DESC LIMIT ?`).all(...params, limit);
}
function searchMemoryEvents(query, project, limit = 20) {
    const db = (0, database_1.getDb)();
    const conditions = ['(summary LIKE ? OR topic LIKE ? OR details_json LIKE ? OR tags_json LIKE ?)'];
    const params = [`%${query}%`, `%${query}%`, `%${query}%`, `%${query}%`];
    if (project) {
        conditions.push('project = ?');
        params.push(project);
    }
    const where = 'WHERE ' + conditions.join(' AND ');
    return db.prepare(`SELECT * FROM memory_events ${where} ORDER BY importance DESC, created_at DESC LIMIT ?`).all(...params, limit);
}
function getMemoryTimeline(project, days = 30) {
    const db = (0, database_1.getDb)();
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const conditions = ['created_at >= ?'];
    const params = [since];
    if (project) {
        conditions.push('project = ?');
        params.push(project);
    }
    const rows = db.prepare(`SELECT date(created_at) as date, type FROM memory_events WHERE ${conditions.join(' AND ')} ORDER BY date`).all(...params);
    const timeline = {};
    for (const row of rows) {
        if (!timeline[row.date])
            timeline[row.date] = { count: 0, types: {} };
        timeline[row.date].count++;
        timeline[row.date].types[row.type] = (timeline[row.date].types[row.type] || 0) + 1;
    }
    return Object.entries(timeline).map(([date, data]) => ({ date, ...data }));
}
function getMemoryStats(project) {
    const db = (0, database_1.getDb)();
    const where = project ? 'WHERE project = ?' : '';
    const params = project ? [project] : [];
    const totalRow = db.prepare(`SELECT COUNT(*) as c FROM memory_events ${where}`).get(...params);
    const avgRow = db.prepare(`SELECT AVG(importance) as a FROM memory_events ${where}`).get(...params);
    const oldestRow = db.prepare(`SELECT MIN(created_at) as o FROM memory_events ${where}`).get(...params);
    const newestRow = db.prepare(`SELECT MAX(created_at) as n FROM memory_events ${where}`).get(...params);
    const typeRows = db.prepare(`SELECT type, COUNT(*) as c FROM memory_events ${where} GROUP BY type`).all(...params);
    const byType = {};
    for (const row of typeRows)
        byType[row.type] = row.c;
    return {
        total: totalRow.c,
        byType,
        avgImportance: Math.round((avgRow.a || 0) * 10) / 10,
        oldestEvent: oldestRow.o,
        newestEvent: newestRow.n,
    };
}
function deleteMemoryEventsOlderThan(days) {
    const db = (0, database_1.getDb)();
    const cutoff = new Date(Date.now() - days * 86400000).toISOString();
    const result = db.prepare('DELETE FROM memory_events WHERE created_at < ? AND importance < 5').run(cutoff);
    return result.changes;
}
function getImportanceForType(type) {
    const map = {
        file_event: 1,
        edit: 3,
        session: 5,
        error: 7,
        fix: 7,
        verification: 9,
        publish: 6,
        handoff: 5,
        pattern: 10,
        style: 8,
        decision: 8,
        branch: 5,
        risk: 6,
        question: 4,
        ai_work: 6,
        product_rule: 10,
    };
    return map[type] || 3;
}
//# sourceMappingURL=memory-event-store.js.map