"""
The pycity_scheduling framework


Copyright (C) 2025,
Institute for Automation of Complex Power Systems (ACS),
E.ON Energy Research Center (E.ON ERC),
RWTH Aachen University

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""


import numpy as np
import pyomo.environ as pyomo
import pycity_base.classes.supply.boiler as bl

from pycity_scheduling.classes.thermal_entity_heating import ThermalEntityHeating
from pycity_scheduling.util.generic_constraints import LowerActivationLimit


class Boiler(ThermalEntityHeating, bl.Boiler):
    """
    Extension of pyCity_base class Boiler for scheduling purposes.

    Parameters
    ----------
    environment : pycity_scheduling.classes.Environment
        Common to all other objects. Includes time and weather instances.
    p_th_nom : float
        Nominal heat output in [kW].
    eta : float, optional
        Efficiency of the gas boiler (without unit).
    lower_activation_limit : float, optional (only adhered to in integer mode)
        Must be in [0, 1]. Lower activation limit of the gas boiler as a
        percentage of the rated power. When the gas boiler is in operation, its
        power must be zero or between the lower activation limit and its
        rated power.

        - `lower_activation_limit = 0`: Linear behavior
        - `lower_activation_limit = 1`: Two-point controlled
    min_off_time : int, optional (only adhered to in integer mode)
        Minimum number of consecutive time steps the boiler must remain turned off, once it has been decided that it
        should turn off subject to 'lower_activation_limit'. Defaults to '1', i.e., not limited to a consecutive number
        of time steps.
    min_on_time : int, optional (only adhered to in integer mode)
        Minimum number of consecutive time steps the boiler must remain turned on, once it has been decided that it
        should turn on subject to 'lower_activation_limit'. Defaults to '1', i.e., not limited to a consecutive number
        of time steps.

    Notes
    -----
    - Gas boilers offer sets of constraints for operation. In the `convex` mode the
      following constraints and bounds are generated by the boiler:

    .. math::
        0 \\geq p_{th\\_heat} \\geq -p_{th\\_nom}

    - See also:
        - pycity_scheduling.util.generic_constraints.LowerActivationLimit:
          Generates additional constraints for the `lower_activation_limit` in `integer` mode.
    """

    def __init__(self, environment, p_th_nom, eta=1, lower_activation_limit=0.0, min_off_time=1, min_on_time=1):
        # Flow temperature of 55 C
        super().__init__(environment, 1000*p_th_nom, eta, 55, lower_activation_limit)
        self._long_id = "BL_" + self._id_string
        self.p_th_nom = p_th_nom
        self.min_off_time = min_off_time
        self.min_on_time = min_on_time
        self.activation_constr = None

    def populate_model(self, model, mode="convex"):
        """
        Add device block to pyomo ConcreteModel

        Call parent's `populate_model` method and set variables upper bounds
        to `self.p_th_nom`.

        Parameters
        ----------
        model : pyomo.ConcreteModel
        mode : str, optional
            Specifies which set of constraints to use.

            - `convex`  : Use linear constraints
            - `integer`  : Use integer variables representing discrete control decisions
        """
        if self.activation_constr is None:
            self.activation_constr = LowerActivationLimit(self, "p_th_heat", self.lower_activation_limit,
                                                          -self.p_th_nom, self.min_off_time, self.min_on_time)

        super().populate_model(model, mode)
        m = self.model

        if mode == "convex" or mode == "integer":
            def p_th_heat_vars_lb_rule(model, t):
                return model.p_th_heat_vars[t] >= -self.p_th_nom
            m.p_th_heat_vars_lb_constr = pyomo.Constraint(m.t, rule=p_th_heat_vars_lb_rule)

            def p_th_heat_vars_ub_rule(model, t):
                return model.p_th_heat_vars[t] <= 0.0
            m.p_th_heat_vars_ub_constr = pyomo.Constraint(m.t, rule=p_th_heat_vars_ub_rule)

            self.activation_constr.apply(m, mode)
        else:
            raise ValueError(
                "Mode %s is not implemented by class Boiler." % str(mode)
            )
        return

    def get_objective(self, coeff=1):
        """
        Objective function for entity level scheduling.

        Return the objective function of the boiler weighted with `coeff`.
        Sum of `p_th_heat`.

        Parameters
        ----------
        coeff : float, optional
            Coefficient for the objective function.

        Returns
        -------
        ExpressionBase :
            Objective function.
        """
        return coeff * sum(self.model.p_th_heat_vars[t] for t in range(self.op_horizon))

    def get_decision_var(self):
        return self.model.p_th_heat_vars
