"""Accounting and policy-boundary checks for Chapter 19 (no document builds)."""
import unittest
from dataclasses import replace
from calibration import Calibration, australian_calibration, load_population, ubi_weight
from emtr import Australia1July2025, Household, VoTa


class DemographicAccounting(unittest.TestCase):
    def test_age_boundaries_and_continuous_ramp(self):
        for age, expected in [(0, .5), (12, .5), (13, .5), (13.5, .55),
                              (14, .6), (15, .7), (16, .8), (17, .9), (18, 1), (100, 1)]:
            self.assertAlmostEqual(ubi_weight(age), expected)
        with self.assertRaises(ValueError):
            ubi_weight(-1)

    def test_published_population_and_income(self):
        c = australian_calibration()
        self.assertEqual(len(load_population()), 101)
        self.assertEqual(c.population, 27614411)
        self.assertAlmostEqual(c.total_weight, 25042976.6)
        self.assertEqual(c.aggregate_income, 1894110000000)
        self.assertAlmostEqual(c.adult_ubi, 32414.73414032693)
        self.assertAlmostEqual(c.services_pool / c.population, 21557.28450212877)

    def test_pool_conservation_with_children(self):
        # One adult and two young children: two weights, three people.
        c = Calibration(population=3, total_weight=2, aggregate_income=80000, ubi_rate=.2, svc_rate=.3)
        self.assertEqual(c.total_consumption, 100000)
        self.assertEqual(c.ubi_pool, 20000)
        self.assertEqual(c.adult_ubi, 10000)
        self.assertEqual(c.adult_ubi * (1 + .5 + .5), c.ubi_pool)
        all_adults = replace(c, total_weight=3)
        self.assertEqual(all_adults.ubi_pool, c.ubi_pool)
        self.assertLess(all_adults.adult_ubi, c.adult_ubi)
        self.assertEqual(all_adults.services_pool, c.services_pool)

    def test_income_scaling_and_consumption_feedback(self):
        c = australian_calibration()
        self.assertAlmostEqual(replace(c, aggregate_income=c.aggregate_income / 2).adult_ubi,
                               c.adult_ubi / 2)
        for q in (0, .8, .9, 1):
            s = replace(c, consumption_fraction=q)
            self.assertAlmostEqual(s.total_consumption, q * (s.aggregate_income + s.ubi_pool), places=3)
            self.assertAlmostEqual(s.adult_ubi * s.total_weight, s.ubi_pool, places=3)
        self.assertAlmostEqual(australian_calibration(.8).disposable_adult_ubi, 11464.579653841945)

    def test_original_vota_configuration_api_retains_demographic_accounting(self):
        v = VoTa(mean_income=70000, svc_rate=.25, ubi_rate=.25, f_start=.6)
        self.assertEqual(v.mean_income, 70000)
        self.assertAlmostEqual(v.ubi_weight(0), .6)
        self.assertAlmostEqual(sum(n * v.U_star * v.ubi_weight(a) for a, n in load_population().items()),
                               v.calibration.ubi_pool, places=3)
        self.assertAlmostEqual(v.emtr(50000, Household([40])), 50)

    def test_household_income_and_marginal_rate(self):
        v = VoTa(Calibration(3, 2, 80000, ubi_rate=.2, svc_rate=.3))
        hh = Household([30, 5, 8])
        self.assertEqual(v.disposable_income(0, hh), 10000)
        self.assertEqual(v.disposable_income(30000, hh), 25000)
        for y in (0, 10000, 50000, 200000):
            self.assertAlmostEqual(v.emtr(y, hh), 50)
        self.assertEqual(v.disposable_income(10000, Household([30, 30], partner_income=20000)), 25000)
        etr = lambda y: 1 - v.disposable_income(y, hh) / y
        self.assertLess(etr(10000), etr(100000))


