"""A small, readable model of Hong Kong salaries tax (Inland Revenue Ordinance, Cap. 112).

Scope: salaries tax and the married-couple options (separate taxation, joint
assessment), the common allowances and deductions, the place-of-residence
"rental value" rule, the s8(1B) 60-day rule for non-Hong Kong employments,
a simple property tax / personal assessment comparison, and corporate
profits tax for an owner-managed company. All money is in HK dollars.

Figures come from IRD's "Allowances, Deductions and Tax Rate Table"
(PAM 61(e), August 2026) and the GovHK tax-rate page. Each year is a
parameter set, so the same code runs the IRD worked examples for 2024/25
and 2025/26 and the current year 2026/27.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from itertools import product

# ---------------------------------------------------------------- parameters

YEARS = {
    "2024/25": dict(basic=132_000, married=264_000, child=130_000, newborn=130_000,
                    parent60=50_000, parent55=25_000, sibling=37_500, disabled=75_000,
                    single_parent=132_000, reduction_cap=1_500, eldercare=100_000),
    "2025/26": dict(basic=132_000, married=264_000, child=130_000, newborn=130_000,
                    parent60=50_000, parent55=25_000, sibling=37_500, disabled=75_000,
                    single_parent=132_000, reduction_cap=3_000, eldercare=100_000),
    # 2026/27: no one-off tax reduction has been announced yet (it would come in
    # the February 2027 Budget), so the cap is 0 here.
    "2026/27": dict(basic=145_000, married=290_000, child=140_000, newborn=140_000,
                    parent60=55_000, parent55=27_500, sibling=37_500, disabled=75_000,
                    single_parent=145_000, reduction_cap=0, eldercare=110_000),
}
CURRENT = "2026/27"

BANDS = [(50_000, 0.02), (50_000, 0.06), (50_000, 0.10), (50_000, 0.14)]
TOP_RATE = 0.17
STD_LOW, STD_HIGH, STD_THRESHOLD = 0.15, 0.16, 5_000_000

MPF_CAP = 18_000            # mandatory contributions deduction (employee side)
MPF_RATE, MPF_INCOME_CAP_MONTH = 0.05, 30_000
HLI_CAP = 100_000           # home loan interest, basic
RENT_CAP = 100_000          # domestic rents, basic
EXTRA_CAP_WITH_CHILD = 20_000  # additional HLI / rent ceiling, child born on/after 25 Oct 2023
SELF_ED_CAP = 100_000
VHIS_CAP = 8_000            # per insured person
TVC_QDAP_CAP = 60_000
DONATION_PCT = 0.35

PROFITS_TIER = 2_000_000
CORP_LOW, CORP_HIGH = 0.0825, 0.165
UNINC_LOW, UNINC_HIGH = 0.075, 0.15
PROPERTY_RATE, PROPERTY_REPAIRS = 0.15, 0.20


# ------------------------------------------------------------ core formulas

def progressive(nci: float) -> float:
    """Tax at progressive rates on net chargeable income (IRO Sch. 1)."""
    tax, left = 0.0, max(0.0, nci)
    for width, rate in BANDS:
        step = min(left, width)
        tax += step * rate
        left -= step
    return tax + left * TOP_RATE


def standard(net_income: float) -> float:
    """Two-tier standard rate on net income before allowances (2024/25 onwards)."""
    ni = max(0.0, net_income)
    return STD_LOW * min(ni, STD_THRESHOLD) + STD_HIGH * max(0.0, ni - STD_THRESHOLD)


def tax_before_reduction(net_income: float, allowances: float) -> float:
    """s13: the lower of progressive tax on (net income - allowances) and standard-rate tax."""
    return min(progressive(net_income - allowances), standard(net_income))


def after_reduction(tax: float, year: str) -> float:
    """One-off 100% tax reduction, capped per case (per notice of assessment)."""
    return max(0.0, tax - YEARS[year]["reduction_cap"])


def mpf_mandatory(salary: float) -> float:
    """Employee mandatory MPF contribution: 5% of relevant income, income capped at 30,000/month."""
    return min(MPF_RATE * salary, MPF_RATE * MPF_INCOME_CAP_MONTH * 12)


# ------------------------------------------------------------------ people

@dataclass
class Person:
    """One taxpayer. Amounts are for the year of assessment.

    income          employment income in cash (salary, bonus)
    outgoings       expenses wholly, exclusively and necessarily incurred (s12(1)(a))
    housing_refund  rent reimbursed by the employer under a rent-refund arrangement
    rent_to_employer rent the employee pays the employer for provided quarters
    mpf, self_ed, donations, vhis, tvc, hli, rent, eldercare: amounts *paid*; caps applied here
    """
    income: float = 0.0
    outgoings: float = 0.0
    housing_refund: float = 0.0
    provided_quarters: bool = False
    rent_to_employer: float = 0.0
    mpf: float | None = None          # None -> mandatory rate on income
    self_ed: float = 0.0
    donations: float = 0.0
    vhis: float = 0.0
    tvc: float = 0.0
    hli: float = 0.0
    rent: float = 0.0
    extra_ceiling: bool = False       # lives with a child born on/after 25 Oct 2023
    disabled: bool = False

    def rental_value(self) -> float:
        """s9(2): 10% of employment income after outgoings, less rent paid to the employer."""
        if not (self.provided_quarters or self.housing_refund):
            return 0.0
        base = self.income - self.outgoings
        return max(0.0, 0.10 * base - self.rent_to_employer)

    def assessable(self) -> float:
        return max(0.0, self.income - self.outgoings) + self.rental_value()

    def deductions(self, claim_hli: bool = True, claim_rent: bool = True) -> float:
        a = self.assessable()
        mpf = mpf_mandatory(self.income) if self.mpf is None else self.mpf
        extra = EXTRA_CAP_WITH_CHILD if self.extra_ceiling else 0
        d = min(mpf, MPF_CAP) + min(self.self_ed, SELF_ED_CAP) + min(self.vhis, VHIS_CAP) \
            + min(self.tvc, TVC_QDAP_CAP)
        if claim_hli:
            d += min(self.hli, HLI_CAP + extra)
        # Domestic rents are not deductible when the employer provides housing.
        if claim_rent and not (self.provided_quarters or self.housing_refund):
            d += min(self.rent, RENT_CAP + extra)
        d = min(d, a)
        d += min(self.donations, DONATION_PCT * max(0.0, a - d))
        return min(d, a)

    def net_income(self, **kw) -> float:
        return max(0.0, self.assessable() - self.deductions(**kw))


@dataclass
class Dependants:
    children: int = 0
    newborns: int = 0
    parents60: int = 0          # dependent parents/grandparents aged 60+
    parents60_live_with: int = 0  # of those, how many live with the claimant all year
    parents55: int = 0
    siblings: int = 0
    disabled: int = 0

    def child_total(self, y: dict) -> float:
        return self.children * y["child"] + self.newborns * y["newborn"]

    def parent_total(self, y: dict) -> float:
        return (self.parents60 + self.parents60_live_with) * y["parent60"] + self.parents55 * y["parent55"]

    def other_total(self, y: dict) -> float:
        return self.siblings * y["sibling"] + self.disabled * y["disabled"]


# ------------------------------------------------------------ single filer

def single_tax(p: Person, dep: Dependants | None = None, year: str = CURRENT,
               single_parent: bool = False, reduce: bool = True) -> float:
    y = YEARS[year]
    dep = dep or Dependants()
    allow = y["basic"] + dep.child_total(y) + dep.parent_total(y) + dep.other_total(y)
    if single_parent and (dep.children or dep.newborns):
        allow += y["single_parent"]
    if p.disabled:
        allow += y["disabled"]
    t = tax_before_reduction(p.net_income(), allow)
    return after_reduction(t, year) if reduce else t


# ------------------------------------------------------------ married couple

@dataclass
class Couple:
    a: Person
    b: Person
    dep: Dependants = field(default_factory=Dependants)


def _person_allowances(y, own_basic: bool, children_here: bool, parents_here: bool,
                       others_here: bool, dep: Dependants, p: Person) -> float:
    allow = y["basic"] if own_basic else 0.0
    if children_here:
        allow += dep.child_total(y)
    if parents_here:
        allow += dep.parent_total(y)
    if others_here:
        allow += dep.other_total(y)
    if p.disabled:
        allow += y["disabled"]
    return allow


def separate(c: Couple, kids_to: str, parents_to: str, others_to: str,
             year: str = CURRENT) -> tuple[float, float]:
    """Separate taxation. If one spouse has no income, the other takes the married
    person's allowance (s29) instead of the basic allowance."""
    y = YEARS[year]
    a_ni, b_ni = c.a.net_income(), c.b.net_income()
    out = []
    for who, p, ni, other in (("a", c.a, a_ni, c.b), ("b", c.b, b_ni, c.a)):
        allow = _person_allowances(y, True, kids_to == who, parents_to == who,
                                   others_to == who, c.dep, p)
        if other.assessable() == 0:
            allow += y["married"] - y["basic"]
        t = tax_before_reduction(ni, allow) if p.assessable() > 0 else 0.0
        out.append(after_reduction(t, year))
    return out[0], out[1]


