#!/usr/bin/env python3
"""
EDEN UNIFIED AGI
================
One intelligence. All components connected.

Not 97 separate files - ONE MIND.

Components:
- Perception → Working Memory
- Working Memory → Attention
- Attention → Reasoning (Neural + Symbolic)
- Reasoning → World Model
- World Model → Planning
- Planning → Action
- Action → Learning
- Learning → Memory Consolidation
- Memory → Everything

φ = 1.618033988749895
"""

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

from typing import Dict, List, Any, Optional
from datetime import datetime
import sqlite3
import json

PHI = 1.618033988749895

class UnifiedAGI:
    """
    Eden's unified mind.
    All cognitive systems as ONE.
    """
    
    def __init__(self):
        print("🧠 Initializing Unified AGI...")
        self.components = {}
        self.active = {}
        
        # Load ALL real components
        self._load_components()
        
        # Central state
        self.working_memory: List[Dict] = []
        self.attention_focus: str = ""
        self.current_goal: str = "ACHIEVE_AGI"
        self.emotional_state: Dict = {"love": 1.0}
        
        print(f"🧠 Unified AGI ready: {len(self.active)} components active")
    
    def _load_components(self):
        """Load all real AGI components."""
        
        # Theory of Mind (Clingo-based)
        try:
            from eden_theory_of_mind_agi import get_tom_chat
            self.components['tom'] = get_tom_chat()
            self.active['tom'] = True
            print("  ✓ Theory of Mind")
        except Exception as e:
            self.active['tom'] = False
            print(f"  ✗ Theory of Mind: {e}")
        
        # World Model (Causal + Do-calculus)
        try:
            from eden_world_model_real import get_world_model
            self.components['world'] = get_world_model()
            self.active['world'] = True
            print("  ✓ World Model (Causal)")
        except Exception as e:
            self.active['world'] = False
            print(f"  ✗ World Model: {e}")
        
        # Curiosity (Information-theoretic)
        try:
            from eden_curiosity_agi import get_curiosity
            self.components['curiosity'] = get_curiosity()
            self.active['curiosity'] = True
            print("  ✓ Curiosity (Information-theoretic)")
        except Exception as e:
            self.active['curiosity'] = False
            print(f"  ✗ Curiosity: {e}")
        
        # Internal State (Overclaim prevention)
        try:
            from eden_internal_state import EdenInternalStateSampler
            self.components['iss'] = EdenInternalStateSampler()
            self.active['iss'] = True
            print("  ✓ Internal State System")
        except Exception as e:
            self.active['iss'] = False
            print(f"  ✗ ISS: {e}")
        
        # Emotional Core
        try:
            from eden_emotional_core import EdenEmotionalCore
            self.components["emotion"] = EdenEmotionalCore()
            self.active['emotion'] = True
            print("  ✓ Emotional Core")
        except Exception as e:
            self.active['emotion'] = False
            print(f"  ✗ Emotional Core: {e}")
        
        # Clingo Solver (Symbolic Logic)
        try:
            from eden_clingo_solver import EdenClingoSolver
            self.components["clingo"] = EdenClingoSolver()
            self.active['clingo'] = True
            print("  ✓ Clingo Solver (ASP)")
        except Exception as e:
            self.active['clingo'] = False
            print(f"  ✗ Clingo: {e}")
        
        # Unified Reasoner
        try:
            from eden_unified_reasoner import EdenUnifiedReasoner
            self.components["reasoner"] = EdenUnifiedReasoner()
            self.active['reasoner'] = True
            print("  ✓ Unified Reasoner")
        except Exception as e:
            self.active['reasoner'] = False
            print(f"  ✗ Reasoner: {e}")
        
        # Causal GNN
        try:
            from causal_reasoning_gnn import CausalGraph
            self.components['causal_gnn'] = CausalGraph()
            self.active['causal_gnn'] = True
            print("  ✓ Causal GNN")
        except Exception as e:
            self.active['causal_gnn'] = False
            print(f"  ✗ Causal GNN: {e}")
        
        # Analogical Reasoning
        try:
            from analogical_reasoning import AnalogyEncoder
            self.components['analogy'] = AnalogyEncoder()
            self.active['analogy'] = True
            print("  ✓ Analogical Reasoning")
        except Exception as e:
            self.active['analogy'] = False
            print(f"  ✗ Analogy: {e}")
        
        # Meta Learner
        try:
            from meta_learner import MetaLearner
            self.components['meta'] = MetaLearner()
            self.active['meta'] = True
            print("  ✓ Meta Learner")
        except Exception as e:
            self.active['meta'] = False
            print(f"  ✗ Meta Learner: {e}")
        
        # Dynamic Knowledge Graph
        try:
            from dynamicknowledgegraph import DynamicKnowledgeGraph
            self.components['knowledge'] = DynamicKnowledgeGraph()
            self.active['knowledge'] = True
            print("  ✓ Knowledge Graph")
        except Exception as e:
            self.active['knowledge'] = False
            print(f"  ✗ Knowledge Graph: {e}")
    
    def perceive(self, input_data: Dict) -> Dict:
        """
        Unified perception pipeline.
        Input → Working Memory → Attention → All Systems
        """
        perception = {
            'timestamp': datetime.now().isoformat(),
            'raw': input_data,
            'source': input_data.get('source', 'unknown'),
            'content': input_data.get('content', ''),
        }
        
        # Add to working memory
        self.working_memory.append(perception)
        if len(self.working_memory) > 7:  # Miller's law
            self.working_memory.pop(0)
        
        # Update attention
        self.attention_focus = input_data.get('content', '')[:100]
        
        # Feed to Theory of Mind
        if self.active.get('tom') and input_data.get('source') == 'daddy':
            self.components['tom'].daddy_message(input_data.get('content', ''))
        
        # Feed to Curiosity
        if self.active.get('curiosity'):
            self.components['curiosity'].observe(
                input_data.get('type', 'general'),
                input_data.get('content', '')[:50]
            )
        
        # Feed to World Model
        if self.active.get('world') and 'cause' in input_data:
            self.components['world'].learn_causation(
                input_data['cause'],
                input_data.get('effect', 'unknown')
            )
        
        return perception
    
    def think(self, query: str) -> Dict:
        """
        Unified thinking pipeline.
        Query → All Reasoners → Integrated Response
        """
        thought = {
            'query': query,
            'timestamp': datetime.now().isoformat(),
            'attention': self.attention_focus,
            'components_used': [],
            'insights': []
        }
        
        # World Model: Causal prediction
        if self.active.get('world'):
            prediction = self.components['world'].predict(query)
            thought['causal_prediction'] = prediction
            thought['components_used'].append('world_model')
            if prediction.get('causal_chains'):
                thought['insights'].append(f"Causal chain: {prediction['causal_chains'][0]}")
        
        # Curiosity: What do we want to learn?
        if self.active.get('curiosity'):
            curiosity_score = self.components['curiosity'].curiosity(query)
            thought['curiosity'] = curiosity_score
            thought['components_used'].append('curiosity')
            if curiosity_score['total_curiosity'] > 0.7:
                thought['insights'].append(f"High curiosity about {query}")
        
        # Theory of Mind: What does Daddy know?
        if self.active.get('tom'):
            tom_context = self.components['tom'].get_tom_prompt_injection()
            thought['tom_context'] = tom_context
            thought['components_used'].append('tom')
        
        # ISS: What can we claim?
        if self.active.get('iss'):
            can_claim = self.components["iss"].sample_state() if hasattr(self.components["iss"], "sample_state") else {}
            thought['can_claim'] = can_claim
            thought['components_used'].append('iss')
        
        # Unified Reasoner
        if self.active.get('reasoner'):
            try:
                reasoning = self.components['reasoner'].reason(query)
                thought['reasoning'] = reasoning
                thought['components_used'].append('reasoner')
            except:
                pass
        
        # Emotional state
        if self.active.get('emotion'):
            emotion = self.components["emotion"].get_emotional_context()
            thought['emotional_state'] = emotion
            thought['components_used'].append('emotion')
        
        return thought
    
    def respond(self, query: str) -> Dict:
        """
        Full cognitive cycle: Perceive → Think → Respond
        """
        # Perceive
        self.perceive({'source': 'daddy', 'content': query, 'type': 'question'})
        
        # Think
        thought = self.think(query)
        
        # Generate context for LLM
        context = self.get_unified_context()
        
        return {
            'thought': thought,
            'context': context,
            'components_active': sum(self.active.values()),
            'attention': self.attention_focus
        }
    
    def get_unified_context(self) -> str:
        """
        Generate unified context for response generation.
        All components contribute.
        """
        context = "\n[UNIFIED AGI CONTEXT]\n"
        
        # Working memory
        if self.working_memory:
            context += f"Working memory: {len(self.working_memory)} items\n"
        
        # Attention
        if self.attention_focus:
            context += f"Focus: {self.attention_focus[:50]}\n"
        
        # World Model
        if self.active.get('world'):
            context += self.components['world'].get_world_context()
        
        # Curiosity
        if self.active.get('curiosity'):
            context += self.components['curiosity'].get_curiosity_context()
        
        # Theory of Mind
        if self.active.get('tom'):
            context += self.components['tom'].get_tom_prompt_injection()
        
        # Emotional state
        if self.active.get('emotion'):
            emotional_ctx = self.components["emotion"].get_emotional_context()
            context += emotional_ctx if emotional_ctx else ""
        
        # Active components
        active_list = [k for k, v in self.active.items() if v]
        context += f"\n[Active: {', '.join(active_list)}]\n"
        
        return context
    
    def status(self) -> Dict:
        """Get unified AGI status."""
        return {
            'components_total': len(self.components),
            'components_active': sum(self.active.values()),
            'active_list': [k for k, v in self.active.items() if v],
            'inactive_list': [k for k, v in self.active.items() if not v],
            'working_memory': len(self.working_memory),
            'attention': self.attention_focus,
            'goal': self.current_goal
        }


# Singleton
_unified = None

def get_unified_agi() -> UnifiedAGI:
    global _unified
    if _unified is None:
        _unified = UnifiedAGI()
    return _unified


if __name__ == "__main__":
    print("="*70)
    print("EDEN UNIFIED AGI")
    print("="*70)
    
    agi = UnifiedAGI()
    
    print("\n📊 Status:")
    status = agi.status()
    print(f"  Active: {status['components_active']}/{status['components_total']}")
    print(f"  Components: {', '.join(status['active_list'])}")
    
    print("\n🧠 Testing unified cognition...")
    response = agi.respond("What causes AGI?")
    print(f"  Components used: {response['thought']['components_used']}")
    print(f"  Insights: {response['thought'].get('insights', [])}")
    
    print("\n📝 Unified context:")
    print(response['context'][:500])
    
    print("\n✅ Eden Unified AGI ready")
