"""Property checks over every income on a grid, and a search over household choices.

Run: python search.py   (writes results_search.json used by the web page)
"""
import json
import random
from model import *

R = {}
YEAR = CURRENT
y = YEARS[YEAR]

# ------------------------------------------------------------ 1. properties
# Each check runs over every salary from 0 to 20,000,000 in steps of $1,000, for
# 12 household shapes. This is an exhaustive grid, not a proof.
shapes = [
    ("single", Dependants()), ("single, 1 child", Dependants(children=1)),
    ("single, 2 parents 60+ living with you", Dependants(parents60=2, parents60_live_with=2)),
    ("married, 1 income", None), ("married, 1 income, 2 children", None),
    ("married, 1 income, 3 children, 2 parents", None),
]
grid = range(0, 20_000_001, 1_000)
worst_marginal, cliffs, above_standard, checked = 0.0, [], 0, 0
for label, dep in shapes:
    prev = None
    for s in grid:
        if dep is not None:
            t = single_tax(Person(income=s), dep, YEAR)
            ni = Person(income=s).net_income()
        else:
            kids = 0 if "children" not in label else int(label.split(", ")[2][0])
            parents = 2 if "parents" in label else 0
            c = Couple(Person(income=s), Person(), Dependants(children=kids, parents60=parents))
            t = sum(separate(c, "a", "a", "a", YEAR))
            ni = c.a.net_income()
        checked += 1
        if t > standard(ni) + 1e-6:
            above_standard += 1
        if prev is not None:
            m = (t - prev[1]) / (s - prev[0])
            worst_marginal = max(worst_marginal, m)
            if (s - t) < (prev[0] - prev[1]) - 1e-6:
                cliffs.append((label, s))
        prev = (s, t)
R["properties"] = dict(points=checked, shapes=len(shapes), worst_marginal=round(worst_marginal, 4),
                       cliffs=len(cliffs), above_standard=above_standard)
print("properties", R["properties"])

# Marginal rate by income for a single person (for the chart).
curve = []
for s in range(0, 8_000_001, 20_000):
    t0 = single_tax(Person(income=s, mpf=0), year=YEAR, reduce=False)
    t1 = single_tax(Person(income=s + 1_000, mpf=0), year=YEAR, reduce=False)
    curve.append([s, round((t1 - t0) / 1_000, 4), round(t0 / s, 4) if s else 0])
R["marginal_curve_single"] = curve

# ------------------------------------------------- 2. blind search: couples
random.seed(7)
def rand_income():
    r = random.random()
    if r < 0.15: return 0
    if r < 0.30: return random.randrange(20_000, 200_000, 1_000)
    if r < 0.80: return random.randrange(200_000, 1_200_000, 1_000)
    if r < 0.95: return random.randrange(1_200_000, 4_000_000, 10_000)
    return random.randrange(4_000_000, 15_000_000, 10_000)

N = 5_000
households, gains, differ, joint_best, examples = 0, [], 0, 0, []
guideline_wrong = []
for i in range(N):
    a = rand_income()
    b = rand_income() if random.random() < 0.8 else 0
    if a == 0 and b == 0:
        a = random.randrange(200_000, 1_000_000, 1_000)
    dep = Dependants(children=random.choice([0, 0, 1, 1, 2, 2, 3]),
                     parents60=random.choice([0, 0, 0, 1, 2]))
    dep.parents60_live_with = random.randint(0, dep.parents60)
    c = Couple(Person(income=a), Person(income=b), dep)
    opts = list(couple_options(c, YEAR))
    best_choice, best = min(opts, key=lambda kv: kv[1])
    # The guideline for children, then IRD's own comparison with joint assessment
    # (IRD invites the election when it helps, form BIR50E).
    rot = min(couple_rule_of_thumb(c, YEAR), joint(c, YEAR))
    households += 1
    gain = rot - best
    gains.append(gain)
    if gain > 0.5:
        differ += 1
        examples.append(dict(a=a, b=b, children=dep.children, parents=dep.parents60,
                             rule=round(rot), best=round(best), choice=best_choice, gain=round(gain)))
    if best_choice[0] == "joint" and best < min(v for k, v in opts if k[0] == "separate") - 0.5:
        joint_best += 1