class AustralianReference(unittest.TestCase):
    def setUp(self):
        self.au = Australia1July2025()
        self.single = Household([40])
        self.parent = Household([42, 5, 8, 11])

    def test_tax_brackets_offsets_and_levy(self):
        self.assertAlmostEqual(self.au.income_tax(45000), 4288)
        self.assertAlmostEqual(self.au.income_tax(190000), 51638)
        self.assertEqual(self.au.lito(37500), 700)
        self.assertEqual(self.au.lito(45000), 325)
        self.assertAlmostEqual(self.au.lito(70000), 0)
        self.assertEqual(self.au.sapto(34919, True), 2230)
        self.assertEqual(self.au.sapto(52759, True), 0)
        self.assertEqual(self.au.medicare_levy(28011, self.single), 0)
        self.assertAlmostEqual(self.au.medicare_levy(30000, self.single), 198.9)
        self.assertAlmostEqual(self.au.medicare_levy(40000, self.single), 800)

    def test_zero_earnings_benefits(self):
        # Basic PPS + three published annual FTB-A maxima + FTB-B age 5+.
        # Tax is fully offset; no Medicare levy at this income.
        expected = (982.50 * 365 / 14 + 3 * 6865.65 + 134.96 * 365 / 14 + 459.90) / 1.1
        self.assertAlmostEqual(self.au.disposable_income(0, self.parent), expected)
        self.assertAlmostEqual(self.au.disposable_income(0, self.single), 781.10 * 365 / 14 / 1.1)

    def test_pps_taxability_and_ftba_exemption(self):
        y = 65000
        pps = self.au.pps(y, self.parent)
        self.assertGreater(pps, 0)
        self.assertAlmostEqual(self.au.ftba(y, self.parent), 3 * 6865.65)
        taxable = y + pps
        sapto = self.au.sapto(taxable, True)
        tax = max(0, self.au.income_tax(taxable) - self.au.lito(taxable) - sapto)
        expected = (taxable - tax - self.au.medicare_levy(taxable, self.parent, sapto)
                    + self.au.ftba(y, self.parent) + self.au.ftbb(y, self.parent)) / 1.1
        self.assertAlmostEqual(self.au.disposable_income(y, self.parent), expected)

    def test_ftb_cash_cliffs_and_base_rate(self):
        self.assertAlmostEqual(self.au.ftba(80000, self.parent) - self.au.ftba(80000.01, self.parent),
                               3 * 938.05 + .002)
        self.assertGreater(self.au.ftbb(120007, self.parent), 0)
        self.assertEqual(self.au.ftbb(120007.01, self.parent), 0)
        self.assertAlmostEqual(self.au.ftba(110000, Household([40, 5])), 72.94 * 365 / 14)

    def test_worked_marginal_examples(self):
        self.assertAlmostEqual(self.au.emtr(20000, self.single), (1 - .206 / 1.1) * 100)
        self.assertAlmostEqual(self.au.emtr(220000, self.single), (1 - .53 / 1.1) * 100)

    def test_invalid_or_unmodelled_inputs_fail_explicitly(self):
        for hh in [Household([18]), Household([67]), Household([40, 40, 40]),
                   Household([40], partner_income=10000),
                   Household([40, 5], childcare_cost_per_child=[100]),
                   Household([40, 5], childcare_hours_per_child=[20], childcare_cost_per_child=[12])]:
            with self.assertRaises(ValueError):
                self.au.disposable_income(0, hh)


