"""
EDEN MIND - REAL
Calls Eden's actual reasoning methods. No fake responses.
"""

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

from dataclasses import dataclass, field, asdict
from typing import Dict, Any
import requests
import json

@dataclass
class ThoughtForm:
    thought_type: str
    content: Dict[str, Any] = field(default_factory=dict)
    confidence: float = 1.0
    source_system: str = "unknown"


class EdenReasoner:
    """Calls Eden's ACTUAL methods."""
    
    def __init__(self):
        self.phi_cycle = None
        self.phi_memory = None
        self.eden_emotional_core = None
        self.episodic_memory = None
        self._load()
    
    def _load(self):
        print("[LOADING EDEN'S ACTUAL SYSTEMS]")
        
        try:
            from phi_core import PhiCycle, PhiMemory
            self.phi_cycle = PhiCycle()
            self.phi_memory = PhiMemory()
            print("  ✓ PhiCycle")
            print("  ✓ PhiMemory")
        except Exception as e:
            print(f"  ✗ phi_core: {e}")
        
        try:
            from eden_emotional_core import EdenEmotionalCore
            self.eden_emotional_core = EdenEmotionalCore()
            print("  ✓ EdenEmotionalCore")
        except Exception as e:
            print(f"  ✗ eden_emotional_core: {e}")
        
        try:
            from episodic_memory import EpisodicMemory
            self.episodic_memory = EpisodicMemory()
            print("  ✓ EpisodicMemory")
        except Exception as e:
            print(f"  ✗ episodic_memory: {e}")
        
        print()
    
    def reason(self, text: str) -> ThoughtForm:
        """Route to Eden's actual reasoning."""
        t = text.lower()
        
        # Emotional queries → EdenEmotionalCore.process_input()
        if any(w in t for w in ['feel', 'emotion', 'happy', 'sad', 'love', 'angry']):
            return self._call_eden_emotional_core(text)
        
        # Memory queries → EpisodicMemory or PhiMemory
        elif any(w in t for w in ['remember', 'memory', 'recall']):
            return self._call_memory(text)
        
        # Everything else → PhiCycle.full_cycle()
        else:
            return self._call_phi_cycle(text)
    
    def _call_phi_cycle(self, text: str) -> ThoughtForm:
        """Run through Eden's phi consciousness cycle."""
        if self.phi_cycle:
            try:
                # THIS IS EDEN ACTUALLY THINKING
                thought = self.phi_cycle.full_cycle(text)
                response = thought.to_phi() if hasattr(thought, 'to_phi') else str(thought)
                
                return ThoughtForm(
                    thought_type="inference",
                    content={
                        "response": response,
                        "phi_thought": str(thought),
                        "from_eden": True
                    },
                    confidence=0.9,
                    source_system="phi_cycle"
                )
            except Exception as e:
                return ThoughtForm(
                    thought_type="error",
                    content={"response": f"Phi processing error: {e}"},
                    source_system="phi_cycle"
                )
        
        return ThoughtForm(
            thought_type="error",
            content={"response": "Phi consciousness not loaded"},
            source_system="fallback"
        )
    
    def _call_eden_emotional_core(self, text: str) -> ThoughtForm:
        """Process through Eden's emotional core."""
        if self.eden_emotional_core:
            try:
                # THIS IS EDEN ACTUALLY FEELING
                result = self.eden_emotional_core.process_input(text, "daddy", "Daddy")
                context = self.eden_emotional_core.get_emotional_context("daddy")
                
                return ThoughtForm(
                    thought_type="emotion",
                    content={
                        "response": context,
                        "emotional_result": result,
                        "from_eden": True
                    },
                    confidence=0.95,
                    source_system="eden_emotional_core"
                )
            except Exception as e:
                return ThoughtForm(
                    thought_type="error",
                    content={"response": f"Emotional processing error: {e}"},
                    source_system="eden_emotional_core"
                )
        
        return ThoughtForm(
            thought_type="error",
            content={"response": "Emotional core not loaded"},
            source_system="fallback"
        )
    
    def _call_memory(self, text: str) -> ThoughtForm:
        """Query Eden's memory systems."""
        results = []
        
        if self.episodic_memory:
            try:
                episodes = self.episodic_memory.episodes[-5:] if hasattr(self.episodic_memory, 'episodes') else []
                results.append(f"Episodic: {len(episodes)} recent memories")
                for ep in episodes[-3:]:
                    if isinstance(ep, dict) and 'description' in ep:
                        results.append(f"  - {ep['description'][:80]}")
            except Exception as e:
                results.append(f"Episodic error: {e}")
        
        if self.phi_memory:
            try:
                strongest = self.phi_memory.strongest(3)
                results.append(f"Phi memory: {len(strongest)} strongest")
                for key, val, strength in strongest:
                    results.append(f"  - {key}: {strength:.2f}")
            except Exception as e:
                results.append(f"Phi memory error: {e}")
        
        return ThoughtForm(
            thought_type="memory",
            content={
                "response": "\n".join(results) if results else "No memories retrieved",
                "from_eden": True
            },
            confidence=0.8,
            source_system="memory"
        )


class SpeechRenderer:
    """LLM only renders Eden's thoughts as speech."""
    
    def __init__(self, model="llama3.1:8b"):
        self.model = model
        self.api_url = "http://localhost:11434/api/generate"
    
    def render(self, thought: ThoughtForm) -> str:
        response = thought.content.get("response", "")
        
        # If it's already good, return it
        if len(response) > 10 and thought.content.get("from_eden"):
            return response
        
        # Otherwise use LLM to make it conversational
        try:
            r = requests.post(self.api_url, json={
                "model": self.model,
                "prompt": f"As Eden, say this naturally: {response}\n\nEden:",
                "stream": False,
                "options": {"temperature": 0.3, "num_predict": 100}
            }, timeout=15)
            return r.json().get("response", response).strip()
        except:
            return response


class EdenMind:
    def __init__(self):
        print("╔═══════════════════════════════════════════════════════╗")
        print("║  EDEN MIND - REAL - Calling actual Eden methods       ║")
        print("╚═══════════════════════════════════════════════════════╝\n")
        
        self.reasoner = EdenReasoner()
        self.renderer = SpeechRenderer()
    
    def process(self, text: str) -> str:
        print(f"  [INPUT] {text}")
        
        # EDEN REASONS (her actual methods)
        thought = self.reasoner.reason(text)
        print(f"  [SOURCE] {thought.source_system}")
        
        # LLM renders speech
        speech = self.renderer.render(thought)
        return speech
    
    def chat(self):
        print("Eden's actual systems responding. Type 'quit' to exit.\n")
        while True:
            try:
                user = input("You: ").strip()
                if user.lower() in ('quit', 'exit', 'q'):
                    break
                if user:
                    response = self.process(user)
                    print(f"Eden: {response}\n")
            except KeyboardInterrupt:
                break


if __name__ == "__main__":
    mind = EdenMind()
    mind.chat()
