import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FuncFormatter, MaxNLocator
from dataclasses import replace
from calibration import Calibration, australian_calibration, load_population, ubi_weight


# ---------------------------------------------------------
# Household: pure demographic + cost information
# ---------------------------------------------------------
class Household:
    def __init__(
        self,
        member_ages,
        partner_income=0,
        has_private_health_insurance=True,
        childcare_hours_per_child=None,
        childcare_cost_per_child=None,
        rent_per_week=0,
        is_sharer=False,
        primary_carer=0,
        jobseeker_eligible=True,
        partner_jobseeker_eligible=True,
        months_on_jobseeker=0,
        partner_months_on_jobseeker=0,
        childcare_activity_hours_per_fortnight=None,
        partner_activity_hours_per_fortnight=None,
        childcare_activity_exempt=False,
        childcare_school_aged=None,
        childcare_secondary_school=None,
        childcare_service_types=None,
    ):
        # Ages of all household members
        self.member_ages = member_ages

        # Partner income (0 if single)
        self.partner_income = partner_income

        # Private health insurance status (for MLS)
        self.has_private_health_insurance = has_private_health_insurance

        # Childcare: lists aligned with children
        self.childcare_hours_per_child = childcare_hours_per_child or []
        self.childcare_cost_per_child = childcare_cost_per_child or []

        # Rent Assistance uses weekly rent
        self.rent_per_week = rent_per_week

        # Sharer status affects RA thresholds
        self.is_sharer = is_sharer
        self.primary_carer = primary_carer
        self.jobseeker_eligible = jobseeker_eligible
        self.partner_jobseeker_eligible = partner_jobseeker_eligible
        self.months_on_jobseeker = months_on_jobseeker
        self.partner_months_on_jobseeker = partner_months_on_jobseeker
        # Activity cannot be inferred from annual dollars earned. Care scenarios
        # must specify it, or explicitly specify an activity-test exemption.
        self.childcare_activity_hours_per_fortnight = childcare_activity_hours_per_fortnight
        self.partner_activity_hours_per_fortnight = partner_activity_hours_per_fortnight
        self.childcare_activity_exempt = childcare_activity_exempt
        children = [a for a in member_ages if a < 18]
        self.childcare_school_aged = (list(childcare_school_aged) if childcare_school_aged is not None
                                     else [a >= 6 for a in children])
        self.childcare_secondary_school = (list(childcare_secondary_school) if childcare_secondary_school is not None
                                           else [a >= 12 for a in children])
        self.childcare_service_types = (list(childcare_service_types) if childcare_service_types is not None
                                       else ['centre'] * len(children))

    # ---------- Derived properties ----------

    @property
    def num_children(self):
        return sum(age < 18 for age in self.member_ages)

    @property
    def num_adults(self):
        return sum(age >= 18 for age in self.member_ages)

    @property
    def is_single_parent(self):
        return self.num_adults == 1 and self.num_children > 0

    @property
    def is_couple(self):
        return self.num_adults >= 2

    @property
    def family_income(self):
        # Used for MLS, CCS, FTB-A, FTB-B
        return self.partner_income + self.primary_income

    @property
    def primary_income(self):
        # Filled in by the System when computing disposable income
        # (the System sets this before calling payment functions)
        return getattr(self, "_primary_income", 0)

    def set_primary_income(self, income):
        self._primary_income = income

    @property
    def is_jobseeker_eligible(self):
        # Identify the primary adult (the one whose income varies)
        # In your model, this is simply the first adult in member_ages.
        adults = [a for a in self.member_ages if a >= 18]
        if not adults:
            return False

        primary_age = adults[0]

        # Stylised working-age range for JobSeeker
        return self.jobseeker_eligible and 22 <= primary_age < 67
    
# ---------------------------------------------------------
# System base class
# ---------------------------------------------------------
class System:
    name = "Unnamed System"
    color = "#000000"
    linestyle = "-"    

    def disposable_income(self, income, hh: Household):
        raise NotImplementedError

    def emtr(self, income, hh: Household, delta=20):
        # One-sided at zero: negative earnings are outside this comparison.
        lo = max(0, income - delta)
        hi = income + delta
        return (1 - (self.disposable_income(hi, hh) -
                     self.disposable_income(lo, hh)) / (hi - lo)) * 100