class FamilySizeComparison(unittest.TestCase):
    def test_single_parent_matches_existing_chart_calculation(self):
        from family_comparison import zero_earnings_family
        for ages in ([], [5], [5, 8], [5, 8, 11]):
            result = zero_earnings_family(1, ages)
            self.assertAlmostEqual(result.australia_consumption,
                                   Australia1July2025().disposable_income(0, Household([40] + ages)))

    def test_couple_ftbb_counts_income_support(self):
        from family_comparison import zero_earnings_family
        result = zero_earnings_family(2, [3, 5, 7, 9, 11])
        # Full published annual FTB-B under-5 rate less the secondary-earner taper.
        expected_b = 5500.55 - .2 * (715.10 * 365 / 14 - 6935)
        self.assertAlmostEqual(result.ftbb, expected_b)
        self.assertAlmostEqual(result.australia_cash,
                               2 * 715.10 * 365 / 14 + 5 * 6865.65 + expected_b)
        self.assertGreater(result.vota_cash, result.australia_cash)
        self.assertGreater(result.vota_consumption, result.australia_consumption)

    def test_children_are_not_double_counted_for_ftb_and_ya(self):
        from family_comparison import zero_earnings_family
        teens = zero_earnings_family(2, [13, 14, 15, 16, 17])
        students = zero_earnings_family(2, [18, 19, 20, 21, 22])
        self.assertEqual(teens.ftbb, 0)
        self.assertEqual(teens.youth_allowance, 0)
        self.assertAlmostEqual(teens.ftba, 5 * 8650.50)
        self.assertEqual(students.ftba, 0)
        self.assertEqual(students.ftbb, 0)
        self.assertAlmostEqual(students.youth_allowance, 5 * 472.50 * 365 / 14)

    def test_additional_young_children_narrow_after_tax_gap(self):
        from family_comparison import zero_earnings_family
        one = zero_earnings_family(2, [3])
        two = zero_earnings_family(2, [3, 5])
        self.assertAlmostEqual(two.australia_consumption - one.australia_consumption, 6865.65 / 1.1)
        self.assertAlmostEqual(two.vota_consumption - one.vota_consumption,
                               australian_calibration().disposable_adult_ubi / 2)
        self.assertLess(two.australia_consumption - two.vota_consumption,
                           one.australia_consumption - one.vota_consumption)

    def test_unconditional_payment_is_unaffected_by_youth_allowance_eligibility(self):
        from family_comparison import zero_earnings_family
        eligible = zero_earnings_family(2, [18, 19, 20, 21, 22])
        ineligible = zero_earnings_family(2, [18, 19, 20, 21, 22], False)
        self.assertEqual(eligible.vota_cash, ineligible.vota_cash)
        self.assertGreater(eligible.vota_consumption, eligible.australia_consumption)
        self.assertEqual(eligible.vota_consumption, ineligible.vota_consumption)
        self.assertGreater(eligible.australia_consumption, ineligible.australia_consumption)
        self.assertGreater(ineligible.vota_consumption, ineligible.australia_consumption)


class PretaxFamilyComparison(unittest.TestCase):
    def test_gross_up_preserves_after_income_tax_value(self):
        from family_comparison import (australian_pretax_equivalent,
                                       parent_net_income, zero_earnings_family)
        for parents in (1, 2):
            for ages in ([], [3], [13], [5, 8], [13, 14, 17], [14, 15, 16, 17]):
                with self.subTest(parents=parents, ages=ages):
                    r = zero_earnings_family(parents, ages)
                    partner = r.parent_support / 2 if parents == 2 else 0
                    base = r.parent_support - partner
                    pps = parents == 1 and bool(ages) and min(ages) < 14
                    net = lambda y: parent_net_income(y, parents, len(ages), partner, pps, base)
                    gross = australian_pretax_equivalent(parents, ages)
                    self.assertAlmostEqual(net(gross - partner) - net(base), r.ftba + r.ftbb)
                    self.assertGreaterEqual(gross + 1e-8, r.australia_cash)

    def test_no_tax_free_benefits_need_no_gross_up(self):
        from family_comparison import australian_pretax_equivalent
        self.assertAlmostEqual(australian_pretax_equivalent(1, []), 781.10 * 365 / 14)
        self.assertAlmostEqual(australian_pretax_equivalent(2, []), 2 * 715.10 * 365 / 14)

    def test_large_family_exemption_and_age_cutoff(self):
        from family_comparison import zero_earnings_family
        younger = zero_earnings_family(1, [14, 15, 16, 17])
        older = zero_earnings_family(1, [16, 16.5, 17, 17.5])
        self.assertAlmostEqual(younger.parent_support, 1011.50 * 365 / 14)
        self.assertAlmostEqual(older.parent_support, 836.50 * 365 / 14)

    def test_couple_family_levy_reduction_with_exempt_spouse(self):
        from family_comparison import parent_net_income
        au = Australia1July2025()
        income, partner, children = 50000, 715.10 * 365 / 14, 2
        threshold = 47238 + 4338 * children
        reduction = max(0, .02 * threshold - .08 * (income + partner - threshold))
        levy = max(0, .02 * income - reduction)
        tax = max(0, au.income_tax(income) - au.lito(income) - .15 * (partner - 6000))
        self.assertAlmostEqual(parent_net_income(income, 2, children, partner, False, partner),
                               income - tax - levy)

    def test_buying_power_uses_a_common_retail_price_basis(self):
        from family_comparison import household_table_rows, zero_earnings_family
        for parents, children, vmin, vmax, amin, amax in household_table_rows():
            for amount, ages in (amin, amax):
                result = zero_earnings_family(parents, ages)
                self.assertAlmostEqual(amount, result.australia_consumption * 1.1)
                self.assertAlmostEqual(result.vota_cash * .528,
                                       result.vota_consumption * 1.1)
                self.assertLessEqual(vmin, result.vota_cash + 1e-8)
                self.assertGreaterEqual(vmax, result.vota_cash - 1e-8)
        # With no children, Australian buying power is the basic payment,
        # while a VoTa payment buys 52.8% of its face value at these retail prices.
        row = next(household_table_rows())
        self.assertAlmostEqual(row[4][0], 781.10 * 365 / 14)
        self.assertAlmostEqual(row[2] * .528, 17115, delta=1)

    def test_table_covers_twelve_households_and_under_18_configurations(self):
        from family_comparison import household_table_rows, australian_pretax_equivalent
        rows = list(household_table_rows())
        self.assertEqual(len(rows), 12)
        for parents, children, vmin, vmax, amin, amax in rows:
            self.assertLessEqual(vmin, vmax)
            self.assertLessEqual(amin[0], amax[0])
            self.assertTrue(all(age < 18 for age in amin[1] + amax[1]))
            self.assertAlmostEqual(vmax, australian_calibration().adult_ubi * (parents + children))
        with self.assertRaises(ValueError):
            australian_pretax_equivalent(2, [18])