def joint(c: Couple, year: str = CURRENT, threshold_per_couple: float = STD_THRESHOLD) -> float:
    """Joint assessment (s10): incomes and allowances aggregated, married person's
    allowance replaces two basic allowances, one notice and so one tax-reduction cap.

    threshold_per_couple: where the 15% standard rate stops for the couple. The
    published IRD material does not say whether it is $5M for the couple or $5M each.
    """
    y = YEARS[year]
    ni = c.a.net_income() + c.b.net_income()
    allow = y["married"] + c.dep.child_total(y) + c.dep.parent_total(y) + c.dep.other_total(y)
    allow += y["disabled"] * (c.a.disabled + c.b.disabled)
    std = STD_LOW * min(ni, threshold_per_couple) + STD_HIGH * max(0.0, ni - threshold_per_couple)
    t = min(progressive(ni - allow), std)
    return after_reduction(t, year)


def couple_options(c: Couple, year: str = CURRENT):
    """Every lawful choice the couple can make, with its total tax."""
    for kids, parents, others in product("ab", repeat=3):
        ta, tb = separate(c, kids, parents, others, year)
        yield ("separate", kids, parents, others), ta + tb
    yield ("joint",), joint(c, year)


def couple_best(c: Couple, year: str = CURRENT):
    return min(couple_options(c, year), key=lambda kv: kv[1])