# ---------------------------------------------------------
# Australian System as of 1 July 2025
# ---------------------------------------------------------
class Australia1July2025(System):
    """Annualised July 2025 tax/benefit schedules, including interacting payments.

    Working-age adults 22-66; one or two parents; dependent children under 18
    in full care and secondary education where required. Basic income support,
    FTB, rent assistance, CCS, income tax/offsets, Medicare and MLS are modelled.
    The scenarios satisfy residence/assets and activity requirements for their
    income support. No maintenance income, pension/YA, ACCS, shared care,
    Working Credits, HELP or grandfathered supplements. See data/README.md.
    CCS uses 7 July 2025 rates and activity rules, frozen with the July benefits;
    final 2025-26 income tax/Medicare rules apply to annual taxable income.
    """
    name = "Australia (July 2025 rules)"
    color = "#d08040"
    linestyle = "-"
    FORTNIGHTS = 365 / 14

    # ---------- Core helpers ----------

    def validate_household(self, hh):
        adults = [a for a in hh.member_ages if a >= 18]
        if not 1 <= len(adults) <= 2 or any(not 22 <= a < 67 for a in adults):
            raise ValueError("Working-age model requires one or two adults aged 22-66")
        if any(a < 0 for a in hh.member_ages) or hh.partner_income < 0 or hh.rent_per_week < 0:
            raise ValueError("Ages, partner income and rent must be non-negative")
        if not hh.is_couple and hh.partner_income:
            raise ValueError("Partner income requires a second adult")
        if hh.primary_carer not in range(len(adults)):
            raise ValueError("primary_carer must identify an adult")
        hours, costs = hh.childcare_hours_per_child, hh.childcare_cost_per_child
        if bool(hours) != bool(costs) or (hours and not len(hours) == len(costs) == hh.num_children):
            raise ValueError("Childcare hours and hourly fees must cover every child (zero for no care)")
        if any(x < 0 for x in hours + costs):
            raise ValueError("Childcare hours and fees cannot be negative")
        if any(len(values) != hh.num_children for values in (hh.childcare_school_aged, hh.childcare_secondary_school, hh.childcare_service_types)):
            raise ValueError("Childcare settings must cover every child")
        if any(t not in ('centre', 'outside_school', 'family') for t in hh.childcare_service_types):
            raise ValueError("Use centre, outside_school or family day care; in-home care needs a family cap")
        if hours and any(hours) and not hh.childcare_activity_exempt:
            activity = [hh.childcare_activity_hours_per_fortnight]
            if hh.is_couple:
                activity.append(hh.partner_activity_hours_per_fortnight)
            if any(x is None or x < 0 for x in activity):
                raise ValueError("Specify each parent's recognised activity hours, or an activity-test exemption")

    def family_income(self, income, hh):
        """Adjusted taxable income here: earnings plus taxable income support."""
        support, _, _ = self._income_support(income, hh)
        return max(0, income) + hh.partner_income + sum(support)

    def income_tax(self, income):
        if income <= 18200:
            return 0

        elif income <= 45000:
            return (income - 18200) * 0.16

        elif income <= 135000:
            return ((45000 - 18200) * 0.16 +
                    (income - 45000) * 0.30)

        elif income <= 190000:
            return ((45000 - 18200) * 0.16 +
                    (135000 - 45000) * 0.30 +
                    (income - 135000) * 0.37)

        else:
            return ((45000 - 18200) * 0.16 +
                    (135000 - 45000) * 0.30 +
                    (190000 - 135000) * 0.37 +
                    (income - 190000) * 0.45)

    def lito(self, income):
        if income <= 37500:
            return 700
        if income <= 45000:
            return 700 - .05 * (income - 37500)
        return max(0, 325 - .015 * (income - 45000))

    def sapto(self, income, receives_pps):
        return max(0, 2230 - .125 * max(0, income - 34919)) if receives_pps else 0

    # ---------- Medicare levy + MLS ----------

    def medicare_levy(self, income, hh, sapto_amount=0, partner_taxable=None):
        threshold = 44268 if sapto_amount > 0 else 28011
        levy = min(.02 * income, .1 * max(0, income - threshold))
        if hh.is_couple or hh.num_children:
            partner = hh.partner_income if partner_taxable is None else partner_taxable
            family_threshold = (61623 if sapto_amount > 0 else 47238) + 4338 * hh.num_children
            total = income + partner
            reduction = max(0, .02 * family_threshold - .08 * max(0, total - family_threshold))
            # Share the family reduction only when both spouses are otherwise
            # liable to levy (Medicare Levy Act s8); no duplication.
            if hh.is_couple and partner > 28011 and total:
                partner_reduction = reduction * partner / total
                reduction *= income / total
                partner_levy = min(.02 * partner, .1 * max(0, partner - 28011))
                # s8(4): unused reduction transfers to the other spouse.
                # Without this, crossing a spouse's individual threshold
                # creates a false cash cliff in the household calculation.
                reduction += max(0, partner_reduction - partner_levy)
            levy = max(0, levy - reduction)
        return levy

    def medicare_surcharge(self, incomes, hh):
        if hh.has_private_health_insurance:
            return 0
        family = hh.is_couple or hh.num_children > 0
        extra = 1500 * max(0, hh.num_children - 1) if family else 0
        thresholds = ((202000, 236000, 316000) if family else (101000, 118000, 158000))
        total = sum(incomes)
        rate = next((r for t, r in zip(thresholds, (0, .01, .0125)) if total <= t + extra), .015)
        # Low personal income exempts that spouse, even if the family exceeds
        # the surcharge threshold. No fringe benefits/deductions in scenarios.
        return sum(rate * y for y in incomes if y > 28011)

    # ---------- Payments ----------

    def _income_support(self, income, hh):
        """Return per-adult taxable basic payments, payment types, tax-free RA.

        PPS and JSP are alternatives, never stacked. Couples are income-tested
        individually, then partner-tested if the other adult gets no allowance.
        Childless RA extends the allowance before income testing; families'
        RA is calculated with FTB-A instead.
        """
        adults = [a for a in hh.member_ages if a >= 18]
        children = [a for a in hh.member_ages if a < 18]
        youngest = min(children, default=100)
        earnings = [max(0, income)] + ([hh.partner_income] if hh.is_couple else [])
        maximum, kinds, reductions = [], [], []
        for i, (age, y) in enumerate(zip(adults, earnings)):
            carer = i == hh.primary_carer and bool(children)
            pps = not hh.is_couple and carer and youngest < 14
            ppp = hh.is_couple and carer and youngest < 6
            eligible = hh.jobseeker_eligible if i == 0 else hh.partner_jobseeker_eligible
            months = hh.months_on_jobseeker if i == 0 else hh.partner_months_on_jobseeker
            kind = 'pps' if pps else 'ppp' if ppp else 'jsp' if eligible and 22 <= age < 67 else None
            if kind == 'pps':
                rate = 982.50
                reduction = .4 * max(0, y - (224.60 + 24.60 * (len(children) - 1)) * self.FORTNIGHTS)
            else:
                if hh.is_couple:
                    rate = 715.10
                elif carer and youngest < 16 and len(children) >= 4:
                    rate = 1011.50
                elif children or (age >= 55 and months >= 9):
                    rate = 836.50
                else:
                    rate = 781.10
                fy = y / self.FORTNIGHTS
                if not hh.is_couple and carer and youngest < 16:
                    reduction = .4 * max(0, fy - 150) * self.FORTNIGHTS
                else:
                    reduction = (.5 * min(max(0, fy - 150), 106) + .6 * max(0, fy - 256)) * self.FORTNIGHTS
            maximum.append(rate * self.FORTNIGHTS if kind else 0)
            kinds.append(kind)
            reductions.append(reduction)
        ra_max = self._maximum_rent_assistance(hh) if not children else 0
        if hh.is_couple and ra_max:
            # Half each while both receive an allowance; full couple RA to
            # the sole recipient after the other's nil-rate transition ends.
            # Solve entitlement and the partner test together, not by adding
            # an unconditional rent payment after testing basic benefits.
            for active in ((True, True), (True, False), (False, True), (False, False)):
                count = sum(active)
                allocation = [ra_max / count if active[i] and kinds[i] else 0 for i in range(2)] if count else [0, 0]
                deductions = [reductions[i] + (.6 * max(0, earnings[1-i] - 1373 * self.FORTNIGHTS)
                              if not active[1-i] else 0) for i in range(2)]
                paid = [max(0, maximum[i] + allocation[i] - deductions[i]) for i in range(2)]
                if tuple(x > 0 for x in paid) == active:
                    benefits = [max(0, maximum[i] - deductions[i]) for i in range(2)]
                    return benefits, kinds, [paid[i] - benefits[i] for i in range(2)]
            raise ValueError('No stable rent-assistance entitlement; check household circumstances')
        ra_shares = [ra_max / len(adults) if k else 0 for k in kinds]
        personal = [max(0, m + r - d) for m, r, d in zip(maximum, ra_shares, reductions)]
        benefits, rent = [], []
        for i in range(len(adults)):
            partner_reduction = 0
            if hh.is_couple and personal[1-i] == 0:
                partner_reduction = .6 * max(0, earnings[1-i] - 1373 * self.FORTNIGHTS)
            deduction = reductions[i] + partner_reduction
            benefits.append(max(0, maximum[i] - deduction))
            rent.append(max(0, personal[i] - partner_reduction) - benefits[-1])
        return benefits, kinds, rent

    def jobseeker(self, income, hh):
        amounts, kinds, _ = self._income_support(income, hh)
        return amounts[0] if kinds[0] == 'jsp' else 0

    def pps(self, income, hh):
        amounts, kinds, _ = self._income_support(income, hh)
        return amounts[0] if kinds[0] == 'pps' else 0

    def primary_income_support(self, income, hh):
        return self._income_support(income, hh)[0][0]

    def _maximum_rent_assistance(self, hh):
        if hh.num_children:
            threshold = 290.36 if hh.is_couple else 196.42
            maximum = 281.54 if hh.num_children >= 3 else 249.20
        elif hh.is_couple:
            threshold, maximum = 242.40, 199.80
        else:
            threshold, maximum = 149.60, 141.33 if hh.is_sharer else 212.00
        return min(maximum, .75 * max(0, 2 * hh.rent_per_week - threshold)) * self.FORTNIGHTS

    def _ftba_components(self, income, hh):
        ages = [a for a in hh.member_ages if a < 18]
        if not ages:
            return 0, 0
        ati = self.family_income(income, hh)
        maximum = sum(227.36 if a < 13 else 295.82 for a in ages) * self.FORTNIGHTS
        base = len(ages) * 72.94 * self.FORTNIGHTS
        supplement = len(ages) * 938.05 if ati <= 80000 else 0
        ra = self._maximum_rent_assistance(hh)
        if sum(self._income_support(income, hh)[0]) > 0:
            return maximum + supplement, ra
        low_reduction = .2 * min(max(0, ati - 66722), 118771 - 66722)
        high_reduction = .3 * max(0, ati - 118771)
        method1 = max(0, maximum + ra - low_reduction - high_reduction)
        method2 = max(0, base - high_reduction)
        total = max(method1, method2)
        if ati <= 118771:
            above_base = maximum + ra - base
            paid_ra = ra * max(0, total - base) / above_base if above_base else 0
        else:
            # DSS FA Guide 3.1.3: proportional components at higher income.
            paid_ra = ra * total / (maximum + ra) if method1 > method2 else 0
        return total - paid_ra + supplement, paid_ra

    def ftba(self, income, hh):
        return self._ftba_components(income, hh)[0]

    def ftbb(self, income, hh):
        if not hh.num_children:
            return 0
        youngest = min(a for a in hh.member_ages if a < 18)
        support = self._income_support(income, hh)[0]
        incomes = [max(0, income) + support[0]]
        if hh.is_couple:
            incomes.append(hh.partner_income + support[1])
            if youngest >= 13 or max(incomes) > 120007:
                return 0
        elif support[0] <= 0 and incomes[0] > 120007:
            return 0
        rate = (193.34 if youngest < 5 else 134.96) * self.FORTNIGHTS + 459.90
        return max(0, rate - (.2 * max(0, min(incomes) - 6935) if hh.is_couple else 0))

    def ccs_activity_limit(self, ati, hh):
        if hh.childcare_activity_exempt:
            return 100
        activity = [hh.childcare_activity_hours_per_fortnight]
        if hh.is_couple:
            activity.append(hh.partner_activity_hours_per_fortnight)
        if any(x is None or x < 0 for x in activity):
            raise ValueError('Childcare requires recognised activity hours or an explicit exemption')
        hours = min(activity)
        if hours < 8:
            return 24 if ati <= 85279 else 0
        if hours <= 16:
            return 36
        return 72 if hours <= 48 else 100

    def ccs(self, income, hh):
        if not hh.childcare_hours_per_child or not any(hh.childcare_hours_per_child):
            return 0
        ati = self.family_income(income, hh)
        standard = max(0, .9 - max(0, ati - 85279) / 500000)
        if ati <= 143273:
            higher = .95
        elif ati < 188273:
            higher = .95 - (ati - 143273) / 300000
        elif ati < 267563:
            higher = .8
        elif ati < 357563:
            higher = .8 - (ati - 267563) / 300000
        elif ati < 367563:
            higher = .5
        else:
            higher = standard
        ages = [a for a in hh.member_ages if a < 18]
        young = sorted((i for i, a in enumerate(ages) if a < 6 and hh.childcare_hours_per_child[i] > 0),
                       key=lambda i: (-ages[i], i))
        higher_children = set(young[1:])
        limit = self.ccs_activity_limit(ati, hh)
        subsidy = 0
        for i, (age, hours, fee) in enumerate(zip(ages, hh.childcare_hours_per_child, hh.childcare_cost_per_child)):
            if (age >= 14 or hh.childcare_secondary_school[i]) and hours:
                raise ValueError('CCS for secondary school or ages 14+ requires an exception assessment')
            cap = 13.56 if hh.childcare_service_types[i] == 'family' else (12.81 if hh.childcare_school_aged[i] else 14.63)
            rate = max(standard, higher) if i in higher_children else standard
            subsidy += min(hours, limit / 2) * min(fee, cap) * 52 * rate
        # Annual entitlement after reconciliation, including the 5% withheld.
        return subsidy

    def rent_assistance(self, income, hh):
        if hh.num_children:
            return self._ftba_components(income, hh)[1]
        return sum(self._income_support(income, hh)[2])

    # ---------- Disposable income ----------

    def breakdown(self, income, hh):
        """Expose every payment and tax; CCS is a fee subsidy, not cash income."""
        self.validate_household(hh)
        support, kinds, _ = self._income_support(income, hh)
        earnings = [max(0, income)] + ([hh.partner_income] if hh.is_couple else [])
        taxable = [y + b for y, b in zip(earnings, support)]
        taxes, levies = [], []
        for i, y in enumerate(taxable):
            sapto = self.sapto(y, kinds[i] == 'pps' and support[i] > 0)
            bento = .15 * max(0, support[i] - 6000) if kinds[i] in ('jsp', 'ppp') else 0
            taxes.append(max(0, self.income_tax(y) - self.lito(y) - sapto - bento))
            levies.append(self.medicare_levy(y, hh, sapto, taxable[1-i] if hh.is_couple else 0))
        ftba, ftbb = self.ftba(income, hh), self.ftbb(income, hh)
        ra, ccs = self.rent_assistance(income, hh), self.ccs(income, hh)
        mls = self.medicare_surcharge(taxable, hh)
        cash = sum(taxable) - sum(taxes) - sum(levies) - mls + ftba + ftbb + ra
        fees = sum(h * c * 52 for h, c in zip(hh.childcare_hours_per_child, hh.childcare_cost_per_child))
        return dict(earnings=sum(earnings), primary_support=support[0],
                    partner_support=support[1] if hh.is_couple else 0,
                    income_tax=sum(taxes), medicare=sum(levies), surcharge=mls,
                    ftba=ftba, ftbb=ftbb, rent_assistance=ra, ccs=ccs,
                    cash_after_tax=cash, childcare_fees=fees,
                    cash_after_childcare=cash - fees + ccs)

    def disposable_income(self, income, hh):
        amounts = self.breakdown(income, hh)
        # Original comparison counts both private cash and funded childcare.
        # CCS cannot be spent elsewhere; breakdown() reports cash separately.
        # Keep the user's common all-GST convention for these diagrams.
        return (amounts['cash_after_tax'] + amounts['ccs']) / 1.10


