"""
Eden Cognitive System - Full reflective intelligence
All cognitive capabilities working together
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))

from autonomy.learning_loops import LearningLoop
from autonomy.task_planner import TaskPlanner
from autonomy.task_executor import TaskExecutor
from autonomy.meta_learner import MetaLearner
from autonomy.transfer_learning import TransferLearner
from memory.episodic_memory import EpisodicMemory
from reasoning.causal_model import CausalModel
from reasoning.self_reflection import SelfReflectionLoop
from reasoning.hypothesis_generator import HypothesisGenerator

class EdenCognitive:
    def __init__(self):
        # Core systems
        self.learning = LearningLoop()
        self.planner = TaskPlanner()
        self.executor = TaskExecutor()
        
        # Cognitive systems
        self.meta_learner = MetaLearner(self.learning)
        self.episodic = EpisodicMemory()
        self.causal = CausalModel()
        self.transfer = TransferLearner()
        
        # Reflective systems
        self.reflection = SelfReflectionLoop(self.meta_learner, self.causal)
        self.hypothesis = HypothesisGenerator(self.causal, self.meta_learner)
        
        print("🧠 Eden Cognitive System Initialized")
        print("   All reflective intelligence systems online")
    
    def cognitive_task_completion(self, goal, task_type):
        print(f"\n{'='*70}")
        print(f"🎯 COGNITIVE TASK: {goal}")
        print(f"{'='*70}")
        
        # 1. Check episodic memory
        similar = self.episodic.recall_by_context(task_type)
        if similar:
            print(f"\n📚 Recalled {len(similar)} similar episodes")
        
        # 2. Use causal reasoning
        plan = self.planner.create_plan(goal)
        for step in plan['steps']:
            if step['action']:
                prediction = self.causal.predict_outcome(step['action'])
                if prediction['prediction'] != 'unknown':
                    print(f"   Predicting: {step['action']} → {prediction['prediction']} ({prediction['confidence']:.0%})")
        
        # 3. Execute with learning
        result = self.executor.execute_plan(plan, dry_run=True)
        
        # 4. Create episodic memory
        episode = self.episodic.create_episode({
            'task': goal,
            'approach': plan['steps'][0]['action'] if plan['steps'] else 'unknown',
            'outcome': 'completed' if result['success'] else 'failed',
            'success': result['success'],
            'task_type': task_type
        })
        
        # 5. Learn causal link
        if plan['steps']:
            self.causal.learn_causal_link(
                plan['steps'][0]['action'],
                'completed' if result['success'] else 'failed',
                result['success']
            )
        
        print(f"\n✅ Task complete - Episode {episode['id']} created")
        return result
    
    def full_cognitive_cycle(self):
        """Complete cognitive reflection cycle"""
        print("\n" + "="*70)
        print("🧠 EDEN FULL COGNITIVE CYCLE")
        print("="*70)
        
        # Meta-learning
        print("\n1️⃣ META-LEARNING:")
        self.meta_learner.self_reflect()
        
        # Self-reflection
        print("\n2️⃣ SELF-REFLECTION:")
        self.reflection.continuous_reflect()
        
        # Hypothesis generation
        print("\n3️⃣ HYPOTHESIS FORMATION:")
        self.hypothesis.display_hypotheses()
        
        print("\n" + "="*70)
        print("🎉 COGNITIVE CYCLE COMPLETE")
        print("="*70)

if __name__ == "__main__":
    print("="*70)
    print("EDEN COGNITIVE SYSTEM TEST")
    print("="*70)
    
    eden = EdenCognitive()
    
    # Test cognitive task
    eden.cognitive_task_completion("Create a status report", "document_creation")
    
    # Run full cognitive cycle
    eden.full_cognitive_cycle()
    
    print("\n✅ EDEN COGNITIVE SYSTEM FULLY OPERATIONAL")
