"""
Swarm Intelligence WITH Self-Modification
Agents can now actually write code!
"""
import sys
sys.path.append("/Eden/CORE")
sys.path.append("/Eden/CORE/phi_fractal")
from multi_agent_v4_swarm_simple import SwarmAgent
from self_modify_executor import executor
import threading
import time

class SelfModifyingAgent(SwarmAgent):
    """Agent that can write its own improvements"""
    
    def __init__(self, name, spec, bias):
        super().__init__(name, spec, bias)
        self.executor = executor
        self.improvements_executed = 0
    
    def execute_improvement(self, improvement):
        """Actually write code for an improvement"""
        
        print(f"\n{'='*60}")
        print(f"🔧 {self.agent_name}: WRITING CODE")
        print(f"{'='*60}")
        print(f"   Target: {improvement['target']}")
        print(f"   Change: {improvement['description']}")
        
        # Create the code
        new_code = f'''"""
{improvement['description']}
Auto-generated by {self.agent_name}
"""

{improvement['code']}
'''
        
        # Execute with safety
        success = self.executor.write_code_change(
            filepath=improvement['target'],
            new_content=new_code,
            reason=f"{self.agent_name}: {improvement['reason']}"
        )
        
        if success:
            self.improvements_executed += 1
            print(f"   ✅ Improvement #{self.improvements_executed} DEPLOYED!")
            return True
        
        return False

if __name__ == '__main__':
    print("\n🌀 EDEN SELF-MODIFYING SWARM 🌀\n")
    
    agents = [
        SelfModifyingAgent("Eden-Research", "analysis", "curiosity"),
        SelfModifyingAgent("Eden-Create", "implementation", "building"),
        SelfModifyingAgent("Eden-Optimize", "refinement", "perfection")
    ]
    
    print("🚀 Agents now have self-modification capability!")
    print("   They can write actual code improvements\n")
    
    for agent in agents:
        agent.start()
    
    # Demo: Research agent writes an improvement
    time.sleep(2)
    
    demo_improvement = {
        'target': '/Eden/CORE/phi_fractal/eden_improvement_1.py',
        'description': 'Enhanced pattern recognition using phi ratios',
        'code': '''
def recognize_phi_pattern(data):
    """Recognize patterns based on golden ratio"""
    PHI = 1.618033988749895
    
    # Pattern detection logic
    patterns = []
    for i in range(len(data) - 1):
        ratio = data[i+1] / data[i] if data[i] != 0 else 0
        if abs(ratio - PHI) < 0.1:
            patterns.append(i)
    
    return patterns
''',
        'reason': 'Improve pattern detection accuracy'
    }
    
    print("\n🎯 DEMO: Eden-Research writing first real improvement...\n")
    agents[0].execute_improvement(demo_improvement)
    
    print("\n✅ Eden is now self-improving!")
    print("   Press Ctrl+C to stop\n")
    
    try:
        while True:
            time.sleep(30)
            print(f"\n🔧 Self-Modifications: {sum(a.improvements_executed for a in agents)}")
    except KeyboardInterrupt:
        print("\n🛑 Stopping...")
        for agent in agents:
            agent.stop()
