import csv, json, os
from decimal import Decimal as D, ROUND_HALF_UP
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = HERE
inp = {i["name"]: D(i["value"]) for i in json.load(open(os.path.join(HERE, "cleaner-employment-cost-inputs.json")))["inputs"] if i["value"] != "n/a"}
RATE, LEAVE = inp["nlw_21_plus"], inp["statutory_leave_weeks"]
THR, NIC, EA = inp["employer_nic_threshold"], inp["employer_nic_rate"], inp["employment_allowance"]
PR, QL, QU = inp["employer_pension_rate"], inp["qualifying_earnings_lower"], inp["qualifying_earnings_upper"]
WEEKS = D(52)
def p(x): return x.quantize(D("0.01"), rounding=ROUND_HALF_UP)
rows = []
for h in [D(x) for x in ["8", "16", "24", "30", "37.5"]]:
    pay = RATE * h * WEEKS
    nic = max(D(0), pay - THR) * NIC
    pension = D(0) if h == 8 else PR * (min(pay, QU) - QL)
    paid_h, leave_h = h * WEEKS, h * (WEEKS - LEAVE)
    no_ea, ea = pay + nic + pension, pay + max(D(0), nic - EA) + pension
    rows.append({"weekly_hours": f"{h.normalize():f}", "annual_pay": p(pay), "employer_nic": p(nic), "employer_pension": p(pension),
      "annual_cost_no_ea": p(no_ea), "annual_cost_with_ea": p(ea),
      "cost_per_paid_hour_no_ea": p(no_ea / paid_h), "cost_per_paid_hour_with_ea": p(ea / paid_h),
      "cost_per_hour_after_leave_no_ea": p(no_ea / leave_h), "cost_per_hour_after_leave_with_ea": p(ea / leave_h)})
r8 = rows[0]; assert r8["employer_pension"] == 0
assert rows[1]["annual_pay"] > 10000
exp = {"8":("12.81","12.71","14.36","14.24"),"16":("13.87","12.87","15.55","14.42"),"24":("14.25","12.94","15.97","14.50"),"30":("14.40","12.97","16.13","14.54"),"37.5":("14.52","13.00","16.27","14.56")}
for r in rows:
    got = tuple(str(r[k]) for k in ("cost_per_paid_hour_no_ea","cost_per_paid_hour_with_ea","cost_per_hour_after_leave_no_ea","cost_per_hour_after_leave_with_ea"))
    assert got == exp[r["weekly_hours"]], (r["weekly_hours"], got)
keys = list(rows[0])
with open(os.path.join(REPO, "cleaner-employment-cost-per-hour.csv"), "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=keys, lineterminator="\n"); w.writeheader(); w.writerows({k: str(v) for k, v in r.items()} for r in rows)
json.dump([{k: str(v) for k, v in r.items()} for r in rows], open(os.path.join(REPO, "cleaner-employment-cost-data.json"), "w"), indent=1)
with open(os.path.join(HERE, "cleaner-employment-cost-compute-output.txt"), "w") as f:
    f.write("\t".join(keys) + "\n")
    for r in rows: f.write("\t".join(str(r[k]) for k in keys) + "\n")
print(open(os.path.join(HERE, "cleaner-employment-cost-compute-output.txt")).read())