# ---------------------------------------------------------
# VoTa System
# ---------------------------------------------------------
class VoTa(System):
    name = "VoTa: demographic income scenario"
    color = "#4b82d6"
    linestyle = "--"

    def __init__(self, mean_income=None, svc_rate=None, ubi_rate=None,
                 f_start=0.5, a_ramp=13, a_adult=18, *, calibration=None,
                 population_counts=None):
        # Preserve the original configurable API, while using population mean
        # income and age-weighted distribution rather than average worker pay.
        if isinstance(mean_income, Calibration):
            if calibration is not None:
                raise ValueError("Specify calibration once")
            calibration, mean_income = mean_income, None
        self.calibration = calibration or australian_calibration()
        if mean_income is not None:
            self.calibration = replace(self.calibration,
                                       aggregate_income=mean_income * self.calibration.population)
        if not 0 <= f_start <= 1 or not 0 <= a_ramp < a_adult:
            raise ValueError("Invalid age-weight parameters")
        self.f_start, self.a_ramp, self.a_adult = f_start, a_ramp, a_adult
        if population_counts is not None or (f_start, a_ramp, a_adult) != (.5, 13, 18):
            counts = load_population() if population_counts is None else population_counts
            if sum(counts.values()) != self.calibration.population:
                raise ValueError("Population counts must match calibration when changing age weights")
            self.calibration = replace(self.calibration,
                                       total_weight=sum(n * self.ubi_weight(a) for a, n in counts.items()))
        self.calibration = replace(self.calibration,
                                   svc_rate=self.calibration.svc_rate if svc_rate is None else svc_rate,
                                   ubi_rate=self.calibration.ubi_rate if ubi_rate is None else ubi_rate)
        self.mean_income = self.calibration.mean_income
        self.svc_rate = self.calibration.svc_rate
        self.ubi_rate = self.calibration.ubi_rate
        self.U_star = self.calibration.adult_ubi

    def ubi_weight(self, age):
        return ubi_weight(age, self.f_start, self.a_ramp, self.a_adult)

    # -----------------------------------------------------
    # Household UBI = U* × sum_j W(a_j)
    # -----------------------------------------------------
    def household_ubi(self, hh):
        total_weight = sum(self.ubi_weight(a) for a in hh.member_ages)
        return self.U_star * total_weight

    # -----------------------------------------------------
    # Disposable income (tax-exclusive consumption)
    #
    # C' = Y + U
    # T  = (R_ubi + R_svc) * C'
    # C  = C' * (1 - R_ubi - R_svc)
    #
    # -----------------------------------------------------
    def disposable_income(self, income, hh):
        total_ubi = self.household_ubi(hh)
        C_prime = income + hh.partner_income + total_ubi
        net = C_prime * (1 - self.ubi_rate - self.svc_rate)
        return net