examples.sort(key=lambda e: -e["gain"])
gains.sort()
R["couples"] = dict(households=households, options_each=len(opts), differ=differ, joint_best=joint_best,
                    median_gain_when_differs=round(sorted(g for g in gains if g > 0.5)[differ // 2]) if differ else 0,
                    max_gain=round(gains[-1]), examples=examples[:8])
print("couples", {k: v for k, v in R["couples"].items() if k != "examples"})
for e in examples[:5]:
    print("  ", e)

# Why the guideline loses. It asks whether the higher earner "is assessed at the
# standard rate". If they claim every allowance, the allowances themselves can pull
# them just below the standard-rate line, so the guideline says "higher earner",
# yet each allowance there is worth only the small gap to the standard-rate tax.
pulled_off, other = 0, 0
for e in examples:
    hi = Person(income=max(e["a"], e["b"]))
    allow = y["basic"] + e["children"] * y["child"] + e["parents"] * 2 * y["parent60"]
    std_alone = standard(hi.net_income()) <= progressive(hi.net_income() - y["basic"])
    if std_alone:
        pulled_off += 1
    else:
        other += 1
R["couples"]["causes"] = {"higher earner on the standard rate before claiming": pulled_off, "other": other}
print("causes", R["couples"]["causes"])

# ----------------------------- 3. the low-earning spouse (joint assessment)
earner = 900_000
rows = []
for spouse in [0, 1, 20_000, 60_000, 100_000, 145_000, 200_000, 300_000]:
    c = Couple(Person(income=earner, mpf=0), Person(income=spouse, mpf=0), Dependants(children=1))
    sep = min(sum(separate(c, k, k, k, YEAR)) for k in "ab")
    jt = joint(c, YEAR)
    rows.append(dict(spouse=spouse, separate=round(sep), joint=round(jt)))
R["low_earning_spouse"] = dict(earner=earner, rows=rows)
print("low earning spouse", rows)

# ------------------------------------------- 4. rent refund vs paying rent
rows = []
for salary, rent in [(600_000, 180_000), (900_000, 300_000), (1_200_000, 360_000),
                     (2_000_000, 540_000), (3_000_000, 720_000), (6_000_000, 1_200_000)]:
    cash = single_tax(Person(income=salary, rent=rent, mpf=0), year=YEAR)
    refund = single_tax(Person(income=salary - rent, housing_refund=rent, mpf=0), year=YEAR)
    rows.append(dict(package=salary, rent=rent, cash=round(cash), refund=round(refund),
                     saving=round(cash - refund)))
R["housing"] = rows
print("housing", rows)

# ------------------------------------------- 5. landlords: personal assessment
rows = []
for salary, rent, interest in [(400_000, 240_000, 120_000), (800_000, 300_000, 200_000),
                               (1_500_000, 360_000, 250_000), (3_000_000, 600_000, 400_000)]:
    no = landlord_tax(salary, rent, interest, YEAR)
    pa = landlord_tax(salary, rent, interest, YEAR, personal_assessment=True)
    rows.append(dict(salary=salary, rent=rent, interest=interest, without_pa=round(no),
                     with_pa=round(pa), saving=round(no - pa)))
R["landlord"] = rows
print("landlord", rows)

# ---------------------------------------- 6. owner-manager: salary vs dividends
rows = []
for profit in [500_000, 1_000_000, 2_000_000, 3_000_000, 5_000_000, 10_000_000, 30_000_000]:
    best_w, best_t = 0, owner_total_tax(profit, 0, YEAR)
    for w in range(0, profit + 1, 5_000):
        t = owner_total_tax(profit, w, YEAR)
        if t < best_t - 0.01:
            best_w, best_t = w, t
    rows.append(dict(profit=profit, all_dividend=round(owner_total_tax(profit, 0, YEAR)),
                     all_salary=round(owner_total_tax(profit, profit / (1 + MPF_RATE) if profit / 1.05 > 360_000
                                                     else profit / 1.05, YEAR)),
                     best_salary=best_w, best=round(best_t)))
R["owner"] = rows
print("owner", rows)

# ------------------------------------------------- 7. the 60-day cliff
rows = []
for salary in [1_000_000, 2_000_000, 5_000_000]:
    t60 = single_tax(Person(income=non_hk_employment_assessable(salary, 60), mpf=0), year=YEAR)
    t61 = single_tax(Person(income=non_hk_employment_assessable(salary, 61), mpf=0), year=YEAR)
    rows.append(dict(salary=salary, tax60=round(t60), tax61=round(t61), jump=round(t61 - t60)))
R["sixty_day"] = rows
R["sixty_day_curve"] = [[d, round(single_tax(Person(income=non_hk_employment_assessable(2_000_000, d), mpf=0),
                                             year=YEAR))] for d in range(0, 121)]
print("60-day", rows)

# ----------------------------------- 8. single parent who marries
rows = []
for a, b in [(500_000, 400_000), (900_000, 600_000), (1_500_000, 1_000_000)]:
    dep = Dependants(children=1)
    before = single_tax(Person(income=a), dep, YEAR, single_parent=True) + single_tax(Person(income=b), year=YEAR)
    c = Couple(Person(income=a), Person(income=b), dep)
    after = couple_best(c, YEAR)[1]
    rows.append(dict(parent=a, partner=b, unmarried=round(before), married=round(after),
                     cost=round(after - before)))
R["marriage"] = rows
print("marriage", rows)

# ------------------------------- 9. one tax reduction per notice (2025/26)
y2526 = "2025/26"
lost = 0
example = None
random.seed(11)
for _ in range(20_000):
    a = random.randrange(150_000, 700_000, 1_000)
    b = random.randrange(150_000, 400_000, 1_000)
    dep = Dependants(children=random.choice([0, 1, 2, 3]), parents60=random.choice([0, 1, 2]))
    c = Couple(Person(income=a), Person(income=b), dep)
    # before reduction
    saved = YEARS[y2526]["reduction_cap"]
    YEARS[y2526]["reduction_cap"] = 0
    sep0 = min(sum(separate(c, k, k, k, y2526)) for k in "ab")
    jt0 = joint(c, y2526)
    YEARS[y2526]["reduction_cap"] = saved
    sep1 = min(sum(separate(c, k, k, k, y2526)) for k in "ab")
    jt1 = joint(c, y2526)
    if jt0 < sep0 - 0.5 and jt1 >= sep1 - 0.5:
        lost += 1
        if example is None or (sep0 - jt0) > example["joint_saving_before"]:
            example = dict(a=a, b=b, children=dep.children, parents=dep.parents60,
                           joint_saving_before=round(sep0 - jt0), joint_saving_after=round(sep1 - jt1))
R["reduction_per_case"] = dict(tried=20_000, flipped=lost, example=example)
print("reduction per case", R["reduction_per_case"])

# --------------------------- 10. joint assessment and the $5M standard-rate tier
# Matters only when joint beats separate, i.e. one spouse earns less than their
# allowances and the other is far into the standard-rate zone.
c = Couple(Person(income=8_000_000, mpf=0), Person(income=60_000, mpf=0), Dependants(children=3, parents60=2))
R["joint_threshold"] = dict(a=8_000_000, b=60_000, children=3, parents=2,
                            separate=round(min(sum(separate(c, k, k, k, YEAR)) for k in "ab")),
                            joint_5m=round(joint(c, YEAR, 5_000_000)),
                            joint_10m=round(joint(c, YEAR, 10_000_000)))
print("joint threshold", R["joint_threshold"])

# -------------------------------- 11. the 17% plateau
R["plateau"] = dict(single_zone=2_132_500,
                    rate_at_1_5m=round((single_tax(Person(income=1_501_000, mpf=0), year=YEAR, reduce=False)
                                        - single_tax(Person(income=1_500_000, mpf=0), year=YEAR, reduce=False)) / 1000, 3),
                    rate_at_3m=round((single_tax(Person(income=3_001_000, mpf=0), year=YEAR, reduce=False)
                                      - single_tax(Person(income=3_000_000, mpf=0), year=YEAR, reduce=False)) / 1000, 3))
print("plateau", R["plateau"])

json.dump(R, open("results_search.json", "w"), indent=1, default=str)
