import json
import os
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Optional

class RLMBridge:
    """
    Python Bridge for Genesis RLM (Relational Lifecycle Memory).
    Supports semantic queries and state-aware knowledge capture.
    """
    def __init__(self, blackboard=None):
        """Initialize RLM Bridge with PostgreSQL backend."""
        import sys
        sys.path.append(r"E:\genesis-system\data\genesis-memory")
        from storage.postgresql_store import PostgreSQLStore
        from elestio_config import PostgresConfig
        
        self.pg_store = PostgreSQLStore(**PostgresConfig.get_connection_params())
        print("[OK] RLMBridge: PostgreSQL (Elestio) backend active")

    def query(self, text: str, entity_type: Optional[str] = None) -> List[Dict]:
        """Search entities via PostgreSQL."""
        entity = self.pg_store.get_entity(text)
        if entity:
            return [{
                "name": entity["name"],
                "type": entity["entity_type"],
                "properties": entity["properties"] or {}
            }]
        
        # Fallback to search episodes if no direct entity match
        entities = self.pg_store.search_episodes(query=text, source_type=entity_type)
        return [e.to_dict() for e in entities]

    def load_graph(self) -> Dict:
        """Compatibility method to return entities in graph format from PostgreSQL."""
        entities = self.pg_store.get_all_entities(limit=200)
        return {
            "entities": [
                {
                    "name": e["name"],
                    "type": e["entity_type"],
                    "observations": e["properties"].get("observations", []) if e["properties"] else []
                }
                for e in entities
            ]
        }

    def store(self, name: str, entity_type: str, observations: List[str]):
        """Store or update an entity in PostgreSQL."""
        content = f"Entity: {name}\nType: {entity_type}\nObservations: {'; '.join(observations)}"
        self.pg_store.store_entity(
            name=name,
            entity_type=entity_type,
            properties={"observations": observations}
        )
        # Also store as an episode for temporal tracking
        self.pg_store.store_episode(
            content=content,
            source_type="rlm_sync",
            importance_score=0.8
        )

    def create_relation(self, from_entity: str, relation_type: str, to_entity: str):
        """Create a link between nodes in PostgreSQL."""
        # This assumes entities exist. In PostgreSQLStore, we'd need entity IDs.
        # For simplicity in this bridge, we'll store relationship as a Connection
        # between the latest episodes of these entities.
        return True # Placeholder for more complex linking