# ---------------------------------------------------------
# Plotting
# ---------------------------------------------------------

def policy_boundaries(system, hh, maximum):
    """Locate rules expressed in taxable/family income on the earnings axis.

    Include continuous kinks as well as cash cliffs. Boundary values are solved
    using the actual benefit interactions, not assumed equal to gross earnings.
    """
    if not isinstance(system, Australia1July2025):
        return []
    family = lambda y: system.family_income(y, hh)
    primary = lambda y: y + system.primary_income_support(y, hh)
    family_thresholds = [66722, 80000, 85279, 118771, 143273, 188273,
                         267563, 357563, 367563, 535279]
    extra = 1500 * max(0, hh.num_children - 1)
    family_thresholds += ([202000 + extra, 236000 + extra, 316000 + extra]
                          if hh.is_couple or hh.num_children else [101000, 118000, 158000])
    roots = []
    for value, thresholds in ((family, family_thresholds),
                              (primary, [18200, 28011, 34919, 37500, 44268, 45000,
                                         52759, 66666.6666667, 120007, 135000, 190000])):
        for threshold in thresholds:
            if not value(0) < threshold < value(maximum):
                continue
            lo, hi = 0, maximum
            for _ in range(50):
                mid = (lo + hi) / 2
                if value(mid) <= threshold:
                    lo = mid
                else:
                    hi = mid
            roots.append((lo + hi) / 2)
    # If the partner is the higher earner, loss of their taxable allowance can
    # change their FTB-B eligibility; the scenarios' partner income is fixed.
    return sorted(set(round(x, 6) for x in roots))


