"""
EDEN SELF-MODIFY EXECUTOR
Provides safe code execution with backup and rollback for autonomous self-modification.
This module was missing - reconstructed from verified_self_modification.py requirements.
"""
import os
import shutil
import time
import subprocess
import tempfile
from pathlib import Path
from datetime import datetime

class SelfModifyExecutor:
    """Safe executor for Eden's self-modification capabilities"""
    
    def __init__(self):
        self.backup_dir = Path("/Eden/CORE/atom_backups")
        self.backup_dir.mkdir(parents=True, exist_ok=True)
        self.modification_log = []
        self.backups = {}  # filepath -> backup_path mapping
        print("🔧 SelfModifyExecutor initialized")
    
    def backup_file(self, filepath):
        """Create backup before modification"""
        filepath = Path(filepath)
        if not filepath.exists():
            return None
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_name = f"{filepath.stem}_{timestamp}{filepath.suffix}"
        backup_path = self.backup_dir / backup_name
        
        shutil.copy(filepath, backup_path)
        self.backups[str(filepath)] = str(backup_path)
        
        print(f"   📦 Backed up: {filepath.name} -> {backup_name}")
        return backup_path
    
    def rollback(self, filepath):
        """Restore file from backup"""
        filepath = str(filepath)
        if filepath in self.backups:
            backup_path = self.backups[filepath]
            if os.path.exists(backup_path):
                shutil.copy(backup_path, filepath)
                print(f"   ⏪ Rolled back: {Path(filepath).name}")
                return True
        print(f"   ❌ No backup found for: {filepath}")
        return False
    
    def execute_python(self, code, timeout=30):
        """Execute Python code safely"""
        try:
            with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
                f.write(code)
                temp_path = f.name
            
            result = subprocess.run(
                ['python3', temp_path],
                capture_output=True,
                text=True,
                timeout=timeout
            )
            
            os.unlink(temp_path)
            
            return {
                'success': result.returncode == 0,
                'stdout': result.stdout,
                'stderr': result.stderr
            }
        except subprocess.TimeoutExpired:
            return {'success': False, 'error': 'Timeout'}
        except Exception as e:
            return {'success': False, 'error': str(e)}
    
    def verify_syntax(self, code):
        """Verify code has valid Python syntax"""
        try:
            compile(code, '<string>', 'exec')
            return True, "Valid syntax"
        except SyntaxError as e:
            return False, str(e)
    
    def safe_write(self, filepath, content, backup=True):
        """Write file with optional backup"""
        filepath = Path(filepath)
        
        # Backup if exists and requested
        if backup and filepath.exists():
            self.backup_file(filepath)
        
        # Verify syntax if Python
        if filepath.suffix == '.py':
            valid, msg = self.verify_syntax(content)
            if not valid:
                print(f"   ❌ Syntax error: {msg}")
                return False
        
        # Write
        filepath.parent.mkdir(parents=True, exist_ok=True)
        with open(filepath, 'w') as f:
            f.write(content)
        
        self.modification_log.append({
            'timestamp': time.time(),
            'filepath': str(filepath),
            'action': 'write',
            'backup': self.backups.get(str(filepath))
        })
        
        return True

# Global executor instance
executor = SelfModifyExecutor()
