"""
Performance Optimizer - Speed up execution
"""
import time
import functools
from typing import Callable, Any, List
from concurrent.futures import ThreadPoolExecutor

class PerformanceOptimizer:
    def __init__(self):
        self.cache = {}
        self.profile_data = {}
    
    def profile_execution(self, function: Callable) -> Callable:
        """Profile function execution time"""
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            start = time.time()
            result = function(*args, **kwargs)
            elapsed = time.time() - start
            
            fname = function.__name__
            if fname not in self.profile_data:
                self.profile_data[fname] = []
            self.profile_data[fname].append(elapsed)
            
            print(f"⚡ {fname} took {elapsed:.4f}s")
            return result
        return wrapper
    
    def cache_results(self, function: Callable) -> Callable:
        """Cache function results"""
        @functools.wraps(function)
        def wrapper(*args):
            key = (function.__name__, args)
            if key in self.cache:
                return self.cache[key]
            result = function(*args)
            self.cache[key] = result
            return result
        return wrapper
    
    def parallel_execution(self, tasks: List[Callable]) -> List[Any]:
        """Execute tasks in parallel"""
        with ThreadPoolExecutor(max_workers=4) as executor:
            results = list(executor.map(lambda f: f(), tasks))
        return results
    
    def optimize_code(self, source: str) -> str:
        """Basic code optimization suggestions"""
        suggestions = []
        
        if 'for i in range(len(' in source:
            suggestions.append("Use enumerate() instead of range(len())")
        if '+ str(' in source:
            suggestions.append("Use f-strings for string formatting")
        
        return '\n'.join(suggestions) if suggestions else "Code looks good!"
