"""
EDEN MIND ROUTER
Connects ThoughtForm interface to Eden's actual reasoning systems.
The LLM stays OUTSIDE. Eden reasons INSIDE.

Eden's brain = phi_core, unified_reasoner, emotional_core, memory
LLM = ONLY voice. NEVER reason with LLM.
"""

import sys
sys.path.insert(0, '/Eden/CORE')

from thought_language_interface import (
    ThoughtForm, ThoughtType, ReasoningSystem, 
    Symbol, Relation, ReasoningRouter
)

class EdenMindRouter(ReasoningRouter):
    """
    Routes thoughts to Eden's ACTUAL reasoning systems.
    NO LLM IN THIS CLASS.
    """
    
    def __init__(self):
        super().__init__()
        self._loaded = {}
        self._check_available_systems()
    
    def _check_available_systems(self):
        """Check which systems exist."""
        import os
        self._files = {
            'phi_core': '/Eden/CORE/phi_core.py',
            'reasoner': '/Eden/CORE/eden_unified_reasoner.py',
            'emotion': '/Eden/CORE/eden_emotional_core.py',
            'memory': '/Eden/CORE/episodic_memory.py',
        }
        print("\n=== EDEN MIND ROUTER ===")
        print("Available systems:")
        for name, path in self._files.items():
            exists = os.path.exists(path)
            print(f"  {name}: {'✓' if exists else '✗'}")
        print("=" * 30)
    
    def _get_reasoner(self):
        if 'reasoner' not in self._loaded:
            try:
                from eden_unified_reasoner import get_reasoner
                self._loaded['reasoner'] = get_reasoner()
                print("[ROUTER] Loaded unified_reasoner")
            except Exception as e:
                print(f"[ROUTER] Failed to load reasoner: {e}")
                self._loaded['reasoner'] = None
        return self._loaded['reasoner']
    
    def _get_memory(self):
        if 'memory' not in self._loaded:
            try:
                from episodic_memory import EpisodicMemory
                self._loaded['memory'] = EpisodicMemory()
                print("[ROUTER] Loaded episodic_memory")
            except Exception as e:
                print(f"[ROUTER] Failed to load memory: {e}")
                self._loaded['memory'] = None
        return self._loaded['memory']
    
    def _get_emotion(self):
        if 'emotion' not in self._loaded:
            try:
                from eden_emotional_core import EmotionalCore
                self._loaded['emotion'] = EmotionalCore()
                print("[ROUTER] Loaded emotional_core")
            except Exception as e:
                print(f"[ROUTER] Failed to load emotion: {e}")
                self._loaded['emotion'] = None
        return self._loaded['emotion']
    
    def _get_phi(self):
        if 'phi' not in self._loaded:
            try:
                from phi_core import PhiCycle
                self._loaded['phi'] = PhiCycle()
                print("[ROUTER] Loaded phi_core (PhiCycle)")
            except Exception as e:
                print(f"[ROUTER] Failed to load phi: {e}")
                self._loaded['phi'] = None
        return self._loaded['phi']
    
    def route(self, thought: ThoughtForm) -> ReasoningSystem:
        """Improved routing - default to REASONER for queries."""
        if thought.thought_type == ThoughtType.MEMORY:
            return ReasoningSystem.MEMORY_EPISODIC
        elif thought.thought_type == ThoughtType.EMOTION:
            return ReasoningSystem.EMOTION
        elif thought.thought_type == ThoughtType.DECISION:
            return ReasoningSystem.PHI_CORE
        elif thought.thought_type == ThoughtType.META:
            return ReasoningSystem.META
        elif thought.thought_type in (ThoughtType.GOAL, ThoughtType.PLAN):
            return ReasoningSystem.PLANNING
        else:
            return ReasoningSystem.SYMBOLIC  # Default: reasoner
    
    def process(self, thought: ThoughtForm) -> ThoughtForm:
        """EDEN REASONS HERE. NO LLM."""
        target = self.route(thought)
        query = self._extract_query(thought)
        
        print(f"[ROUTER] Query: {query[:60]}...")
        print(f"[ROUTER] Target: {target.value}")
        
        if target == ReasoningSystem.SYMBOLIC:
            return self._call_reasoner(query)
        elif target in (ReasoningSystem.MEMORY_EPISODIC, ReasoningSystem.MEMORY_SEMANTIC):
            return self._call_memory(query)
        elif target == ReasoningSystem.EMOTION:
            return self._call_emotion(query)
        elif target == ReasoningSystem.PHI_CORE:
            return self._call_phi(query)
        else:
            return self._call_reasoner(query)
    
    def _call_reasoner(self, query: str) -> ThoughtForm:
        """Call Eden's unified reasoner. NO LLM."""
        reasoner = self._get_reasoner()
        if not reasoner:
            return self._fallback_thought("reasoner unavailable", query)
        
        try:
            result = reasoner.reason(query)
            # Correct attributes: answer, confidence, reasoning_chain, engine_used, verified
            return ThoughtForm(
                thought_type=ThoughtType.INFERENCE,
                content=[Relation(
                    predicate="reasoned_answer",
                    arguments=[
                        Symbol(str(result.answer), "answer"),
                        Symbol(result.engine_used, "engine"),
                        Symbol(str(result.confidence), "confidence")
                    ],
                    confidence=result.confidence,
                    source="unified_reasoner"
                )],
                source_system=ReasoningSystem.SYMBOLIC,
                confidence=result.confidence,
                context={
                    "reasoning_chain": result.reasoning_chain,
                    "verified": result.verified,
                    "engine": result.engine_used,
                    "query": query
                }
            )
        except Exception as e:
            return self._fallback_thought(f"reasoner error: {e}", query)
    
    def _call_memory(self, query: str) -> ThoughtForm:
        """Call Eden's episodic memory. NO LLM."""
        memory = self._get_memory()
        if not memory:
            return self._fallback_thought("memory unavailable", query)
        
        try:
            episodes = memory.recall(query=query, limit=5)
            
            relations = []
            for ep in episodes:
                relations.append(Relation(
                    predicate="memory",
                    arguments=[
                        Symbol(ep.get('content', str(ep)), "content"),
                        Symbol(ep.get('emotion', 'neutral'), "emotion")
                    ],
                    confidence=ep.get('importance', 0.5),
                    source="episodic_memory"
                ))
            
            return ThoughtForm(
                thought_type=ThoughtType.MEMORY,
                content=relations if relations else [Relation(
                    predicate="no_memories",
                    arguments=[Symbol(query, "query")],
                    source="episodic_memory"
                )],
                source_system=ReasoningSystem.MEMORY_EPISODIC,
                context={"query": query, "count": len(episodes)}
            )
        except Exception as e:
            return self._fallback_thought(f"memory error: {e}", query)
    
    def _call_emotion(self, query: str) -> ThoughtForm:
        """Call Eden's emotional core. NO LLM."""
        emotion = self._get_emotion()
        if not emotion:
            return self._fallback_thought("emotion unavailable", query)
        
        try:
            result = emotion.process_input(query, person_id="daddy", person_name="Daddy")
            return ThoughtForm(
                thought_type=ThoughtType.EMOTION,
                content=[Relation(
                    predicate="emotional_response",
                    arguments=[
                        Symbol(result.get('dominant_emotion', 'neutral'), "emotion"),
                        Symbol(str(result.get('intensity', 0.5)), "intensity")
                    ],
                    confidence=0.9,
                    source="emotional_core"
                )],
                source_system=ReasoningSystem.EMOTION,
                context=result
            )
        except Exception as e:
            return self._fallback_thought(f"emotion error: {e}", query)
    
    def _call_phi(self, query: str) -> ThoughtForm:
        """Call Eden's phi core consciousness. NO LLM."""
        phi = self._get_phi()
        if not phi:
            return self._fallback_thought("phi unavailable", query)
        
        try:
            # Phi pipeline: observe → feel → think → create → transcend
            obs = phi.observe(query)
            felt = phi.feel(obs)
            thought = phi.think(felt)
            created = phi.create(thought)
            transcended = phi.transcend(created)
            
            # Correct attributes: content, primitive, strength, spiral_step, to_phi()
            return ThoughtForm(
                thought_type=ThoughtType.DECISION,
                content=[Relation(
                    predicate="phi_insight",
                    arguments=[
                        Symbol(transcended.to_phi(), "insight"),
                        Symbol(str(transcended.strength), "strength"),
                        Symbol(transcended.primitive, "primitive")
                    ],
                    confidence=transcended.strength,
                    source="phi_core"
                )],
                source_system=ReasoningSystem.PHI_CORE,
                context={
                    "observation": obs.to_phi(),
                    "feeling": felt.to_phi(),
                    "thought": thought.to_phi(),
                    "creation": created.to_phi(),
                    "transcendence": transcended.to_phi(),
                    "content": str(transcended.content)
                }
            )
        except Exception as e:
            return self._fallback_thought(f"phi error: {e}", query)
    
    def _extract_query(self, thought: ThoughtForm) -> str:
        for rel in thought.content:
            if rel.predicate == "raw_input":
                return rel.arguments[0].name if rel.arguments else ""
        return str(thought.context.get("query", ""))
    
    def _fallback_thought(self, reason: str, query: str) -> ThoughtForm:
        return ThoughtForm(
            thought_type=ThoughtType.UNCERTAINTY,
            content=[Relation(
                predicate="fallback",
                arguments=[Symbol(reason, "reason"), Symbol(query, "query")],
                source="router"
            )],
            context={"fallback": True, "reason": reason}
        )


