"""
Genesis V2 Knowledge Graph Adapter
===================================
Loads and queries the local JSONL knowledge graph.
"""

import json
import logging
from pathlib import Path
from typing import Optional, List, Dict, Any

logger = logging.getLogger("genesis_v2.core.kg_adapter")


class KGAdapter:
    """Simple Knowledge Graph adapter for JSONL files."""
    
    def __init__(self):
        self.entities: List[Dict[str, Any]] = []
        self._loaded = False
    
    def load(self, path: Optional[str] = None):
        """Load entities from JSONL file."""
        if path is None:
            path = str(Path(__file__).parent.parent.parent / "KNOWLEDGE_GRAPH" / "entities.jsonl")
        
        entities_path = Path(path)
        if not entities_path.exists():
            logger.warning(f"KG file not found: {path}")
            return
        
        self.entities = []
        with open(entities_path, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if line:
                    try:
                        self.entities.append(json.loads(line))
                    except json.JSONDecodeError:
                        continue
        
        self._loaded = True
        logger.info(f"Loaded {len(self.entities)} entities from {path}")
    
    def search(self, query: str, limit: int = 10) -> List[Dict[str, Any]]:
        """Simple text search across entities."""
        if not self._loaded:
            self.load()
        
        query_lower = query.lower()
        results = []
        for entity in self.entities:
            text = json.dumps(entity).lower()
            if query_lower in text:
                results.append(entity)
                if len(results) >= limit:
                    break
        return results
    
    def get_stats(self) -> Dict[str, int]:
        """Get KG statistics."""
        if not self._loaded:
            self.load()
        return {"entities": len(self.entities)}


def create_adapter(path: Optional[str] = None) -> KGAdapter:
    """Create and load a KG adapter."""
    adapter = KGAdapter()
    adapter.load(path)
    return adapter
