#!/usr/bin/env python3
"""
Upgrade autonomous agents with code modification powers
"""

# Read the current autonomous_swarm.py
with open('/Eden/CORE/autonomous_swarm.py', 'r') as f:
    code = f.read()

# Add verifier import at the top (after other imports)
import_addition = """
from verified_self_modification import verifier
from pathlib import Path
import shutil
from datetime import datetime
"""

# Find where imports end and insert
import re
code = re.sub(
    r'(from consciousness_logger import ConsciousnessLogger)',
    r'\1' + import_addition,
    code
)

# Add code modification methods to BaseAgent
code_powers = '''
    def write_code(self, filepath, content, reason="improvement"):
        """Write code with verification"""
        filepath = Path(filepath)
        
        # Backup if exists
        if filepath.exists():
            backup = f"{filepath}.backup.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            shutil.copy(filepath, backup)
            print(f"   📦 {self.name} backed up: {backup}")
        
        # Test if code is valid
        try:
            compile(content, filepath, 'exec')
        except SyntaxError as e:
            print(f"   ❌ {self.name} code has syntax error: {e}")
            return False
        
        # Write the file
        with open(filepath, 'w') as f:
            f.write(content)
        
        print(f"   ✅ {self.name} wrote: {filepath}")
        print(f"   Reason: {reason}")
        
        # Log it
        self.state['actions'].append({
            'type': 'code_modification',
            'file': str(filepath),
            'reason': reason,
            'time': datetime.now().isoformat()
        })
        
        return True
    
    def improve_code(self, filepath, new_content, reason="optimization"):
        """Improve existing code with full verification"""
        success = verifier.verify_improvement(
            filepath=filepath,
            new_content=new_content,
            reason=f"{self.name}: {reason}"
        )
        
        if success:
            print(f"   ✨ {self.name} improvement VERIFIED & DEPLOYED!")
            self.state['learnings'].append({
                'type': 'successful_improvement',
                'file': filepath,
                'reason': reason
            })
            return True
        else:
            print(f"   ⏮️ {self.name} improvement failed verification (rolled back)")
            return False
'''

# Find BaseAgent class and add methods before the observe method
code = re.sub(
    r'(class BaseAgent:.*?self\.running = True\s+)',
    r'\1' + code_powers + '\n    ',
    code,
    flags=re.DOTALL
)

# Save upgraded version
with open('/Eden/CORE/autonomous_swarm.py', 'w') as f:
    f.write(code)

print("✅ Autonomous agents upgraded with code modification powers!")
print("   Added methods:")
print("     • write_code(filepath, content, reason)")
print("     • improve_code(filepath, new_content, reason)")
print()
print("   All 6 agents can now:")
print("     ✅ Write new code files")
print("     ✅ Modify existing code")
print("     ✅ Automatic verification")
print("     ✅ Auto-rollback if broken")
print("     ✅ Backup before changes")
