
import json
import os
import sys
from pathlib import Path

# Add core to path
sys.path.append("e:/genesis-system/core")
sys.path.append("e:/genesis-system/data/genesis-memory")

from storage.postgresql_store import PostgreSQLStore
from elestio_config import PostgresConfig

def migrate():
    print("🚀 Starting Final Entity Migration to PostgreSQL...")
    pg = PostgreSQLStore(**PostgresConfig.get_connection_params())
    
    entities_path = "e:/genesis-system/KNOWLEDGE_GRAPH/entities.jsonl"
    count = 0
    
    with open(entities_path, "r") as f:
        for line in f:
            if not line.strip(): continue
            entity = json.loads(line)
            
            # Extract basic data
            name = entity.get("id") or entity.get("name")
            e_type = entity.get("type") or "observation"
            props = {k: v for k, v in entity.items() if k not in ["id", "type", "name"]}
            
            # Store in PG
            pg.store_entity(
                name=name,
                entity_type=e_type,
                properties=props,
                importance=0.7
            )
            count += 1
            if count % 20 == 0:
                print(f"  Migration: {count} entities processed...")

    print(f"✅ MIGRATION COMPLETE: {count} entities pushed to Elestio PostgreSQL.")
    
    # Verify count via PG stats
    stats = pg.get_stats()
    print(f"📊 PostgreSQL Multi-Tier Stats: {json.dumps(stats, indent=2)}")

if __name__ == "__main__":
    migrate()
