from policyengine_uk.model_api import *
from policyengine_core.variables import Variable


class marginal_tax_rate(Variable):
    label = "Marginal tax rate"
    documentation = "Percent of marginal income gains that do not increase household net income."
    entity = Person
    definition_period = YEAR
    value_type = float
    unit = "/1"

    def formula(person, period, parameters):
        p = parameters(period).gov.simulation
        mtr_values = np.zeros(person.count, dtype=np.float32)
        simulation = person.simulation
        adult_index_values = person("adult_index", period)
        delta = p.marginal_tax_rate_delta
        adult_count = p.marginal_tax_rate_adults
        for adult_index in range(1, 1 + adult_count):
            alt_simulation = simulation.get_branch(
                f"adult_{adult_index}_pay_rise"
            )
            mask = adult_index_values == adult_index
            for variable in simulation.tax_benefit_system.variables:
                variable_data = simulation.tax_benefit_system.variables[
                    variable
                ]
                if (
                    variable not in simulation.input_variables
                    and not variable_data.is_input_variable()
                ):
                    alt_simulation.delete_arrays(variable)
            alt_simulation.set_input(
                "employment_income",
                period,
                person("employment_income", period) + mask * delta,
            )
            alt_person = alt_simulation.person
            household_net_income = person.household(
                "household_net_income", period
            )
            household_net_income_higher_earnings = alt_person.household(
                "household_net_income", period
            )
            increase = (
                household_net_income_higher_earnings - household_net_income
            )
            mtr_values += where(mask, 1 - increase / delta, 0)
        return mtr_values