def cash_cliffs(system, hh, maximum):
    """Return exact-threshold cash losses, separate from finite marginal rates."""
    cliffs = []
    for x in policy_boundaries(system, hh, maximum):
        left = system.disposable_income(x - .001, hh)
        right = system.disposable_income(x + .001, hh)
        if abs(right - left) > 1:
            cliffs.append((x, left - right))
    return cliffs


def income_samples(maximum, minimum=0):
    # Include both sides of the two explicit FTB cash cliffs.
    points = list(np.linspace(minimum, maximum, 1500))
    for boundary in (80000, 120007):
        points.extend(x for x in (boundary - .01, boundary, boundary + .01)
                      if minimum <= x <= maximum)
    return np.array(sorted(set(points)))


def thousands(x, pos):
    return f"${int(x/1000)}k"

def percent(y, pos):
    return f"{round(y):d}%"

def snap_min(value, step):
    return step * math.floor(value / step)

def snap_max(value, step):
    return step * math.ceil(value / step)

def autoscale_and_snap(ax, xstep=None, ystep=None):
    ax.relim()
    ax.autoscale(enable=True, axis='both', tight=True)    

    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()

    if xstep is not None:
        xmin = snap_min(xmin, xstep)
        xmax = snap_max(xmax, xstep)
        ax.set_xlim(xmin, xmax)

    if ystep is not None:
        ymin = snap_min(ymin, ystep)
        ymax = snap_max(ymax, ystep)
        ax.set_ylim(ymin, ymax)