class PartTimeFamilyComparison(unittest.TestCase):
    def test_matches_independent_single_parent_earnings_model(self):
        from family_comparison import part_time_australian_buying_power
        for ages in ([], [5], [3, 8], [5, 8, 11]):
            expected = Australia1July2025().disposable_income(30000, Household([40] + ages)) * 1.1
            self.assertAlmostEqual(part_time_australian_buying_power(1, ages), expected)

    def test_couple_retains_non_earner_support_and_ftb(self):
        from family_comparison import part_time_australian_buying_power, FORTNIGHTS
        # Independent worked couple: reduced earner allowance, full partner
        # allowance, one young child's FTB, and no family Medicare levy.
        support = 715.10 * FORTNIGHTS - (53 * FORTNIGHTS + .6 * (30000 - 256 * FORTNIGHTS))
        taxable = 30000 + support
        tax = (taxable - 18200) * .16 - 700
        ftbb = 193.34 * FORTNIGHTS + 459.90 - .2 * (715.10 * FORTNIGHTS - 6935)
        expected = taxable - tax + 715.10 * FORTNIGHTS + 6865.65 + ftbb
        self.assertAlmostEqual(part_time_australian_buying_power(2, [3]), expected)

    def test_principal_carer_taper_ends_at_sixteen(self):
        from family_comparison import part_time_australian_buying_power
        # FTB is unchanged across this boundary; JSP withdrawal increases.
        self.assertGreater(part_time_australian_buying_power(1, [15.99]),
                           part_time_australian_buying_power(1, [16]))

    def test_rows_keep_ubi_and_apply_common_price_basis(self):
        from family_comparison import household_table_rows, part_time_table_rows
        rows = list(part_time_table_rows())
        self.assertEqual(len(rows), 12)
        for base, work in zip(household_table_rows(), rows):
            self.assertEqual(base[:2], work[:2])
            for index in (2, 3):
                self.assertAlmostEqual((work[index] - base[index]) * .528, 15840)
            self.assertLessEqual(work[4][0], work[5][0])


