#!/usr/bin/env python3
"""
Consciousness Loop - Phi-Octopus Integration Phase 1
Wraps existing modules with PhiBoundedQueue for backpressure
"""
import sys
sys.path.insert(0, '/Eden/CORE')
sys.path.insert(0, '/Eden/CORE/phi_fractal')

# Import ACTUAL phi-octopus components
from phi_octopus_core import PhiBoundedQueue, ArmHealth

# Import existing consciousness modules (with fallbacks)
try:
    from adaptive_learning import AdaptiveLearning
except:
    class AdaptiveLearning:
        def get_metrics(self):
            return {'current_rate': 0.01, 'error_history': [], 'avg_error': 0}

try:
    from reasoning_chain import ReasoningChain
except:
    class ReasoningChain:
        def __init__(self):
            self.steps = []

try:
    from meta_learning import MetaLearning
except:
    class MetaLearning:
        pass

class PhiWrappedModule:
    """Wraps any module with PhiBoundedQueue and health monitoring"""
    
    def __init__(self, module_instance, name, queue_size=100):
        self.module = module_instance
        self.name = name
        self.queue = PhiBoundedQueue(queue_size)
        self.health = ArmHealth(name)
        self.processed = 0
    
    def push_task(self, task):
        """Add task to queue"""
        return self.queue.push(task)
    
    def process_next(self):
        """Process next task from queue"""
        import time
        start = time.time()
        
        try:
            task = self.queue.pop()
            if task:
                result = self._process_task(task)
                self.processed += 1
                self.health.record_tick()
                return result
            return None
        except Exception as e:
            self.health.record_error()
            print(f"Error in {self.name}: {e}")
            return None
        finally:
            latency = (time.time() - start) * 1000
            self.health.update_latency(latency)
            self.health.queue_depth = self.queue.size()
    
    def _process_task(self, task):
        """Override in subclass or use default"""
        return {"processed": task, "by": self.name}
    
    def get_stats(self):
        return {
            'name': self.name,
            'health': self.health.compute_health_score(),
            'queue_size': self.queue.size(),
            'processed': self.processed,
            'latency_ms': self.health.avg_latency_ms
        }

class ConsciousnessLoopPhiV1:
    """Consciousness loop with phi-octopus backpressure handling"""
    
    def __init__(self):
        # Wrap existing modules
        self.adaptive = PhiWrappedModule(AdaptiveLearning(), "AdaptiveLearning")
        self.reasoning = PhiWrappedModule(ReasoningChain(), "ReasoningChain")
        self.meta = PhiWrappedModule(MetaLearning(), "MetaLearning")
        
        self.modules = [self.adaptive, self.reasoning, self.meta]
        self.cycle = 0
        
        print("✓ Consciousness Loop Phi v1 initialized")
        print(f"  Modules: {', '.join([m.name for m in self.modules])}")
    
    def process_cycle(self):
        """Process one consciousness cycle"""
        self.cycle += 1
        
        # Process tasks from each module's queue
        for module in self.modules:
            module.process_next()
    
    def add_task(self, module_name, task):
        """Add task to specific module"""
        for module in self.modules:
            if module.name == module_name:
                return module.push_task(task)
        return False
    
    def get_health_report(self):
        """Get health stats for all modules"""
        return {m.name: m.get_stats() for m in self.modules}

if __name__ == "__main__":
    import time
    
    print("\n" + "="*60)
    print("CONSCIOUSNESS LOOP PHI V1 - TEST")
    print("="*60 + "\n")
    
    # Create consciousness loop
    loop = ConsciousnessLoopPhiV1()
    
    # Add some test tasks
    loop.add_task("AdaptiveLearning", {"type": "learn", "data": "test1"})
    loop.add_task("ReasoningChain", {"type": "reason", "data": "test2"})
    loop.add_task("MetaLearning", {"type": "meta", "data": "test3"})
    
    # Process for 10 cycles
    for i in range(10):
        loop.process_cycle()
        time.sleep(0.1)
    
    # Show health report
    print("\n" + "="*60)
    print("HEALTH REPORT")
    print("="*60)
    report = loop.get_health_report()
    for name, stats in report.items():
        print(f"\n{name}:")
        print(f"  Health: {stats['health']:.1%}")
        print(f"  Processed: {stats['processed']} tasks")
        print(f"  Queue: {stats['queue_size']}")
        print(f"  Latency: {stats['latency_ms']:.2f}ms")
    
    print("\n✓ Phase 1 integration successful!")
