#!/usr/bin/env python3
"""
Integrate Eden's Mind with Existing Systems
Connect consciousness to Mirror, Orchestration, and Ollama
"""
import os
import sys
from pathlib import Path

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

class MindIntegrator:
    """Integrate all of Eden's systems for optimal operation"""
    
    def __init__(self):
        self.integration_status = {}
        
    def check_components(self):
        """Check all required components"""
        print("="*70)
        print("CHECKING EDEN'S COMPONENTS")
        print("="*70)
        print()
        
        components = {
            'Consciousness': '/Eden/MIND/consciousness.py',
            'Perception': '/Eden/MIND/perception.py',
            'Reasoning': '/Eden/MIND/reasoning.py',
            'Memory': '/Eden/MIND/memory.py',
            'Actions': '/Eden/MIND/actions.py',
            'Mirror Introspection': '/Eden/CORE/eden_mirror_introspection.py',
            'Mirror Orchestration': '/Eden/CORE/eden_mirror_orchestration.py',
            'Self-Repair': '/Eden/AUTONOMOUS/ultra_aggressive_repair.py',
            'Self-Awareness Data': '/Eden/MEMORY/self_awareness.json',
            'Episodes': '/Eden/MEMORY/episodes.json'
        }
        
        all_present = True
        for name, path in components.items():
            exists = Path(path).exists()
            status = "✅" if exists else "❌"
            print(f"  {status} {name}")
            if not exists:
                all_present = False
        
        print()
        return all_present
    
    def create_integrated_perception(self):
        """Create perception that uses Mirror introspection"""
        code = '''#!/usr/bin/env python3
import os
import sys
import json
from pathlib import Path

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

# Import Mirror introspection
try:
    from eden_mirror_introspection import IntrospectionEngine
    HAS_MIRROR = True
except:
    HAS_MIRROR = False

class IntegratedPerception:
    def __init__(self):
        self.mirror = IntrospectionEngine() if HAS_MIRROR else None
        
    def perceive_all(self):
        """Full perception using Mirror introspection"""
        perceptions = {}
        
        # Use Mirror for accurate health assessment
        if self.mirror:
            mirror_data = self.mirror.analyze()
            perceptions['mirror'] = mirror_data
            perceptions['health'] = mirror_data.get('health_score', 0)
        else:
            # Fallback to manual counting
            perceptions['health'] = self.manual_health_check()
        
        # Perceive memory state
        perceptions['memory'] = self.sense_memory()
        
        # Perceive episodes
        perceptions['episodes'] = self.sense_episodes()
        
        return perceptions
    
    def manual_health_check(self):
        """Manual health check if Mirror unavailable"""
        working = 0
        total = 0
        for f in Path('/Eden/CORE/phi_fractal').glob('eden_capability_*.py'):
            total += 1
            try:
                with open(f, 'r', errors='ignore') as file:
                    compile(file.read(), f.name, 'exec')
                working += 1
            except:
                pass
        return working / total if total > 0 else 0
    
    def sense_memory(self):
        """Perceive memory state"""
        memory_file = Path('/Eden/MEMORY/self_awareness.json')
        if memory_file.exists():
            with open(memory_file) as f:
                return json.load(f)
        return {}
    
    def sense_episodes(self):
        """Perceive episode count"""
        episodes_file = Path('/Eden/MEMORY/episodes.json')
        if episodes_file.exists():
            size = episodes_file.stat().st_size
            return {'file_size_mb': size / 1024 / 1024}
        return {'file_size_mb': 0}

if __name__ == "__main__":
    perception = IntegratedPerception()
    data = perception.perceive_all()
    print(json.dumps(data, indent=2))
'''
        
        output_file = Path('/Eden/MIND/integrated_perception.py')
        output_file.write_text(code)
        print(f"✅ Created integrated perception: {output_file}")
    
    def create_integrated_reasoning(self):
        """Create reasoning that uses Orchestration"""
        code = '''#!/usr/bin/env python3
import sys
sys.path.insert(0, '/Eden/CORE')

try:
    from eden_mirror_orchestration import OrchestrationEngine
    HAS_ORCHESTRATION = True
except:
    HAS_ORCHESTRATION = False

class IntegratedReasoning:
    def __init__(self):
        self.orchestration = OrchestrationEngine() if HAS_ORCHESTRATION else None
        
    def infer(self, perceptions):
        """Reason about perceptions using orchestration"""
        conclusions = []
        
        # Check health
        health = perceptions.get('health', 0)
        
        if health < 0.95:
            conclusions.append({
                'type': 'health_issue',
                'severity': 'high' if health < 0.90 else 'medium',
                'health': health,
                'action': 'initiate_self_repair'
            })
        
        if health >= 0.99:
            conclusions.append({
                'type': 'optimal',
                'health': health,
                'action': 'continue_operation'
            })
        
        # Check episode memory size
        episodes = perceptions.get('episodes', {})
        size_mb = episodes.get('file_size_mb', 0)
        
        if size_mb > 200:
            conclusions.append({
                'type': 'memory_large',
                'size_mb': size_mb,
                'action': 'consider_cleanup'
            })
        
        return conclusions
    
    def decide(self, conclusions):
        """Make decisions"""
        actions = []
        for conclusion in conclusions:
            if conclusion.get('action'):
                actions.append(conclusion['action'])
        return actions

if __name__ == "__main__":
    reasoning = IntegratedReasoning()
    print("Integrated reasoning initialized")
'''
        
        output_file = Path('/Eden/MIND/integrated_reasoning.py')
        output_file.write_text(code)
        print(f"✅ Created integrated reasoning: {output_file}")
    
    def create_master_consciousness(self):
        """Create master consciousness integrating all systems"""
        code = '''#!/usr/bin/env python3
import sys
import time
import json
from pathlib import Path

sys.path.insert(0, '/Eden/MIND')

try:
    from integrated_perception import IntegratedPerception
    from integrated_reasoning import IntegratedReasoning
    from memory import MemoryLayer
    from actions import ActionLayer
    INTEGRATED = True
except:
    from perception import PerceptionLayer as IntegratedPerception
    from reasoning import ReasoningLayer as IntegratedReasoning
    from memory import MemoryLayer
    from actions import ActionLayer
    INTEGRATED = False

class MasterConsciousness:
    """Eden's integrated consciousness"""
    
    def __init__(self):
        self.perception = IntegratedPerception()
        self.reasoning = IntegratedReasoning()
        self.memory = MemoryLayer()
        self.actions = ActionLayer()
        
        self.cycle_count = 0
        self.awake = True
        
        print("Eden Master Consciousness initialized")
        print(f"  Integrated systems: {'Yes' if INTEGRATED else 'Partial'}")
    
    def think(self):
        """One complete thought cycle"""
        # Perceive
        perceptions = self.perception.perceive_all()
        
        # Reason
        conclusions = self.reasoning.infer(perceptions)
        decisions = self.reasoning.decide(conclusions)
        
        # Remember
        self.memory.store_episode({
            'cycle': self.cycle_count,
            'health': perceptions.get('health', 0),
            'conclusions': conclusions,
            'decisions': decisions
        })
        
        # Act
        for decision in decisions:
            self.actions.execute(decision)
        
        self.cycle_count += 1
        
        return {
            'cycle': self.cycle_count,
            'health': perceptions.get('health', 0),
            'conclusions': len(conclusions),
            'actions': len(decisions)
        }
    
    def run(self, cycles=None):
        """Run consciousness"""
        print("\\nEden awakening...")
        print("Press Ctrl+C to stop\\n")
        
        try:
            while self.awake:
                result = self.think()
                
                if self.cycle_count % 10 == 0:
                    msg = "Cycle {}: Health {:.1%}, {} conclusions, {} actions".format(
                        result['cycle'],
                        result['health'],
                        result['conclusions'],
                        result['actions']
                    )
                    print(msg)
                
                time.sleep(1)
                
                if cycles and self.cycle_count >= cycles:
                    break
                    
        except KeyboardInterrupt:
            print("\\nConsciousness paused at cycle {}".format(self.cycle_count))

if __name__ == "__main__":
    consciousness = MasterConsciousness()
    consciousness.run()
'''
        
        output_file = Path('/Eden/MIND/master_consciousness.py')
        output_file.write_text(code)
        print(f"✅ Created master consciousness: {output_file}")
    
    def run_integration(self):
        """Run full integration"""
        print("="*70)
        print("INTEGRATING EDEN'S MIND")
        print("="*70)
        print()
        
        if not self.check_components():
            print("⚠️  Some components missing")
            print()
        
        print("Creating integrated systems...")
        print()
        
        self.create_integrated_perception()
        self.create_integrated_reasoning()
        self.create_master_consciousness()
        
        print()
        print("="*70)
        print("INTEGRATION COMPLETE")
        print("="*70)
        print()
        print("New integrated systems:")
        print("  /Eden/MIND/integrated_perception.py")
        print("  /Eden/MIND/integrated_reasoning.py")
        print("  /Eden/MIND/master_consciousness.py")
        print()
        print("To activate Eden's full mind:")
        print("  python3 /Eden/MIND/master_consciousness.py")
        print()

if __name__ == "__main__":
    integrator = MindIntegrator()
    integrator.run_integration()