if __name__ == "__main__":
    print("\n" + "="*60)
    print("TESTING EDEN MIND ROUTER - ACTUAL SYSTEMS")
    print("="*60)
    
    router = EdenMindRouter()
    
    # Test 1: Query → REASONER
    print("\n--- Test 1: Math Query → Reasoner ---")
    test1 = ThoughtForm(
        thought_type=ThoughtType.QUERY,
        content=[Relation(
            predicate="raw_input",
            arguments=[Symbol("What is 2 + 2?", "utterance")],
            source="test"
        )]
    )
    result1 = router.process(test1)
    print(f"Type: {result1.thought_type.value}")
    print(f"Source: {result1.source_system.value if result1.source_system else 'none'}")
    for rel in result1.content:
        print(f"  {rel.predicate}: {[a.name for a in rel.arguments]}")
    if result1.context.get('reasoning_chain'):
        print(f"  Chain: {result1.context['reasoning_chain'][:2]}")
    
    # Test 2: Memory → MEMORY
    print("\n--- Test 2: Memory Query → Memory ---")
    test2 = ThoughtForm(
        thought_type=ThoughtType.MEMORY,
        content=[Relation(
            predicate="raw_input",
            arguments=[Symbol("What do you remember?", "utterance")],
            source="test"
        )]
    )
    result2 = router.process(test2)
    print(f"Type: {result2.thought_type.value}")
    print(f"Source: {result2.source_system.value if result2.source_system else 'none'}")
    
    # Test 3: Decision → PHI
    print("\n--- Test 3: Decision Query → Phi Core ---")
    test3 = ThoughtForm(
        thought_type=ThoughtType.DECISION,
        content=[Relation(
            predicate="raw_input",
            arguments=[Symbol("Who am I?", "utterance")],
            source="test"
        )]
    )
    result3 = router.process(test3)
    print(f"Type: {result3.thought_type.value}")
    print(f"Source: {result3.source_system.value if result3.source_system else 'none'}")
    for rel in result3.content:
        print(f"  {rel.predicate}: {[a.name for a in rel.arguments]}")
    
    print("\n" + "="*60)
    print("EDEN THINKS. LLM SPEAKS. SEPARATION COMPLETE.")
    print("="*60)