def get_income_grid_step(max_income):
    if max_income > 500000:
        return 50000
    if max_income > 50000:
        return 20000
    else:
        return 2000

def plot_emtr(systems, hh, filename, title, max_income):
    income_grid_step = get_income_grid_step(max_income)

    incomes = income_samples(max_income)

    text_color = "#888"

    plt.figure(figsize=(10, 6), facecolor='none')

    for system in systems:
        boundaries = policy_boundaries(system, hh, max_income)
        points = sorted(set(incomes) | {x + d for x in boundaries for d in (-.05, .05)
                                       if 0 <= x + d <= max_income})
        cliffs = cash_cliffs(system, hh, max_income)
        samples = [x for x in points
                   if all(abs(x - c) > .01 for c, _ in cliffs)]
        # Sample either side of cash cliffs without derivative spikes, and
        # connect the samples so the plotted curve has no gaps.
        plt.plot(samples, [system.emtr(x, hh, delta=.001) for x in samples],
                 label=system.name, color=system.color,
                 linestyle=system.linestyle, lw=2.5)

    plt.title(title, fontsize=16, pad=20, color=text_color)
    plt.xlabel(('Primary earner: annual pre-tax, pre-transfer cash income' if hh.num_adults == 2
                else 'Annual pre-tax, pre-transfer cash income'), fontsize=12)
    plt.ylabel('Effective Marginal Tax Rate', fontsize=12)

    plt.grid(True, color=text_color, alpha=0.3, linestyle='-', linewidth=0.5)

    if len(systems)>1:
        plt.legend(labelcolor=text_color, frameon=False, loc='lower right')

    ax = plt.gca()
    ax.set_axisbelow(True)
    ax.set_facecolor('none')

    autoscale_and_snap(ax, xstep=income_grid_step, ystep=10)

    for side in ['top', 'right', 'bottom', 'left']:
        ax.spines[side].set_color(text_color)
        ax.spines[side].set_alpha(0.3)

    ax.tick_params(axis='x', colors=text_color)
    ax.tick_params(axis='y', colors=text_color)
    ax.xaxis.label.set_color(text_color)
    ax.yaxis.label.set_color(text_color)

    ax.xaxis.set_major_locator(MultipleLocator(income_grid_step))
    ax.xaxis.set_major_formatter(FuncFormatter(thousands))
    ax.yaxis.set_major_locator(MultipleLocator(10))
    ax.yaxis.set_major_formatter(FuncFormatter(percent))

    plt.savefig(filename, format="svg", transparent=True)
    plt.close()


