"""
Eden Code Executor
Allows Eden to execute Python code safely
"""
import subprocess
import tempfile
import os
import sys

class EdenExecutor:
    def __init__(self):
        self.allowed_imports = [
            'numpy', 'scipy', 'PIL', 'midiutil', 'music21', 'pydub',
            'matplotlib', 'cv2', 'torch', 'math', 'random', 'time'
        ]
        
    def execute_python(self, code, timeout=30):
        """Execute Python code and return output"""
        try:
            # Create temporary file
            with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
                f.write(code)
                temp_file = f.name
            
            # Execute with timeout
            result = subprocess.run(
                [sys.executable, temp_file],
                capture_output=True,
                text=True,
                timeout=timeout,
                cwd='/Eden/ART'  # Run in ART directory
            )
            
            # Clean up
            os.unlink(temp_file)
            
            return {
                'success': result.returncode == 0,
                'output': result.stdout,
                'error': result.stderr,
                'code': code
            }
            
        except subprocess.TimeoutExpired:
            os.unlink(temp_file)
            return {
                'success': False,
                'output': '',
                'error': 'Execution timeout (30s)',
                'code': code
            }
        except Exception as e:
            return {
                'success': False,
                'output': '',
                'error': str(e),
                'code': code
            }
    
    def extract_code_from_response(self, text):
        """Extract Python code blocks from AI response"""
        import re
        
        # Look for ```python code blocks
        pattern = r'```python\n(.*?)```'
        matches = re.findall(pattern, text, re.DOTALL)
        
        if matches:
            return matches[0]
        
        # Look for indented code blocks
        lines = text.split('\n')
        code_lines = []
        in_code = False
        
        for line in lines:
            if line.strip().startswith('import ') or line.strip().startswith('from '):
                in_code = True
            if in_code:
                code_lines.append(line)
                
        if code_lines:
            return '\n'.join(code_lines)
            
        return None

    def search_google(self, query, num_results=5):
        """Eden searches Google"""
        from eden_search import eden_search
        return eden_search.google(query, num_results)
    
    def search_youtube(self, query, max_results=5):
        """Eden searches YouTube"""
        from eden_search import eden_search
        return eden_search.youtube(query, max_results)
    
    def research_topic(self, topic):
        """Eden autonomously researches a topic"""
        from eden_search import eden_search
        return eden_search.learn_from_topic(topic)
