"""Backfill SQLite memory index from existing ChromaDB data.

Usage:
    cd ~/projects/neo-cortex
    python -m scripts.backfill_index
"""

import sys
import time

from neo_cortex import config
from neo_cortex.memory_index import MemoryIndex
from neo_cortex.models import MemoryRecord, StructuredFields
from neo_cortex.store import MemoryStore


def main():
    print("=== Backfill Memory Index ===")

    # Open stores
    store = MemoryStore(config.CORTEX_DB_PATH, config.COLLECTION_NAME)
    index = MemoryIndex(config.MEMORY_INDEX_DB_PATH)

    existing = index.count()
    print(f"SQLite index: {existing} existing records")

    # Get all metadata from ChromaDB
    all_meta = store.get_all_metadata()
    print(f"ChromaDB: {len(all_meta)} memories to backfill")

    inserted = 0
    skipped = 0
    errors = 0

    for meta in all_meta:
        try:
            mid = meta.get("id", "")
            if not mid:
                skipped += 1
                continue

            # Check if already in index
            if index.get_by_id(mid) is not None:
                skipped += 1
                continue

            record = MemoryRecord(
                id=mid,
                session_id=meta.get("session_id", "unknown"),
                timestamp=meta.get("timestamp", time.time()),
                turn_number=int(meta.get("turn_number", 0)),
                question=meta.get("question", ""),
                answer_preview=meta.get("answer_preview", ""),
                document=meta.get("document", ""),
                project=meta.get("project", "general"),
                topic=meta.get("topic", "unknown"),
                activity=meta.get("activity", "discussion"),
                energy=float(meta.get("energy", 1.0)),
                model=meta.get("model", "opus"),
                source=meta.get("source", "neo-cortex"),
            )

            # No structured fields for old memories
            index.insert(record)
            inserted += 1

        except Exception as e:
            errors += 1
            print(f"  Error on {meta.get('id', '?')}: {e}")

    total = index.count()
    print(f"\nDone: {inserted} inserted, {skipped} skipped, {errors} errors")
    print(f"Total in index: {total}")


if __name__ == "__main__":
    main()