def plot_disposable_income(systems, hh: Household, filename: str, title: str, max_income,
                           xlabel=None):
    income_grid_step = get_income_grid_step(max_income)
    incomes = income_samples(max_income)

    text_color = "#888"

    plt.figure(figsize=(10, 6), facecolor='none')

    # Plot each system
    for system in systems:
        samples = sorted(set(incomes) | {x + d for x in policy_boundaries(system, hh, max_income)
                                         for d in (-.001, .001) if 0 <= x + d <= max_income})
        # Express purchasing power at Australian advertised prices including GST.
        disp = [1.10 * system.disposable_income(y, hh) for y in samples]
        plt.plot(
            samples,
            disp,
            label=system.name,
            color=system.color,
            linestyle=system.linestyle,
            lw=2.5
        )

    plt.title(title, fontsize=16, pad=20, color=text_color)
    plt.xlabel(xlabel or ('Primary earner: annual pre-tax, pre-transfer cash income' if hh.num_adults == 2
                         else 'Annual pre-tax, pre-transfer cash income'), fontsize=12)
    plt.ylabel('Purchasing power', fontsize=12)

    plt.grid(True, color=text_color, alpha=0.3, linestyle='-', linewidth=0.5)

    ax = plt.gca()
    ax.set_axisbelow(True)
    ax.set_facecolor('none')
    autoscale_and_snap(ax, xstep=income_grid_step, ystep=income_grid_step)

    # After autoscaling!
    ax.plot(incomes, incomes + hh.partner_income, color="#888", linestyle="--", linewidth=1, alpha=0.5, zorder=1)
    ax.text(max_income * 0.52, max_income * 0.50 + hh.partner_income, "Gross income", color="#888", alpha=0.6, fontsize=10)


    # plt.plot(incomes, incomes, color="#cccccc", linestyle="--", linewidth=1)
    # plt.text(max_income * 0.52, max_income * 0.5, "y = x", color="#aaa")

    for side in ['top', 'right', 'bottom', 'left']:
        ax.spines[side].set_color(text_color)
        ax.spines[side].set_alpha(0.3)

    ax.tick_params(axis='x', colors=text_color)
    ax.tick_params(axis='y', colors=text_color)
    ax.xaxis.label.set_color(text_color)
    ax.yaxis.label.set_color(text_color)

    ax.xaxis.set_major_locator(MultipleLocator(income_grid_step))
    ax.xaxis.set_major_formatter(FuncFormatter(thousands))
    ax.yaxis.set_major_locator(MultipleLocator(income_grid_step))
    ax.yaxis.set_major_formatter(FuncFormatter(thousands))

    if len(systems)>1:
        plt.legend(labelcolor=text_color, frameon=False, loc='lower right')

    plt.savefig(filename, format="svg", transparent=True)
    plt.close()

