from Utilities.Shading import calculate_energy_production_vertical
from scipy.optimize import minimize
import logging

logger = logging.getLogger(__name__)


def optimise_vertical_panel_pitch(c):
    def objective(pitch):
        """
        Objective function to minimize the energy production from vertical panels.

        Args:
            pitch (float): The pitch of the vertical panels in degrees.

        Returns:
            float: The negative of the energy production from vertical panels.
        """
        pitch += c["panel"]["dimensions"]["thickness"]
        c["array"]["spacing"] = pitch
        logging.info(f"Optimizing with pitch: {pitch}m")
        vertical_energy, _ = calculate_energy_production_vertical(c)
        total_energy_yield = vertical_energy.sum()
        logger.info(f"Total energy yield for pitch {pitch}m: {total_energy_yield}kWh")
        return -total_energy_yield

    # perform minimization
    initial_pitch = c["array"]["spacing"]
    result = minimize(
        objective, initial_pitch, bounds=[(0, 20)], tol=1e-8, options={"eps": 1}
    )
    optimal_pitch = result.x[0]
    c["array"]["spacing"] = optimal_pitch
    logger.info(f"Optimal pitch found: {optimal_pitch}m")
    vetical_energy, no_of_panels = calculate_energy_production_vertical(c)
    return (optimal_pitch, vetical_energy, no_of_panels)