"""Zero-earnings family-size comparisons for Chapter 19.

Uses the same July 2025 basic-payment and all-GST basket convention as emtr.py.
Sources: data/README.md. This deliberately calculates only zero-earnings cases;
no earnings/partner tapers are inferred from the single-adult chart model.
"""
from dataclasses import dataclass
from itertools import combinations_with_replacement
from emtr import Australia1July2025
from calibration import australian_calibration, ubi_weight

FORTNIGHTS = 365 / 14


@dataclass(frozen=True)
class FamilyResult:
    parents: int
    child_ages: tuple
    parent_support: float
    ftba: float
    ftbb: float
    youth_allowance: float
    vota_cash: float

    @property
    def australia_cash(self):
        return self.parent_support + self.ftba + self.ftbb + self.youth_allowance

    @property
    def australia_consumption(self):
        return self.australia_cash / 1.1

    @property
    def vota_consumption(self):
        c = australian_calibration()
        return self.vota_cash * (1 - c.ubi_rate - c.svc_rate)


def zero_earnings_family(parents, child_ages, adult_children_receive_ya=True):
    """Parents 22-54, eligible for maximum basic income support, full care.

    Under-18s attend school and meet FTB conditions. Adult children 18-24 either
    qualify for ordinary at-home student Youth Allowance or receive no payment
    (no qualifying activity or exemption; no FTB after secondary school).
    All income/asset/residency tests satisfied; no maintenance or other income.
    No multiple births, rent/childcare payments or non-FTB supplements.
    Ages and eligibility held fixed. No income tax or Medicare is payable:
    individual payments are below the relevant tax-free/offset thresholds.
    """
    ages = tuple(child_ages)
    if parents not in (1, 2) or any(not 0 <= a <= 24 for a in ages):
        raise ValueError('Requires one or two parents and children aged 0-24')
    minors = [a for a in ages if a < 18]
    adults = len(ages) - len(minors)
    youngest = min(minors) if minors else None
    if parents == 2:
        # PPP for a carer with youngest <6, otherwise JSP. Both have the same
        # basic partnered rate; the other parent receives partnered JSP.
        per_parent = 715.10 * FORTNIGHTS
        support = 2 * per_parent
    else:
        if youngest is not None and youngest < 14:
            rate = 982.50
        elif youngest is not None and youngest < 16 and len(minors) >= 4:
            # Single principal carer with a large-family activity exemption.
            rate = 1011.50
        else:
            rate = 836.50 if minors else 781.10
        support = rate * FORTNIGHTS
    ftba = sum((227.36 if age < 13 else 295.82) * FORTNIGHTS + 938.05 for age in minors)
    ftbb = 0
    if minors and (parents == 1 or youngest < 13):
        ftbb = (193.34 if youngest < 5 else 134.96) * FORTNIGHTS + 459.90
        if parents == 2:
            # Income support counts in the secondary-earner income test.
            ftbb = max(0, ftbb - .2 * max(0, per_parent - 6935))
    ya = adults * 472.50 * FORTNIGHTS if adult_children_receive_ya else 0
    # No FTB is also paid for the adult children receiving Youth Allowance.
    weights = parents + sum(ubi_weight(age) for age in ages)
    return FamilyResult(parents, ages, support, ftba, ftbb, ya,
                        australian_calibration().adult_ubi * weights)


def parent_net_income(income, parents, children, partner_income, receives_pps, benefit):
    """Income tax and Medicare for the parent receiving all FTB, 2025-26.

    Actual taxable benefits remain fixed during the gross-up. Only hypothetical
    additional earnings vary. Couples' second parent remains on basic support
    below the individual Medicare threshold, so the first parent receives the
    whole family levy reduction (Medicare Levy Act s8(2)-(3)). No GST deduction.
    """
    tax = Australia1July2025()
    sapto = tax.sapto(income, receives_pps)
    bento = 0 if receives_pps else .15 * max(0, benefit - 6000)
    income_tax = max(0, tax.income_tax(income) - tax.lito(income) - sapto - bento)
    individual_threshold = 44268 if sapto > 0 else 28011
    levy = min(.02 * income, .1 * max(0, income - individual_threshold))
    if parents == 2 or children:
        threshold = (61623 if sapto > 0 else 47238) + 4338 * children
        family_income = income + partner_income
        if family_income <= threshold:
            levy = 0
        else:
            reduction = max(0, .02 * threshold - .08 * (family_income - threshold))
            levy = max(0, levy - reduction)
    return income - income_tax - levy


