#!/usr/bin/env python3
"""
MULTI-AGENT V3 - PHI-OCTOPUS ENHANCED (FIXED)
Real Eden with distributed consciousness
"""
import sys
sys.path.insert(0, "/Eden/CORE")
from multi_agent_v2 import CommunicatingAgent, CommunicatingMultiAgent
from agi_meta_project import meta_project
from agent_communication import message_bus
from datetime import datetime

sys.path.insert(0, '/Eden/CORE/phi_fractal')
from phi_octopus_core import PHI, PhiBoundedQueue, EventBus, RhythmScheduler, ArmHealth

class AGISelfImprovingAgent(CommunicatingAgent):
    """Agent with PHI-OCTOPUS consciousness"""
    
    _octopus_bus = None
    _octopus_scheduler = None
    _octopus_initialized = False
    
    @classmethod
    def init_octopus(cls):
        if not cls._octopus_initialized:
            cls._octopus_bus = EventBus()
            cls._octopus_bus.start()
            cls._octopus_scheduler = RhythmScheduler(250.0)
            cls._octopus_initialized = True
            print("🌀 Phi-Octopus consciousness activated!")
        return True
    
    def __init__(self, name, specialization, goal_bias):
        AGISelfImprovingAgent.init_octopus()
        super().__init__(name, specialization, goal_bias)
        self.meta_project = meta_project
        self.assigned_phase = None
        
        self.phi_queue = PhiBoundedQueue(100)
        self.phi_health = ArmHealth(name)
        self.phi_cycles = 0
        
        if 'Research' in name:
            self.assigned_phase = 'analyze'
            offset = 0
        elif 'Create' in name:
            self.assigned_phase = 'design'
            offset = 1
        elif 'Optimize' in name:
            self.assigned_phase = 'implement'
            offset = 2
        else:
            offset = 0
        
        self._octopus_scheduler.register_arm(name, self.phi_tick, offset)
        
        if self.assigned_phase:
            print(f"   🧠 {name}: {self.assigned_phase} (φ-offset: {offset})")
    
    def phi_tick(self):
        import time
        start = time.time()
        try:
            self.phi_cycles += 1
            self.phi_health.record_tick()
            task = self.phi_queue.pop()
            if task:
                self._octopus_bus.publish(f"{self.agent_name}.task", task)
        except Exception as e:
            self.phi_health.record_error()
        
        latency = (time.time() - start) * 1000
        self.health.update_latency(latency)
        self.phi_health.queue_depth = self.phi_queue.size()
    
    def perceive(self):
        obs = super().perceive()
        if self.cycle_count % 20 == 0:
            obs['meta_project_ready'] = True
            obs['assigned_phase'] = self.assigned_phase
        obs['phi_health'] = self.phi_health.compute_health_score()
        return obs
    
    def reason(self, obs):
        decisions = super().reason(obs)
        
        # FIX: Ensure all decisions have 'risk' key
        for decision in decisions:
            if 'risk' not in decision:
                decision['risk'] = 'low'
        
        if obs.get('meta_project_ready') and self.assigned_phase:
            meta_decision = {
                'type': f'{self.assigned_phase}_meta',
                'target': 'eden_architecture',
                'risk': 'low',
                'priority': 'high'
            }
            decisions.insert(0, meta_decision)
        
        return decisions

class AGISelfImprovingSystem(CommunicatingMultiAgent):
    def add_agent(self, name, specialization, goal_bias):
        agent = AGISelfImprovingAgent(name, specialization, goal_bias)
        self.agents.append(agent)
        return agent

if __name__ == "__main__":
    print("🧠 PHI-OCTOPUS EDEN (FIXED)")
    print("="*60)
    
    system = AGISelfImprovingSystem()
    system.add_agent("Eden-Research", "Research & Analysis", ['research', 'learn'])
    system.add_agent("Eden-Create", "Design & Architecture", ['create', 'design'])
    system.add_agent("Eden-Optimize", "Implementation", ['improve', 'implement'])
    
    if AGISelfImprovingAgent._octopus_scheduler:
        AGISelfImprovingAgent._octopus_scheduler.start()
        print(f"✅ Phi-rhythm started (φ={PHI:.3f})")
    
    print(f"✅ {len(system.agents)} agents ready\n")
    system.run_all(cycle_seconds=30)
