"""
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 files.

        If path is None, loads from both the flat file and the entities/ directory.
        If path is a directory, loads all .jsonl files in it.
        If path is a file, loads just that file.
        """
        kg_root = Path(__file__).parent.parent.parent / "KNOWLEDGE_GRAPH"
        self.entities = []
        files_loaded = 0

        if path is None:
            # Load from flat file if it exists
            flat_file = kg_root / "entities.jsonl"
            if flat_file.exists():
                files_loaded += self._load_file(flat_file)
            # Load all JSONL files from entities/ directory
            entities_dir = kg_root / "entities"
            if entities_dir.is_dir():
                for jsonl_file in sorted(entities_dir.glob("*.jsonl")):
                    files_loaded += self._load_file(jsonl_file)
        else:
            target = Path(path)
            if target.is_dir():
                for jsonl_file in sorted(target.glob("*.jsonl")):
                    files_loaded += self._load_file(jsonl_file)
            elif target.exists():
                files_loaded += self._load_file(target)
            else:
                logger.warning(f"KG path not found: {path}")
                return

        self._loaded = True
        logger.info(f"Loaded {len(self.entities)} entities from {files_loaded} files")

    def _load_file(self, filepath: Path) -> int:
        """Load entities from a single JSONL file. Returns 1 on success, 0 on failure."""
        try:
            with open(filepath, "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
            return 1
        except OSError as e:
            logger.warning(f"Failed to read {filepath}: {e}")
            return 0
    
    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, Any]:
        """Get KG statistics."""
        if not self._loaded:
            self.load()
        categories = {}
        for e in self.entities:
            cat = e.get("category", e.get("type", "unknown"))
            categories[cat] = categories.get(cat, 0) + 1
        return {"entities": len(self.entities), "categories": categories}


def create_adapter(path: Optional[str] = None) -> KGAdapter:
    """Create and load a KG adapter."""
    adapter = KGAdapter()
    adapter.load(path)
    return adapter