def australian_pretax_equivalent(parents, child_ages):
    """Gross up tax-free FTB in the primary carer's hands; under-18s only.

    Solve net(T+x)-net(T)=FTB, retaining taxable benefits and eligibility.
    Report T+x plus the second parent's taxable benefits. This is an income
    equivalent, not the cash benefit or a simulation of working extra hours.
    """
    ages = tuple(child_ages)
    if any(not 0 <= a < 18 for a in ages):
        raise ValueError('The comparison table requires children under 18')
    result = zero_earnings_family(parents, ages)
    partner = result.parent_support / 2 if parents == 2 else 0
    taxable = result.parent_support - partner
    pps = parents == 1 and bool(ages) and min(ages) < 14
    def net(income):
        return parent_net_income(income, parents, len(ages), partner, pps, taxable)
    target = net(taxable) + result.ftba + result.ftbb
    if not result.ftba + result.ftbb:
        return result.parent_support
    low, high = taxable, taxable + 2 * (result.ftba + result.ftbb)
    while net(high) < target:
        high *= 2
    for _ in range(80):
        middle = (low + high) / 2
        if net(middle) < target:
            low = middle
        else:
            high = middle
    return (low + high) / 2 + partner


def part_time_australian_buying_power(parents, child_ages):
    """One parent earns exactly $30,000, evenly through the year; others earn zero.

    July 2025 guide Modules D/E/I: single principal carers with a child under
    16 have a 40% JSP taper; others use the 50%/60% taper. PPS has its own
    child-dependent free area. Both partnered adults still receive allowances,
    so the partner-income test does not reduce the non-earner's payment.
    Family ATI is below the FTB-A threshold and $80,000 supplement cutoff.
    The couple's secondary income remains the non-earner's basic allowance,
    so FTB-B is unchanged. No Working Credits, paid childcare or work expenses.
    """
    ages = tuple(child_ages)
    if any(not 0 <= age < 18 for age in ages):
        raise ValueError('Part-time comparison requires children under 18')
    r = zero_earnings_family(parents, ages)
    earnings = 30000
    youngest = min(ages) if ages else None
    pps = parents == 1 and youngest is not None and youngest < 14
    partner = r.parent_support / 2 if parents == 2 else 0
    maximum = r.parent_support - partner
    if pps:
        free = (224.60 + 24.60 * (len(ages) - 1)) * FORTNIGHTS
        reduction = .4 * max(0, earnings - free)
    elif parents == 1 and youngest is not None and youngest < 16:
        reduction = .4 * max(0, earnings - 150 * FORTNIGHTS)
    else:
        fortnightly = earnings / FORTNIGHTS
        reduction = FORTNIGHTS * (.5 * min(max(0, fortnightly - 150), 106)
                                 + .6 * max(0, fortnightly - 256))
    support = max(0, maximum - reduction)
    taxable = earnings + support
    # These conditions establish that the reused FTB and partner payments
    # remain valid throughout the bounded $30,000 scenario.
    assert support > 0 and taxable + partner < 66722
    if parents == 2:
        assert taxable > partner
    net = parent_net_income(taxable, parents, len(ages), partner, pps, support)
    return net + partner + r.ftba + r.ftbb


def part_time_table_rows():
    """Same age configurations as the opening table, with one $30,000 earner."""
    for parents, children, vmin, vmax, _, _ in household_table_rows():
        configurations = combinations_with_replacement((0, 5, 13, 14, 16, 17.99), children)
        outcomes = [(part_time_australian_buying_power(parents, ages), ages)
                    for ages in configurations]
        yield parents, children, vmin + 30000, vmax + 30000, min(outcomes), max(outcomes)


def household_table_rows():
    """Enumerate every age-policy combination at its threshold representatives.

    Australian amounts are spendable cash after income tax (zero in these cases).
    Multiply gross UBI by 0.528 for buying power at Australian GST-inclusive prices.

    0 represents under-5s, 5 represents ages 5-12, 13 represents the last PPS
    age band, 14-15 can qualify for the large-family JSP exemption, and 16-17
    cannot. School attendance/FTB conditions are met; newborn and multiple-
    birth payments are excluded. The UBI upper end uses the limiting payment as age approaches 18.
    """
    adult_ubi = australian_calibration().adult_ubi
    for parents in (1, 2):
        for children in range(6):
            configurations = list(combinations_with_replacement((0, 5, 13, 14, 16, 17.99), children))
            outcomes = [(zero_earnings_family(parents, ages).australia_cash, ages) for ages in configurations]
            minimum, maximum = min(outcomes), max(outcomes)
            yield parents, children, adult_ubi * (parents + .5 * children), adult_ubi * (parents + children), minimum, maximum


if __name__ == '__main__':
    for parents in (1, 2):
        for n in range(6):
            r = zero_earnings_family(parents, [3, 5, 7, 9, 11][:n])
            print(f'{parents} parents, {n} young children: '
                  f'VoTa ${r.vota_consumption:,.0f}; Australia ${r.australia_consumption:,.0f}')
    for label, ages, ya in [('younger children', [3, 5, 7, 9, 11], True),
                            ('school-age teenagers', [13, 14, 15, 16, 17], True),
                            ('adult students receiving YA', [18, 19, 20, 21, 22], True),
                            ('adult children receiving no payments', [18, 19, 20, 21, 22], False)]:
        r = zero_earnings_family(2, ages, ya)
        print(label, r)
        print(f'Cash: VoTa ${r.vota_cash:,.2f}, Australia ${r.australia_cash:,.2f}; '
              f'after consumption tax: VoTa ${r.vota_consumption:,.2f}, Australia ${r.australia_consumption:,.2f}')
