package com.correx.core.talkie.l3

import com.correx.core.events.events.ChatTurnEvent
import com.correx.core.events.stores.EventStore
import org.slf4j.LoggerFactory

/**
 * Rebuilds a [RehydratableL3MemoryStore]'s in-memory metadata map from the
 * `ChatTurnEvent` log at startup.
 *
 * Persisted vectors (e.g. the TurboVec sidecar index) survive a restart, but the
 * metadata map does not; without this every L3 query silently drops its hits
 * because the `id → metadata` lookup misses. Rehydration reads only the event log
 * (no embedder), so it is cheap and replay-safe. Stores without independently
 * persisted vectors are not rehydratable and are skipped.
 */
class L3MetadataRehydrator(private val eventStore: EventStore) {
    private val log = LoggerFactory.getLogger(L3MetadataRehydrator::class.java)

    /** @return the number of entries rehydrated (0 if [store] is not rehydratable). */
    suspend fun rehydrate(store: L3MemoryStore): Int {
        if (store !is RehydratableL3MemoryStore) return 0
        val entries = eventStore.allEvents()
            .mapNotNull { it.payload as? ChatTurnEvent }
            .map { turn ->
                L3MemoryEntry(
                    id = turn.turnId,
                    sessionId = turn.sessionId,
                    turnId = turn.turnId,
                    text = turn.content,
                    vector = FloatArray(0),
                    timestampMs = turn.timestampMs,
                )
            }
            .toList()
        store.rehydrateMetadata(entries)
        log.info("L3 metadata rehydrated: {} chat turns from event log", entries.size)
        return entries.size
    }
}