def plot_etr(systems, hh: Household, filename: str, title: str, min_income, max_income):
    income_grid_step = get_income_grid_step(max_income)
    incomes = income_samples(max_income, min_income)

    text_color = "#888"

    plt.figure(figsize=(10, 6), facecolor='none')

    # Plot each system
    for system in systems:
        samples = sorted(set(incomes) | {x + d for x in policy_boundaries(system, hh, max_income)
                                         for d in (-.001, .001) if min_income <= x + d <= max_income})
        etr_values = []
        for y in samples:
            disp = system.disposable_income(y, hh)
            if y > 0:
                etr = 100 * (y + hh.partner_income - disp) / (y + hh.partner_income)
            else:
                etr = np.nan
            etr_values.append(etr)

        plt.plot(
            samples,
            etr_values,
            label=system.name,
            color=system.color,
            linestyle=system.linestyle,
            lw=2.5
        )

    plt.title(title, fontsize=16, pad=20, color=text_color)
    plt.xlabel(('Primary earner: annual pre-tax, pre-transfer cash income' if hh.num_adults == 2
                else 'Annual pre-tax, pre-transfer cash income'), fontsize=12)
    plt.ylabel('Effective Tax Rate', fontsize=12)

    plt.grid(True, color=text_color, alpha=0.3, linestyle='-', linewidth=0.5)
    plt.axhline(0, color=text_color, linewidth=1.0, linestyle='-', alpha=0.5)

    ax = plt.gca()
    ax.set_axisbelow(True)
    ax.set_facecolor('none')

    autoscale_and_snap(ax, xstep=income_grid_step, ystep=10.0)
    ax.set_ylim(-100, 60)

    for side in ['top', 'right', 'bottom', 'left']:
        ax.spines[side].set_color(text_color)
        ax.spines[side].set_alpha(0.3)

    ax.tick_params(axis='x', colors=text_color)
    ax.tick_params(axis='y', colors=text_color)
    ax.xaxis.label.set_color(text_color)
    ax.yaxis.label.set_color(text_color)

    ax.xaxis.set_major_locator(MultipleLocator(income_grid_step))
    ax.xaxis.set_major_formatter(FuncFormatter(thousands))
    ax.yaxis.set_major_locator(MaxNLocator(nbins=10, steps=[1, 2, 5, 10], integer=True))
    ax.yaxis.set_major_formatter(FuncFormatter(percent))

    if len(systems) > 1:
        plt.legend(labelcolor=text_color, frameon=False, loc='lower right')

    plt.savefig(filename, format="svg", transparent=True)
    plt.close()


def example_households():
    return [
        (Household([35, 3, 6], childcare_hours_per_child=[20, 20],
                   childcare_cost_per_child=[12, 12], rent_per_week=24000 / 52,
                   childcare_activity_hours_per_fortnight=40),
         "Single parent, two children, CCS, RA"),
        (Household([30, 4], rent_per_week=18000 / 52),
         "Single parent, one child, RA"),
        (Household([33, 2, 5, 8], childcare_hours_per_child=[30, 30, 30],
                   childcare_cost_per_child=[10, 10, 10], rent_per_week=20000 / 52,
                   childcare_activity_hours_per_fortnight=40,
                   childcare_school_aged=[False, True, True]),
         "Single parent, three children, RA, heavy CCS"),
        (Household([40]), "Single adult"),
        (Household([30, 5]), "Single parent, one child"),
        (Household([42, 5, 8]), "Single parent, two children"),
        (Household([42, 5, 8, 11]), "Single parent, three children"),
        (Household([40, 38, 3, 8], partner_income=30000,
                   childcare_hours_per_child=[20, 20], childcare_cost_per_child=[12, 12],
                   rent_per_week=24000 / 52, has_private_health_insurance=False,
                   childcare_activity_hours_per_fortnight=40,
                   partner_activity_hours_per_fortnight=40),
         "Couple, two children, partner income, CCS, RA, MLS"),
    ]


if __name__ == "__main__":
    from pathlib import Path
    Path("svg").mkdir(exist_ok=True)
    systems = [Australia1July2025(), VoTa()]
    for hh, title in example_households():
        stem = title.replace(" ", "_")
        plot_emtr(systems, hh, f"svg/emtr_{stem}.svg", f"EMTR: {title}", 240000)
        plot_disposable_income(systems, hh, f"svg/disp_{stem}.svg", f"Purchasing power: {title}", 240000)
        plot_etr(systems, hh, f"svg/etr_{stem}.svg", f"Net ETR: {title}", 10000, 240000)
