"""
The Holocron: Keeper of Golden Rules
====================================
Stores and retrieves the distilled wisdom (Golden Rules) generated by the
Great Work transmutation pipeline.

Usage:
    holocron = Holocron()
    holocron.load()
    rules = holocron.get_relevant_rules("context")
"""

import json
from pathlib import Path
from typing import List, Dict, Any
import logging

logger = logging.getLogger(__name__)

class Holocron:
    """The Holocron stores Golden Rules."""

    from whitemagic.config.paths import WM_ROOT
    DEFAULT_PATH = WM_ROOT / "wisdom" / "holocron.json"

    def __init__(self, path: Path = None):
        self.path = path or self.DEFAULT_PATH
        self.rules: List[Dict[str, Any]] = []
        self.version = "1.0.0"

    def save(self, rules: List[Dict[str, Any]]):
        """Save rules to the Holocron."""
        self.path.parent.mkdir(parents=True, exist_ok=True)
        data = {
            "version": self.version,
            "count": len(rules),
            "rules": rules
        }
        with open(self.path, "w") as f:
            json.dump(data, f, indent=2)
        logger.info(f"Holocron saved with {len(rules)} rules to {self.path}")

    def load(self):
        """Load rules from the Holocron."""
        if not self.path.exists():
            logger.warning(f"Holocron not found at {self.path}")
            return

        try:
            with open(self.path, "r") as f:
                data = json.load(f)
            self.rules = data.get("rules", [])
            logger.info(f"Holocron loaded with {len(self.rules)} rules")
        except Exception as e:
            logger.error(f"Failed to load Holocron: {e}")

    def get_all_rules(self) -> List[Dict[str, Any]]:
        return self.rules

    def get_relevant_rules(self, context: str, limit: int = 5) -> List[Dict[str, Any]]:
        """
        Retrieve relevant rules based on context.
        Currently simple keyword match; could use embeddings later.
        """
        if not self.rules:
            return []

        # Simple scoring based on word overlap
        context_words = set(context.lower().split())
        scored = []
        for rule in self.rules:
            title_words = set(rule.get("title", "").lower().split())
            score = len(context_words.intersection(title_words))
            scored.append((score, rule))

        scored.sort(key=lambda x: x[0], reverse=True)
        return [r for s, r in scored[:limit] if s > 0]
