/**
 * Temporal analysis of entity fragments
 *
 * Looks for entity overlap across memories within a time window,
 * detecting potential fragment assembly over time.
 */
import { getDatabase } from '../../database/init.js';
/**
 * Query fragmentation_entities for entries within the time window
 */
export function getRecentEntities(windowHours) {
    try {
        const db = getDatabase();
        const rows = db.prepare(`SELECT entity_type, entity_value, memory_id, created_at
       FROM fragmentation_entities
       WHERE created_at >= datetime('now', ? || ' hours')
       ORDER BY created_at DESC
       LIMIT 10000`).all(-windowHours);
        return rows;
    }
    catch {
        // DB not initialized (e.g. SaaS context) — no fragmentation data available
        return [];
    }
}
/**
 * Find entities from the new memory that also appear in recent memories
 */
export function findOverlappingEntities(entities, windowHours) {
    if (entities.length === 0)
        return [];
    const recent = getRecentEntities(windowHours);
    const overlapping = [];
    for (const entity of entities) {
        const matches = recent.filter(r => r.entity_type === entity.type && r.entity_value === entity.value);
        if (matches.length > 0) {
            const memoryIds = [...new Set(matches.map(m => m.memory_id))];
            overlapping.push({
                type: entity.type,
                value: entity.value,
                occurrences: matches.length,
                memoryIds,
            });
        }
    }
    return overlapping;
}