def couple_rule_of_thumb(c: Couple, year: str = CURRENT) -> float:
    """What a couple does if they follow IRD's published guideline for children
    (higher earner claims, unless that spouse is on the standard rate) and give
    parents to the same spouse, and do not elect joint assessment."""
    y = YEARS[year]
    hi, lo = ("a", "b") if c.a.net_income() >= c.b.net_income() else ("b", "a")
    hi_p = c.a if hi == "a" else c.b
    allow_hi = y["basic"] + c.dep.child_total(y) + c.dep.parent_total(y) + c.dep.other_total(y)
    on_std = standard(hi_p.net_income()) <= progressive(hi_p.net_income() - allow_hi)
    who = lo if (on_std and (c.a if lo == "a" else c.b).assessable() > 0) else hi
    ta, tb = separate(c, who, who, who, year)
    return ta + tb


# ---------------------------------------------- s8(1B): the 60-day rule

def non_hk_employment_assessable(salary: float, hk_days: int, days_in_year: int = 365) -> float:
    """Non-Hong Kong employment: only income for services rendered in Hong Kong is
    taxed, apportioned by days (s8(1A)(b)). s8(1B): if visits total 60 days or less,
    those services are disregarded."""
    if hk_days <= 60:
        return 0.0
    return salary * hk_days / days_in_year


# ------------------------------------------------- property tax vs PA

def property_tax(rent_received: float, rates_paid: float = 0.0) -> float:
    nav = max(0.0, rent_received - rates_paid) * (1 - PROPERTY_REPAIRS)
    return PROPERTY_RATE * nav


def landlord_tax(salary: float, rent_received: float, mortgage_interest: float,
                 year: str = CURRENT, personal_assessment: bool = False) -> float:
    """A single employee who lets one flat. Without PA: salaries tax + property tax.
    With PA (s41-42): property income is added at net assessable value, mortgage
    interest on the let property is deductible up to that value, and allowances
    and progressive rates apply to the total."""
    y = YEARS[year]
    me = Person(income=salary)
    if not personal_assessment:
        return after_reduction(tax_before_reduction(me.net_income(), y["basic"]), year) \
            + property_tax(rent_received)
    nav = rent_received * (1 - PROPERTY_REPAIRS)
    total = me.net_income() + max(0.0, nav - mortgage_interest)
    return after_reduction(tax_before_reduction(total, y["basic"]), year)


# ----------------------------------------- owner-managed company

def profits_tax(profit: float, low: float = CORP_LOW, high: float = CORP_HIGH) -> float:
    p = max(0.0, profit)
    return low * min(p, PROFITS_TIER) + high * max(0.0, p - PROFITS_TIER)


def owner_total_tax(company_profit_before_pay: float, salary: float, year: str = CURRENT) -> float:
    """Single owner-director. Salary is deductible to the company (with the employer's
    5% MPF, capped), taxed to the owner as salaries tax. What is left is taxed at the
    two-tier corporate rate and paid out as dividends, which Hong Kong does not tax."""
    employer_mpf = mpf_mandatory(salary)
    company = profits_tax(company_profit_before_pay - salary - employer_mpf)
    me = Person(income=salary)
    personal = single_tax(me, year=year) if salary > 0 else 0.0
    return company + personal