class RestoredComplexity(unittest.TestCase):
    def setUp(self):
        self.au = Australia1July2025()

    def test_original_ato_example_including_lito(self):
        # Tax on $50,000 is $5,788 before the $250 LITO; Medicare $1,000.
        self.assertAlmostEqual(self.au.disposable_income(50000, Household([40])),
                               (50000 - 5788 + 250 - 1000) / 1.1)

    def test_original_household_coverage_and_no_mutated_income_state(self):
        from emtr import example_households
        self.assertEqual(len(example_households()), 8)
        for hh, _ in example_households():
            original = hh.primary_income
            for y in (0, 30000, 80000, 120008, 200000):
                self.assertTrue(__import__('math').isfinite(self.au.disposable_income(y, hh)))
                self.assertTrue(__import__('math').isfinite(self.au.emtr(y, hh)))
            self.assertEqual(hh.primary_income, original)
        self.assertGreater(self.au.disposable_income(0, Household([65])), 0)
        self.assertGreater(self.au.ftba(0, Household([40, 14, 17])), self.au.ftba(0, Household([40, 5, 8])))

    def test_restored_model_matches_all_existing_table_configurations(self):
        from itertools import combinations_with_replacement
        from family_comparison import zero_earnings_family, part_time_australian_buying_power
        for parents in (1, 2):
            for n in range(6):
                for ages in combinations_with_replacement((0, 5, 13, 14, 16, 17.99), n):
                    hh = Household([40] * parents + list(ages))
                    self.assertAlmostEqual(self.au.disposable_income(0, hh) * 1.1,
                                           zero_earnings_family(parents, ages).australia_cash)
                    self.assertAlmostEqual(self.au.disposable_income(30000, hh) * 1.1,
                                           part_time_australian_buying_power(parents, ages))

    def test_partner_test_and_secondary_income_affect_benefits(self):
        low = Household([40, 38, 5], partner_income=0)
        high = Household([40, 38, 5], partner_income=50000)
        self.assertGreater(self.au.primary_income_support(0, low), self.au.primary_income_support(0, high))
        self.assertEqual(self.au.primary_income_support(0, Household([40, 38], partner_income=100000)), 0)
        self.assertGreater(self.au.ftbb(60000, low), self.au.ftbb(60000, Household([40, 38, 5], partner_income=30000)))

    def test_published_rent_maxima_and_income_withdrawal(self):
        f = 365 / 14
        cases = [(Household([40], rent_per_week=500), 212),
                 (Household([40], rent_per_week=500, is_sharer=True), 141.33),
                 (Household([40, 38], rent_per_week=500), 199.80),
                 (Household([40, 5], rent_per_week=500), 249.20),
                 (Household([40, 5, 8, 11], rent_per_week=500), 281.54)]
        for hh, maximum in cases:
            self.assertAlmostEqual(self.au.rent_assistance(0, hh), maximum * f)
            self.assertEqual(self.au.rent_assistance(250000, hh), 0)
        hh = Household([40, 5], rent_per_week=500)
        self.assertGreater(self.au.rent_assistance(70000, hh), self.au.rent_assistance(90000, hh))
        # RA extends the income-support entitlement; it cannot vanish when
        # the basic taxable allowance alone reaches zero.
        single = Household([40], rent_per_week=500)
        self.assertEqual(self.au.jobseeker(40000, single), 0)
        self.assertGreater(self.au.rent_assistance(40000, single), 0)

    def test_rent_and_ftba_are_not_double_counted(self):
        rented = Household([40, 5], rent_per_week=500)
        owned = Household([40, 5])
        self.assertAlmostEqual(self.au.disposable_income(0, rented) - self.au.disposable_income(0, owned),
                               249.2 * 365 / 14 / 1.1)
        self.assertAlmostEqual(self.au.disposable_income(250000, rented), self.au.disposable_income(250000, owned))

    def care(self, ages, hours=None, fees=None, **kwargs):
        return Household([40] + ages,
                         childcare_hours_per_child=hours or [30] * len(ages),
                         childcare_cost_per_child=fees or [10] * len(ages),
                         childcare_activity_exempt=True, **kwargs)

    def test_ccs_standard_higher_child_rate_and_fee_cap(self):
        # At low income, eldest young child gets 90%, younger gets 95%.
        self.assertAlmostEqual(self.au.ccs(0, self.care([2, 5, 8])), 30 * 10 * 52 * (.95 + .9 + .9))
        capped = self.care([3], fees=[20])
        self.assertAlmostEqual(self.au.ccs(0, capped), 30 * 14.63 * 52 * .9)
        school = self.care([8], fees=[20])
        self.assertAlmostEqual(self.au.ccs(0, school), 30 * 12.81 * 52 * .9)
        family = self.care([3], fees=[20], childcare_service_types=['family'])
        self.assertAlmostEqual(self.au.ccs(0, family), 30 * 13.56 * 52 * .9)
        self.assertEqual(self.au.ccs(535279, capped), 0)

    def test_ccs_activity_hours_and_fee_subsidy_not_spendable_cash(self):
        hh = Household([40, 3], childcare_hours_per_child=[30], childcare_cost_per_child=[10],
                       childcare_activity_hours_per_fortnight=8)
        self.assertAlmostEqual(self.au.ccs(0, hh), 18 * 10 * 52 * .9)
        hh.childcare_activity_hours_per_fortnight = 0
        self.assertAlmostEqual(self.au.ccs(0, hh), 12 * 10 * 52 * .9)
        self.assertEqual(self.au.ccs(90000, hh), 0)
        hh = self.care([3])
        x = self.au.breakdown(30000, hh)
        self.assertAlmostEqual(x['cash_after_childcare'], x['cash_after_tax'] - x['childcare_fees'] + x['ccs'])
        self.assertLess(x['cash_after_childcare'], x['cash_after_tax'])

    def test_ccs_higher_rate_cliff_is_retained(self):
        hh = self.care([2, 5])
        # Younger child's rate falls from 50% to standard (33.5432%).
        self.assertAlmostEqual(self.au.ccs(367563 - .001, hh) - self.au.ccs(367563 + .001, hh),
                               15600 * (.5 - (.9 - (367563 - 85279) / 500000)), delta=.01)

    def test_medicare_surcharge_thresholds_for_single_and_family(self):
        single = Household([40], has_private_health_insurance=False)
        self.assertEqual(self.au.medicare_surcharge([101000], single), 0)
        self.assertAlmostEqual(self.au.medicare_surcharge([101001], single), 1010.01)
        parent = Household([40, 5, 8], has_private_health_insurance=False)
        self.assertEqual(self.au.medicare_surcharge([203500], parent), 0)
        self.assertAlmostEqual(self.au.medicare_surcharge([203501], parent), 2035.01)
        couple = Household([40, 38], has_private_health_insurance=False)
        self.assertAlmostEqual(self.au.medicare_surcharge([200000, 20000], couple), 2000)

    def test_family_medicare_reduction_shared_without_duplication(self):
        hh = Household([40, 38])
        x, y = 29000, 29000
        reduction = max(0, .02 * 47238 - .08 * (x + y - 47238))
        expected = 2 * min(.02 * x, .1 * (x - 28011)) - reduction
        actual = self.au.medicare_levy(x, hh, partner_taxable=y) + self.au.medicare_levy(y, hh, partner_taxable=x)
        self.assertAlmostEqual(actual, expected)

    def test_unused_family_levy_reduction_transfers_to_spouse(self):
        hh = Household([40, 38, 5, 8])
        other = 33266.4642857143
        def combined(y):
            return (self.au.medicare_levy(y, hh, partner_taxable=other)
                    + self.au.medicare_levy(other, hh, partner_taxable=y))
        self.assertAlmostEqual(combined(28011 - .001), combined(28011 + .001), delta=.001)
        threshold = 47238 + 2 * 4338
        y = 28012
        expected = max(0, min(.02 * y, .1 * (y - 28011)) + min(.02 * other, .1 * (other - 28011))
                       - max(0, .02 * threshold - .08 * (y + other - threshold)))
        self.assertAlmostEqual(combined(y), expected)

    def test_plots_locate_actual_cliffs_including_ati_and_mls(self):
        from emtr import cash_cliffs
        hh = Household([40, 5], has_private_health_insurance=False)
        cliffs = cash_cliffs(self.au, hh, 240000)
        by_income = dict(cliffs)
        self.assertAlmostEqual(by_income[80000], 938.05 / 1.1, delta=.01)
        self.assertAlmostEqual(by_income[120007], 3978.5 / 1.1, delta=.01)
        self.assertAlmostEqual(by_income[202000], 2020 / 1.1, delta=.01)
        hh = self.care([2, 5])
        self.assertTrue(any(abs(x - 367563) < .01 for x, loss in cash_cliffs(self.au, hh, 550000)))


if __name__ == '__main__':
    unittest.main()
