"""Grid search optimization."""

from typing import Dict, List, Any, Callable
from itertools import product
from src.core.logger import get_logger

logger = get_logger(__name__)


class GridSearchOptimizer:
    """Grid search parameter optimization."""
    
    def __init__(self):
        """Initialize grid search optimizer."""
        self.logger = get_logger(__name__)
    
    def optimize(
        self,
        param_grid: Dict[str, List[Any]],
        objective_function: Callable[[Dict[str, Any]], float],
        maximize: bool = True
    ) -> Dict[str, Any]:
        """Run grid search optimization.
        
        Args:
            param_grid: Dictionary of parameter -> list of values
            objective_function: Function that takes parameters and returns score
            maximize: True to maximize, False to minimize
            
        Returns:
            Best parameters and score
        """
        best_score = float('-inf') if maximize else float('inf')
        best_params = None
        
        # Generate all parameter combinations
        param_names = list(param_grid.keys())
        param_values = list(param_grid.values())
        
        for combination in product(*param_values):
            params = dict(zip(param_names, combination))
            
            try:
                score = objective_function(params)
                
                if (maximize and score > best_score) or (not maximize and score < best_score):
                    best_score = score
                    best_params = params
            except Exception as e:
                logger.warning(f"Failed to evaluate parameters {params}: {e}")
                continue
        
        return {
            "best_params": best_params,
            "best_score": best_score,
        }

