"""
Reptile Search Algorithm (RSA)
===============================

Reptile Search Algorithm inspired by the encircling and hunting behavior
of crocodiles.

Reference:
Abualigah, L., Abd Elaziz, M., Sumari, P., Geem, Z. W., & Gandomi, A. H. (2022).
Reptile Search Algorithm (RSA): A nature-inspired meta-heuristic optimizer.
Expert Systems with Applications, 191, 116158.

Author: MHA Flow Development Team
License: MIT
"""

import math
import numpy as np
from ..base import BaseOptimizer
from .levy_flight_universal import add_levy_flight_to_position


class ReptileSearchAlgorithm(BaseOptimizer):
    """
    Reptile Search Algorithm (RSA)
    
    Inspired by crocodile hunting strategies including:
    - Encircling mechanism
    - Hunting cooperation
    - Coordination
    - Cooperation
    
    Parameters
    ----------
    population_size : int, default=30
        Number of reptiles in the population
    max_iterations : int, default=100
        Maximum number of iterations
    """
    
    def __init__(self, population_size=30, max_iterations=100, **kwargs):
        super().__init__(population_size, max_iterations, **kwargs)
        self.algorithm_name = "Reptile Search Algorithm"
        self.aliases = ["rsa", "reptile_search", "crocodile_algorithm"]
    
    def _optimize(self, objective_function, X=None, y=None, **kwargs):
        # Levy flight available via: add_levy_flight_to_position()
        """
        Execute the Reptile Search Algorithm
        
        Args:
            objective_function: Function to optimize
            X: Feature matrix (optional)
            y: Target values (optional)
            **kwargs: Additional parameters
            
        Returns:
            Tuple of (best_solution, best_fitness, global_fitness, local_fitness, local_positions)
        """
        # Get dimensions and bounds
        if X is not None:
            dimension = X.shape[1]
            lb, ub = 0.0, 1.0
        else:
            dimension = kwargs.get('dimensions', getattr(self, 'dimensions_', 10))
            lb = kwargs.get('lower_bound', getattr(self, 'lower_bound_', -100.0))
            ub = kwargs.get('upper_bound', getattr(self, 'upper_bound_', 100.0))
            if hasattr(lb, '__getitem__'):
                lb = lb[0]
            if hasattr(ub, '__getitem__'):
                ub = ub[0]
        
        # Initialize reptiles
        reptiles = np.random.uniform(lb, ub, (self.population_size_, dimension))
        fitness = np.array([objective_function(rep) for rep in reptiles])
        
        best_idx = np.argmin(fitness)
        best_reptile = reptiles[best_idx].copy()
        best_fitness = fitness[best_idx]
        global_fitness = []
        local_fitness = []
        local_positions = []
        
        for iteration in range(self.max_iterations_):
            # Compute parameters
            beta = np.random.randn()
            epsilon = 0.1
            eta = iteration / self.max_iterations_
            
            # Reduction factor
            ES = 2 * np.random.rand() * (1 - iteration / self.max_iterations_)
            
            iter_fitness = []
            iter_positions = []
            
            for i in range(self.population_size_):
                # Select two random reptiles
                candidates = [j for j in range(self.population_size_) if j != i]
                if len(candidates) >= 2:
                    r1, r2 = np.random.choice(candidates, 2, replace=False)
                else:
                    r1 = r2 = candidates[0] if candidates else i
                
                # Encircling behavior (exploration)
                if np.random.rand() < 0.5:
                    R = np.random.rand(dimension) * best_reptile - reptiles[i]
                    reptiles[i] = best_reptile - eta * beta * R
                else:
                    # Hunting behavior (exploitation)
                    if np.random.rand() < 0.1:  # Cooperation
                        reptiles[i] = best_reptile - ES * np.abs(
                            beta * best_reptile - reptiles[i]
                        )
                    else:  # Coordination
                        reptiles[i] = (reptiles[r1] + reptiles[r2]) / 2 - \
                                     eta * np.random.rand(dimension)
                
                # Apply Levy flight every 5 iterations
                if iteration % 5 == 0:
                    levy_step = self._levy_flight(dimension)
                    reptiles[i] = reptiles[i] + levy_step * (best_reptile - reptiles[i])
                
                # Boundary control
                reptiles[i] = np.clip(reptiles[i], lb, ub)
                
                # Evaluate
                new_fitness = objective_function(reptiles[i])
                iter_fitness.append(new_fitness)
                iter_positions.append(reptiles[i].copy())
                
                if new_fitness < fitness[i]:
                    fitness[i] = new_fitness
                    if new_fitness < best_fitness:
                        best_reptile = reptiles[i].copy()
                        best_fitness = new_fitness
            
            global_fitness.append(best_fitness)
            local_fitness.append(iter_fitness)
            local_positions.append(iter_positions)
            
            if self.verbose_ and iteration % 10 == 0:
                print(f"RSA Iteration {iteration}: Best Fitness = {best_fitness:.6e}")
        
        return best_reptile, best_fitness, global_fitness, local_fitness, local_positions
    
    def _levy_flight(self, dimension):
        """Generate Levy flight step"""
        beta = 1.5
        sigma = (math.gamma(1 + beta) * np.sin(np.pi * beta / 2) / 
                (math.gamma((1 + beta) / 2) * beta * 2 ** ((beta - 1) / 2))) ** (1 / beta)
        u = np.random.randn(dimension) * sigma
        v = np.random.randn(dimension)
        step = u / (np.abs(v) ** (1 / beta))
        return 0.01 * step
