"""The synthetic MGA book (DESIGN-bordereaux.md sections 2 and 3): one seed, every table, as lists of dicts.

Usage: python -B -m bordereaux.book <out-dir> [seed]
All money is held in integer cents, so sums are exact. Every rule is an assumption of this study, not a description of
any market. It reads nothing from the rest of the study. The same seed gives byte-identical CSV files.
"""
from __future__ import annotations

import csv
import datetime as dt
import hashlib
import io
import math
import random
import sys
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path

D = dt.date
SEED = 61409
FIRST = D(2024, 7, 1)
LAST = D(2026, 9, 30)
CUT = D(2025, 12, 31)
LINES = ("PROP", "GL", "PL")
BINDING = {"PROP": ("0.25", 500_000_000), "GL": ("0.275", 200_000_000), "PL": ("0.30", 300_000_000)}   # rate, max limit in cents
LIMITS = {"PROP": [250_000, 500_000, 1_000_000, 2_000_000, 3_000_000, 5_000_000], "GL": [500_000, 1_000_000, 2_000_000],
          "PL": [250_000, 500_000, 1_000_000, 2_000_000, 3_000_000]}
OVER_AUTHORITY = {"PROP": 7_500_000, "GL": 3_000_000, "PL": 5_000_000}
LINE_RATE = {"PROP": 0.0018, "GL": 0.0022, "PL": 0.0045}
COVERAGES = {"PROP": ["BLDG", "CONT", "BI"], "GL": ["PREM", "PROD"], "PL": ["EO"]}
CLAIM_P = {"PROP": 0.12, "GL": 0.10, "PL": 0.06}
BATCH_QUARTERS = {(2024, 3): 1, (2024, 4): 2, (2025, 1): 3, (2025, 2): 4, (2025, 3): 5}

COV_CODE = {"BLDG": "10", "CONT": "11", "BI": "12", "PREM": "20", "PROD": "21", "EO": "30"}
LOB_CODE = {"PROP": "1", "GL": "2", "PL": "3"}
TXN_CODE = {"NB": "1", "REN": "2", "END": "3", "CAN": "4", "REI": "5"}
PLAN_CODE = {"ANNUAL": "A", "QUARTERLY": "Q", "MONTHLY": "M"}
CCY_CODE = {"USD": "840", "CAD": "124"}
STATUS_CODE = {"ACTIVE": "A", "CANCELLED": "C", "EXPIRED": "E", "PENDING": "P"}
CLAIM_STATUS_CODE = {"OPEN": "O", "CLOSED": "C"}
HIST_CODE = {"RESERVE": "1", "PAY_IND": "2", "PAY_EXP": "3", "RECOVERY": "4", "CLOSE": "5", "REOPEN": "6"}

COLUMNS = {
    "pas_brokers": ["broker_id", "commission_rate", "active_flag"],
    "pas_policies": ["policy_id", "insured_id", "broker_id", "line_of_business", "currency", "effective_date", "expiry_date",
                     "billing_plan", "status", "status_at_conversion", "cancel_effective_date", "prior_policy_id",
                     "source_system", "conversion_batch_id"],
    "pas_coverages": ["coverage_id", "policy_id", "coverage_code", "limit_amount", "deductible", "referral_flag",
                      "source_system", "conversion_batch_id"],
    "pas_transactions": ["transaction_id", "policy_id", "coverage_id", "transaction_type", "effective_date", "booked_date",
                         "written_premium", "annualized_change", "limit_after", "source_system", "conversion_batch_id"],
    "billing_instalments": ["instalment_id", "transaction_id", "policy_id", "due_date", "amount", "paid_date", "source_system",
                            "conversion_batch_id"],
    "broker_commissions": ["commission_id", "transaction_id", "broker_id", "rate", "amount", "source_system",
                           "conversion_batch_id"],
    "claims": ["claim_id", "policy_id", "coverage_id", "loss_date", "reported_date", "status", "source_system",
               "conversion_batch_id"],
    "claim_transactions": ["claim_txn_id", "claim_id", "txn_type", "booked_date", "amount", "source_system",
                           "conversion_batch_id"],
    "binding_terms": ["line_of_business", "mga_commission_rate", "max_limit"],
    "fx_rates": ["currency", "month", "usd_per_unit"],
    "bdx_premium": ["bdx_month", "line_no", "transaction_id", "policy_id", "coverage_id", "coverage_code", "line_of_business",
                    "broker_id", "transaction_type", "effective_date", "term_expiry", "booked_date", "currency", "gross_premium",
                    "fx_rate", "gross_premium_usd", "broker_commission_usd", "mga_commission_usd", "net_due_usd"],
    "bdx_risk": ["bdx_month", "policy_id", "coverage_id", "coverage_code", "line_of_business", "effective_date", "expiry_date",
                 "currency", "limit_amount", "annualized_premium", "referral_flag"],
    "bdx_claims": ["bdx_month", "claim_id", "policy_id", "coverage_id", "loss_date", "reported_date", "status", "currency",
                   "paid_in_month", "paid_to_date", "reserve_outstanding", "recovered_to_date", "incurred", "fx_rate",
                   "paid_in_month_usd", "reserve_usd", "incurred_usd"],
    "bdx_cover": ["bdx_month", "premium_lines", "gross_premium_usd", "broker_commission_usd", "mga_commission_usd", "net_due_usd",
                  "risk_lines", "claim_lines", "paid_in_month_usd", "reserve_usd"],
    "leg_policy_master": ["LEG_POL_NO", "INSURED_REF", "AGENT_CD", "LOB_CD", "CCY_CD", "EFF_DT", "EXP_DT", "PLAN_CD", "STATUS_CD",
                          "ANNUAL_PREM_CENTS", "UNEARNED_CENTS", "PRIOR_POL_NO"],
    "leg_coverages": ["LEG_POL_NO", "COV_CD", "LIMIT_CENTS", "DED_CENTS", "REFER_FLG"],
    "leg_premium_history": ["LEG_TXN_NO", "LEG_POL_NO", "COV_CD", "TXN_CD", "EFF_DT", "BOOK_DT", "PREM_CENTS", "ANNUAL_CHG_CENTS"],
    "leg_commissions": ["LEG_TXN_NO", "AGENT_CD", "RATE_PCT", "COMM_CENTS"],
    "leg_claims": ["LEG_CLM_NO", "LEG_POL_NO", "COV_CD", "LOSS_DT", "RPT_DT", "STATUS_CD", "PAID_CENTS", "RES_CENTS", "RECOV_CENTS"],
    "leg_claim_history": ["LEG_HIST_NO", "LEG_CLM_NO", "HIST_CD", "BOOK_DT", "AMOUNT_CENTS"],
    "leg_open_instalments": ["LEG_INST_NO", "LEG_TXN_NO", "DUE_DT", "AMOUNT_CENTS"],
    "leg_control_report": ["MEASURE", "LOB_CD", "CCY_CD", "ROW_COUNT", "AMOUNT_CENTS"],
    "conv_crosswalk": ["entity", "legacy_key", "target_key", "batch_id"],
    "conv_exclusions": ["legacy_key", "reason"],
    "conv_code_map": ["code_set", "legacy_code", "target_code"],
}


def half_up(x: Decimal) -> int:
    return int(x.quantize(Decimal(1), rounding=ROUND_HALF_UP))


def money(cents: int | None) -> str:
    if cents is None:
        return ""
    sign = "-" if cents < 0 else ""
    c = abs(cents)
    return f"{sign}{c // 100}.{c % 100:02d}"


def iso(d: dt.date | None) -> str:
    return d.isoformat() if d else ""


def ymd(d: dt.date | None) -> str:
    return d.strftime("%Y%m%d") if d else ""


def month_of(d: dt.date) -> str:
    return d.strftime("%Y-%m")


def months() -> list[dt.date]:
    out, m = [], FIRST
    while m <= LAST:
        out.append(m)
        m = D(m.year + m.month // 12, m.month % 12 + 1, 1)
    return out


def month_end(m: dt.date) -> dt.date:
    return D(m.year + m.month // 12, m.month % 12 + 1, 1) - dt.timedelta(days=1)


def fx_table() -> dict[tuple[str, str], Decimal]:
    out = {}
    for i, m in enumerate(months()):
        out[("USD", month_of(m))] = Decimal("1.000000")
        out[("CAD", month_of(m))] = Decimal(f"{0.73 * (1 + 0.03 * math.sin(2 * math.pi * i / 14)):.6f}")
    return out


def to_usd(cents: int, rate: Decimal) -> int:
    return half_up(Decimal(cents) * rate)


def add(d: dt.date, days: int) -> dt.date:
    return d + dt.timedelta(days=days)


def booked_lag(rng: random.Random) -> int:
    return rng.randint(30, 90) if rng.random() < 0.08 else rng.randint(0, 10)


def build_terms(rng: random.Random) -> list[dict]:
    """Every policy term with its coverages and premium events, before ids are assigned to events."""
    terms: list[dict] = []
    queue: list[tuple[dt.date, int, dict | None]] = []
    n = 0
    for m in months():
        factor = 1.5 if m.month in (1, 7) else 1.0
        count = int(round(34 * factor * rng.uniform(0.85, 1.15)))
        days = (month_end(m) - m).days + 1
        for _ in range(count):
            n += 1
            queue.append((add(m, rng.randrange(days)), n, None))
    queue.sort(key=lambda x: (x[0], x[1]))
    seq = 0
    i = 0
    while i < len(queue):
        eff, _, prior = queue[i]
        i += 1
        seq += 1
        term = new_term(rng, seq, eff, prior)
        if term is None:
            continue
        terms.append(term)
        expiry = term["expiry"]
        cancelled = term["can"] is not None and term["rei"] is None
        if not cancelled and expiry <= LAST and rng.random() < 0.8:
            item = (expiry, n + len(queue) + 1, term)
            j = i
            while j < len(queue) and queue[j][0] <= expiry:
                j += 1
            queue.insert(j, item)
    return terms


def new_term(rng: random.Random, seq: int, eff: dt.date, prior: dict | None) -> dict | None:
    if prior is None:
        line = rng.choices(LINES, (0.45, 0.35, 0.20))[0]
        currency = rng.choices(("USD", "CAD"), (0.85, 0.15))[0]
        plan = rng.choices(("ANNUAL", "QUARTERLY", "MONTHLY"), (0.55, 0.25, 0.20))[0]
        insured = f"INS-{seq:06d}"
        broker = None
        codes = COVERAGES[line][:rng.randint(1, len(COVERAGES[line]))]
        covs = []
        for code in codes:
            referred = rng.random() < 0.01
            limit = OVER_AUTHORITY[line] if referred else rng.choice(LIMITS[line])
            annual = half_up(Decimal(limit * 100) * Decimal(str(LINE_RATE[line])) * Decimal(str(round(rng.lognormvariate(0, 0.35), 6))))
            covs.append({"code": code, "limit": limit * 100, "ded": rng.choice((1000, 2500, 5000, 10000)) * 100,
                         "referral": "Y" if referred else "N", "annual": annual})
        kind = "NB"
        lag = rng.randint(6, 20) if rng.random() < 0.10 else rng.randint(0, 5)
    else:
        line, currency, plan, insured, broker = prior["line"], prior["currency"], prior["plan"], prior["insured"], prior["broker"]
        factor = Decimal(str(round(rng.uniform(1.00, 1.12), 6)))
        covs = [{"code": c["code"], "limit": c["limit_now"], "ded": c["ded"], "referral": c["referral"],
                 "annual": half_up(Decimal(c["annual_now"]) * factor)} for c in prior["covs"]]
        kind = "REN"
        lag = rng.randint(-15, 3)
    expiry = add(eff, 365)
    booked = add(eff, lag)
    term = {"seq": seq, "line": line, "currency": currency, "plan": plan, "insured": insured, "broker": broker, "eff": eff,
            "expiry": expiry, "covs": covs, "prior": prior, "kind": kind, "booked": booked, "ends": [], "can": None, "rei": None,
            "claims": [], "txns": []}
    if booked > LAST:
        return None
    for c in covs:
        c["annual_now"] = c["annual"]
        c["limit_now"] = c["limit"]
    # cancellation first, so endorsements stay before it
    can_eff = can_booked = None
    if rng.random() < 0.09:
        can_eff = eff if rng.random() < 0.10 else add(eff, rng.randint(1, 364))
        can_booked = max(add(can_eff, booked_lag(rng)), booked)
    end_until = can_eff or expiry
    n_ends = rng.choices((0, 1, 2), (0.80, 0.14, 0.06))[0]
    for _ in range(n_ends):
        span = (end_until - eff).days - 1
        if span < 1:
            continue
        e_eff = add(eff, rng.randint(1, span))
        e_booked = max(add(e_eff, booked_lag(rng)), booked)
        if can_booked and e_booked >= can_booked:
            continue
        cov = rng.choice(covs)
        term["ends"].append({"eff": e_eff, "booked": e_booked, "cov": cov, "limit_only": rng.random() < 0.05,
                             "pct": rng.choice((-1, 1)) * rng.uniform(0.05, 0.25), "bump": rng.choice((1.25, 1.5))})
    term["ends"].sort(key=lambda x: x["booked"])
    for e in term["ends"]:
        cov = e["cov"]
        if e["limit_only"]:
            e["premium"] = e["annual_change"] = 0
            cov["limit_now"] = int(cov["limit_now"] * e["bump"]) // 100 * 100
            authority = BINDING[line][1]
            if cov["limit_now"] > authority and cov["referral"] != "Y":
                cov["limit_now"] = authority
        else:
            e["annual_change"] = half_up(Decimal(cov["annual_now"]) * Decimal(str(round(e["pct"], 6))))
            remaining = (expiry - e["eff"]).days
            e["premium"] = half_up(Decimal(e["annual_change"]) * remaining / 365)
            cov["annual_now"] += e["annual_change"]
        e["limit_after"] = cov["limit_now"]
    if can_eff:
        remaining = (expiry - can_eff).days
        term["can"] = {"eff": can_eff, "booked": can_booked,
                       "rows": [{"cov": c, "annual_change": -c["annual_now"],
                                 "premium": -half_up(Decimal(c["annual_now"]) * remaining / 365)} for c in covs]}
        if rng.random() < 0.15:
            term["rei"] = {"eff": can_eff, "booked": add(can_booked, rng.randint(1, 30))}
        if can_booked > LAST:
            term["can"] = term["rei"] = None
        elif term["rei"] and term["rei"]["booked"] > LAST:
            term["rei"] = None
    return term


def claim_events(rng: random.Random, reported: dt.date, limit: int, line: str) -> list[dict]:
    """Movements of one claim in time order, in cents; reserve moves are explicit rows, so reserve = sum of RESERVE rows."""
    reserve = max(50_000, min(int(limit * rng.uniform(0.002, 0.03) * rng.lognormvariate(0, 0.5)), limit // 2))
    ev = [{"t": "RESERVE", "d": reported, "a": reserve}]
    d = reported
    steps = ["CHG"] * rng.randint(0, 3) + ["PAY"] * rng.randint(0 if rng.random() < 0.2 else 1, 4)
    rng.shuffle(steps)
    bal = reserve

    def pay(day, share):
        nonlocal bal
        amount = max(10_000, int(bal * share)) if bal > 10_000 else 10_000
        kind = "PAY_EXP" if rng.random() < 0.25 else "PAY_IND"
        ev.append({"t": kind, "d": day, "a": amount})
        drop = min(amount, bal)
        if drop:
            ev.append({"t": "RESERVE", "d": day, "a": -drop})
            bal -= drop

    for s in steps:
        d = add(d, rng.randint(10, 90))
        if s == "CHG":
            change = int(bal * rng.uniform(-0.3, 0.5))
            if change:
                ev.append({"t": "RESERVE", "d": d, "a": change})
                bal += change
        else:
            pay(d, rng.uniform(0.2, 0.7))
    d = add(d, rng.randint(10, 90))
    if bal:
        ev.append({"t": "RESERVE", "d": d, "a": -bal})
        bal = 0
    ev.append({"t": "CLOSE", "d": d, "a": 0})
    if rng.random() < 0.08:
        d = add(d, rng.randint(35, 120))
        again = max(50_000, reserve // 3)
        ev.append({"t": "REOPEN", "d": d, "a": 0})
        ev.append({"t": "RESERVE", "d": d, "a": again})
        bal = again
        d = add(d, rng.randint(35, 60))
        pay(d, 0.5)
        d = add(d, rng.randint(35, 60))
        if bal:
            ev.append({"t": "RESERVE", "d": d, "a": -bal})
            bal = 0
        ev.append({"t": "CLOSE", "d": d, "a": 0})
    paid = sum(x["a"] for x in ev if x["t"] in ("PAY_IND", "PAY_EXP"))
    if line == "PROP" and paid and rng.random() < 0.06:
        ev.append({"t": "RECOVERY", "d": add(d, rng.randint(30, 90)), "a": max(1_000, int(paid * rng.uniform(0.1, 0.5)))})
    return ev


def build(seed: int = SEED) -> dict[str, list[dict]]:
    rng = random.Random(seed)
    fx = fx_table()
    brokers = [{"broker_id": f"BRK-{i:03d}", "rate": rng.choice(("0.10", "0.125", "0.15"))} for i in range(1, 25)]
    terms = build_terms(rng)
    for t in terms:
        if t["broker"] is None:
            t["broker"] = rng.choice(brokers)["broker_id"]
    rate_of = {b["broker_id"]: b["rate"] for b in brokers}
    t_out: dict[str, list[dict]] = {k: [] for k in COLUMNS}
    t_out["pas_brokers"] = [{"broker_id": b["broker_id"], "commission_rate": b["rate"], "active_flag": "Y"} for b in brokers]
    t_out["binding_terms"] = [{"line_of_business": k, "mga_commission_rate": v[0], "max_limit": money(v[1])} for k, v in BINDING.items()]
    t_out["fx_rates"] = [{"currency": c, "month": m, "usd_per_unit": str(r)} for (c, m), r in sorted(fx.items())]

    # ids: policies and coverages in term order; premium transactions numbered in booked order
    legacy_numbers = list(range(1, len(terms) * 2 + 50))
    rng.shuffle(legacy_numbers)
    leg_iter = iter(legacy_numbers)
    coverages = []
    events = []
    for t in terms:
        t["policy_id"] = f"POL-{t['seq']:06d}"
        t["legacy"] = f"LP{700000 + next(leg_iter)}"
        q = (t["eff"].year, (t["eff"].month - 1) // 3 + 1)
        t["batch"] = f"BATCH-{BATCH_QUARTERS.get(q, 6)}"
        for c in t["covs"]:
            c["coverage_id"] = f"COV-{len(coverages) + 1:06d}"
            c["policy"] = t
            coverages.append(c)
            events.append({"term": t, "cov": c, "type": t["kind"], "eff": t["eff"], "booked": t["booked"], "premium": c["annual"],
                           "annual": c["annual"], "limit": c["limit"]})
        for e in t["ends"]:
            events.append({"term": t, "cov": e["cov"], "type": "END", "eff": e["eff"], "booked": e["booked"], "premium": e["premium"],
                           "annual": e["annual_change"], "limit": e["limit_after"]})
        if t["can"]:
            for row in t["can"]["rows"]:
                events.append({"term": t, "cov": row["cov"], "type": "CAN", "eff": t["can"]["eff"], "booked": t["can"]["booked"],
                               "premium": row["premium"], "annual": row["annual_change"], "limit": row["cov"]["limit_now"]})
                if t["rei"]:
                    events.append({"term": t, "cov": row["cov"], "type": "REI", "eff": t["rei"]["eff"], "booked": t["rei"]["booked"],
                                   "premium": -row["premium"], "annual": -row["annual_change"], "limit": row["cov"]["limit_now"]})
    events = [e for e in events if e["booked"] <= LAST]
    order = {"NB": 0, "REN": 0, "END": 1, "CAN": 2, "REI": 3}
    events.sort(key=lambda e: (e["booked"], e["term"]["seq"], order[e["type"]], e["cov"]["coverage_id"], e["eff"]))
    for i, e in enumerate(events, 1):
        e["id"] = f"TXN-{i:07d}"
        e["legacy_id"] = f"LT{500000 + i * 3}"
    convert = {t["seq"] for t in terms if t["booked"] <= CUT}

    for t in terms:
        converted = t["seq"] in convert
        src = "LEGACY" if converted else "NEW"
        cancelled = t["can"] is not None and t["rei"] is None
        status = "CANCELLED" if cancelled else ("EXPIRED" if t["expiry"] <= LAST else "ACTIVE")
        conv_status = ""
        if converted:
            cut_cancelled = t["can"] is not None and t["can"]["booked"] <= CUT and not (t["rei"] and t["rei"]["booked"] <= CUT)
            conv_status = "CANCELLED" if cut_cancelled else ("EXPIRED" if t["expiry"] <= CUT else ("PENDING" if t["eff"] > CUT else "ACTIVE"))
        t["conv_status"] = conv_status
        t_out["pas_policies"].append({
            "policy_id": t["policy_id"], "insured_id": t["insured"], "broker_id": t["broker"], "line_of_business": t["line"],
            "currency": t["currency"], "effective_date": iso(t["eff"]), "expiry_date": iso(t["expiry"]), "billing_plan": t["plan"],
            "status": status, "status_at_conversion": conv_status, "cancel_effective_date": iso(t["can"]["eff"]) if cancelled else "",
            "prior_policy_id": t["prior"]["policy_id"] if t["prior"] else "", "source_system": src,
            "conversion_batch_id": t["batch"] if converted else ""})
        for c in t["covs"]:
            t_out["pas_coverages"].append({
                "coverage_id": c["coverage_id"], "policy_id": t["policy_id"], "coverage_code": c["code"], "limit_amount": money(c["limit"]),
                "deductible": money(c["ded"]), "referral_flag": c["referral"], "source_system": src,
                "conversion_batch_id": t["batch"] if converted else ""})

    # premium, commission, instalments
    inst_no = 0
    instalments_by_event = {}
    for e in events:
        t, c = e["term"], e["cov"]
        src = "LEGACY" if e["booked"] <= CUT else "NEW"
        batch = t["batch"] if src == "LEGACY" else ""
        t_out["pas_transactions"].append({
            "transaction_id": e["id"], "policy_id": t["policy_id"], "coverage_id": c["coverage_id"], "transaction_type": e["type"],
            "effective_date": iso(e["eff"]), "booked_date": iso(e["booked"]), "written_premium": money(e["premium"]),
            "annualized_change": money(e["annual"]), "limit_after": money(e["limit"]), "source_system": src, "conversion_batch_id": batch})
        rate = Decimal(rate_of[t["broker"]])
        e["commission"] = half_up(Decimal(e["premium"]) * rate)
        t_out["broker_commissions"].append({
            "commission_id": e["id"].replace("TXN", "COM"), "transaction_id": e["id"], "broker_id": t["broker"], "rate": str(rate),
            "amount": money(e["commission"]), "source_system": src, "conversion_batch_id": batch})
        if e["premium"] == 0:
            continue
        n = 1
        if e["type"] in ("NB", "REN"):
            n = {"ANNUAL": 1, "QUARTERLY": 4, "MONTHLY": 12}[t["plan"]]
        base = int(e["premium"] / n)
        step = 365 // n
        rows = []
        for k in range(n):
            amount = base if k < n - 1 else e["premium"] - base * (n - 1)
            due = max(add(e["eff"], k * step), e["booked"])
            paid = add(due, rng.randint(0, 45))
            inst_no += 1
            row = {"instalment_id": f"INS-{inst_no:07d}", "transaction_id": e["id"], "policy_id": t["policy_id"], "due_date": iso(due),
                   "amount": money(amount), "paid_date": iso(paid) if paid <= LAST else "", "source_system": src,
                   "conversion_batch_id": batch}
            t_out["billing_instalments"].append(row)
            rows.append((row, due, paid, amount))
        instalments_by_event[e["id"]] = rows

    # claims
    claim_rows = []
    for t in terms:
        if rng.random() >= CLAIM_P[t["line"]]:
            continue
        end = t["expiry"]
        if t["can"] is not None and t["rei"] is None:
            end = t["can"]["eff"]
        span = max((end - t["eff"]).days - 1, 0)
        loss = add(t["eff"], rng.randint(0, span))
        reported = add(loss, rng.randint(0, 120 if t["line"] == "PL" else 30))
        cov = rng.choice(t["covs"])
        if reported > LAST:
            continue
        claim_rows.append({"term": t, "cov": cov, "loss": loss, "reported": reported, "ev": [x for x in claim_events(rng, reported, cov["limit"], t["line"])
                                                                                               if x["d"] <= LAST]})
    claim_rows.sort(key=lambda c: (c["reported"], c["term"]["seq"]))
    ctx_no = 0
    for i, c in enumerate(claim_rows, 1):
        c["id"] = f"CLM-{i:05d}"
        c["legacy_id"] = f"LC{300000 + i * 7}"
        t = c["term"]
        src = "LEGACY" if c["reported"] <= CUT else "NEW"
        c["src"] = src
        status = "OPEN"
        for x in c["ev"]:
            if x["t"] == "CLOSE":
                status = "CLOSED"
            elif x["t"] == "REOPEN":
                status = "OPEN"
        t_out["claims"].append({"claim_id": c["id"], "policy_id": t["policy_id"], "coverage_id": c["cov"]["coverage_id"],
                                "loss_date": iso(c["loss"]), "reported_date": iso(c["reported"]), "status": status, "source_system": src,
                                "conversion_batch_id": t["batch"] if src == "LEGACY" else ""})
        for x in c["ev"]:
            ctx_no += 1
            x["id"] = f"CTX-{ctx_no:07d}"
            x["legacy_id"] = f"LH{100000 + ctx_no * 3}"
            xsrc = "LEGACY" if x["d"] <= CUT else "NEW"
            t_out["claim_transactions"].append({"claim_txn_id": x["id"], "claim_id": c["id"], "txn_type": x["t"], "booked_date": iso(x["d"]),
                                                "amount": money(x["a"]), "source_system": xsrc,
                                                "conversion_batch_id": t["batch"] if xsrc == "LEGACY" else ""})

    build_bordereaux(t_out, events, terms, claim_rows, fx, rate_of)
    build_legacy(t_out, rng, terms, events, claim_rows, instalments_by_event, convert)
    return t_out


def build_bordereaux(t_out, events, terms, claim_rows, fx, rate_of) -> None:
    by_month: dict[str, list[dict]] = {}
    for e in events:
        by_month.setdefault(month_of(e["booked"]), []).append(e)
    cover = {}
    for m in months():
        key = month_of(m)
        lines = by_month.get(key, [])
        gross = broker = mga = net = 0
        for no, e in enumerate(lines, 1):
            t, c = e["term"], e["cov"]
            rate = fx[(t["currency"], key)]
            g = to_usd(e["premium"], rate)
            b = to_usd(e["commission"], rate)
            k = half_up(Decimal(g) * Decimal(BINDING[t["line"]][0]))
            t_out["bdx_premium"].append({
                "bdx_month": key, "line_no": str(no), "transaction_id": e["id"], "policy_id": t["policy_id"], "coverage_id": c["coverage_id"],
                "coverage_code": c["code"], "line_of_business": t["line"], "broker_id": t["broker"], "transaction_type": e["type"],
                "effective_date": iso(e["eff"]), "term_expiry": iso(t["expiry"]), "booked_date": iso(e["booked"]), "currency": t["currency"],
                "gross_premium": money(e["premium"]), "fx_rate": str(rate), "gross_premium_usd": money(g), "broker_commission_usd": money(b),
                "mga_commission_usd": money(k), "net_due_usd": money(g - k)})
            gross, broker, mga, net = gross + g, broker + b, mga + k, net + g - k
        cover[key] = {"bdx_month": key, "premium_lines": len(lines), "gross_premium_usd": gross, "broker_commission_usd": broker,
                      "mga_commission_usd": mga, "net_due_usd": net, "risk_lines": 0, "claim_lines": 0, "paid_in_month_usd": 0, "reserve_usd": 0}

    # the risk list: effective by the month end, expiring after it, cumulative annualized change above zero
    by_cov: dict[str, list[dict]] = {}
    for e in events:
        by_cov.setdefault(e["cov"]["coverage_id"], []).append(e)
    for m in months():
        end, key = month_end(m), month_of(m)
        for t in terms:
            if not (t["eff"] <= end < t["expiry"]):
                continue
            for c in t["covs"]:
                done = [e for e in by_cov.get(c["coverage_id"], []) if e["booked"] <= end]
                annual = sum(e["annual"] for e in done)
                if annual <= 0:
                    continue
                t_out["bdx_risk"].append({
                    "bdx_month": key, "policy_id": t["policy_id"], "coverage_id": c["coverage_id"], "coverage_code": c["code"],
                    "line_of_business": t["line"], "effective_date": iso(t["eff"]), "expiry_date": iso(t["expiry"]), "currency": t["currency"],
                    "limit_amount": money(done[-1]["limit"]), "annualized_premium": money(annual), "referral_flag": c["referral"]})
                cover[key]["risk_lines"] += 1

    for m in months():
        end, key = month_end(m), month_of(m)
        rows = []
        for c in claim_rows:
            if c["reported"] > end:
                continue
            done = [x for x in c["ev"] if x["d"] <= end]
            moved = [x for x in done if x["d"] >= m]
            status = "OPEN"
            for x in done:
                status = {"CLOSE": "CLOSED", "REOPEN": "OPEN"}.get(x["t"], status)
            if status != "OPEN" and not moved:
                continue
            t = c["term"]
            rate = fx[(t["currency"], key)]
            paid_m = sum(x["a"] for x in moved if x["t"] in ("PAY_IND", "PAY_EXP"))
            paid = sum(x["a"] for x in done if x["t"] in ("PAY_IND", "PAY_EXP"))
            res = sum(x["a"] for x in done if x["t"] == "RESERVE")
            rec = sum(x["a"] for x in done if x["t"] == "RECOVERY")
            inc = paid + res - rec
            rows.append({"bdx_month": key, "claim_id": c["id"], "policy_id": t["policy_id"], "coverage_id": c["cov"]["coverage_id"],
                         "loss_date": iso(c["loss"]), "reported_date": iso(c["reported"]), "status": status, "currency": t["currency"],
                         "paid_in_month": money(paid_m), "paid_to_date": money(paid), "reserve_outstanding": money(res),
                         "recovered_to_date": money(rec), "incurred": money(inc), "fx_rate": str(rate),
                         "paid_in_month_usd": money(to_usd(paid_m, rate)), "reserve_usd": money(to_usd(res, rate)),
                         "incurred_usd": money(to_usd(inc, rate))})
            cover[key]["claim_lines"] += 1
            cover[key]["paid_in_month_usd"] += to_usd(paid_m, rate)
            cover[key]["reserve_usd"] += to_usd(res, rate)
        t_out["bdx_claims"] += rows
    rebuild_cover(t_out)


def cents(s: str) -> int:
    """Exact cents from a money string."""
    return half_up(Decimal(s or "0") * 100)


def rebuild_cover(t_out: dict[str, list[dict]]) -> None:
    """The cover sheet is the sum of its own lines, whichever lines the bordereaux hold."""
    keys = [month_of(m) for m in months()]
    cover = {k: {"bdx_month": k, "premium_lines": 0, "gross_premium_usd": 0, "broker_commission_usd": 0, "mga_commission_usd": 0,
                 "net_due_usd": 0, "risk_lines": 0, "claim_lines": 0, "paid_in_month_usd": 0, "reserve_usd": 0} for k in keys}
    for r in t_out["bdx_premium"]:
        c = cover[r["bdx_month"]]
        c["premium_lines"] += 1
        for f in ("gross_premium_usd", "broker_commission_usd", "mga_commission_usd", "net_due_usd"):
            c[f] += cents(r[f])
    for r in t_out["bdx_risk"]:
        cover[r["bdx_month"]]["risk_lines"] += 1
    for r in t_out["bdx_claims"]:
        c = cover[r["bdx_month"]]
        c["claim_lines"] += 1
        c["paid_in_month_usd"] += cents(r["paid_in_month_usd"])
        c["reserve_usd"] += cents(r["reserve_usd"])
    money_fields = ("gross_premium_usd", "broker_commission_usd", "mga_commission_usd", "net_due_usd", "paid_in_month_usd", "reserve_usd")
    t_out["bdx_cover"] = [{k: (money(v) if k in money_fields else str(v)) for k, v in c.items()} for c in cover.values()]


def build_legacy(t_out, rng, terms, events, claim_rows, instalments_by_event, convert) -> None:
    code_map = []
    for name, mapping in (("LOB", LOB_CODE), ("COV", COV_CODE), ("TXN", TXN_CODE), ("PLAN", PLAN_CODE), ("CCY", CCY_CODE), ("STATUS", STATUS_CODE),
                          ("CLAIM_STATUS", CLAIM_STATUS_CODE), ("HIST", HIST_CODE)):
        code_map += [{"code_set": name, "legacy_code": v, "target_code": k} for k, v in mapping.items()]
    code_map += [{"code_set": "AGENT", "legacy_code": b["broker_id"].replace("BRK-", "AG0"), "target_code": b["broker_id"]} for b in t_out["pas_brokers"]]
    t_out["conv_code_map"] = code_map
    agent = {r["target_code"]: r["legacy_code"] for r in code_map if r["code_set"] == "AGENT"}

    cw = t_out["conv_crosswalk"]
    pre_events = [e for e in events if e["booked"] <= CUT]
    by_term: dict[int, list[dict]] = {}
    for e in pre_events:
        by_term.setdefault(e["term"]["seq"], []).append(e)
    control: dict[tuple[str, str, str], list[int]] = {}

    def tally(measure, lob="", ccy="", count=0, amount=0):
        row = control.setdefault((measure, lob, ccy), [0, 0])
        row[0] += count
        row[1] += amount

    converted_terms = [t for t in terms if t["seq"] in convert]
    fake_no = 900000
    for t in converted_terms:
        ev = by_term.get(t["seq"], [])
        lob, ccy = LOB_CODE[t["line"]], CCY_CODE[t["currency"]]
        annual_by_cov: dict[str, int] = {}
        for e in ev:
            annual_by_cov[e["cov"]["coverage_id"]] = annual_by_cov.get(e["cov"]["coverage_id"], 0) + e["annual"]
        annual = sum(annual_by_cov.values())
        in_force = t["eff"] <= CUT < t["expiry"] and annual > 0
        remaining = (t["expiry"] - CUT).days
        unearned = int(Decimal(annual) * remaining / 365) // 100 * 100 if in_force else 0
        t_out["leg_policy_master"].append({
            "LEG_POL_NO": t["legacy"], "INSURED_REF": t["insured"], "AGENT_CD": agent[t["broker"]], "LOB_CD": lob, "CCY_CD": ccy,
            "EFF_DT": ymd(t["eff"]), "EXP_DT": ymd(t["expiry"]), "PLAN_CD": PLAN_CODE[t["plan"]], "STATUS_CD": STATUS_CODE[t["conv_status"]],
            "ANNUAL_PREM_CENTS": str(annual), "UNEARNED_CENTS": str(unearned), "PRIOR_POL_NO": t["prior"]["legacy"] if t["prior"] else ""})
        cw.append({"entity": "policy", "legacy_key": t["legacy"], "target_key": t["policy_id"], "batch_id": t["batch"]})
        tally("POLICY_COUNT", count=1)
        for c in t["covs"]:
            t_out["leg_coverages"].append({"LEG_POL_NO": t["legacy"], "COV_CD": COV_CODE[c["code"]], "LIMIT_CENTS": str(c["limit"]),
                                           "DED_CENTS": str(c["ded"]), "REFER_FLG": c["referral"]})
            cw.append({"entity": "coverage", "legacy_key": f"{t['legacy']}-{COV_CODE[c['code']]}", "target_key": c["coverage_id"], "batch_id": t["batch"]})
            tally("COVERAGE_COUNT", count=1)
        if in_force:
            tally("PREM_IN_FORCE", lob, ccy, 1, annual)
        for e in ev:
            t_out["leg_premium_history"].append({
                "LEG_TXN_NO": e["legacy_id"], "LEG_POL_NO": t["legacy"], "COV_CD": COV_CODE[e["cov"]["code"]], "TXN_CD": TXN_CODE[e["type"]],
                "EFF_DT": ymd(e["eff"]), "BOOK_DT": ymd(e["booked"]), "PREM_CENTS": str(e["premium"]), "ANNUAL_CHG_CENTS": str(e["annual"])})
            t_out["leg_commissions"].append({"LEG_TXN_NO": e["legacy_id"], "AGENT_CD": agent[t["broker"]], "RATE_PCT": str(Decimal(next(b["commission_rate"] for b in t_out["pas_brokers"] if b["broker_id"] == t["broker"])) * 100),
                                             "COMM_CENTS": str(e["commission"])})
            cw.append({"entity": "transaction", "legacy_key": e["legacy_id"], "target_key": e["id"], "batch_id": t["batch"]})
            tally("TXN_COUNT", count=1)
            tally("WRITTEN_HISTORY", lob, ccy, 1, e["premium"])
            for row, due, paid, amount in instalments_by_event.get(e["id"], []):
                if paid > CUT:
                    legacy_key = row["instalment_id"].replace("INS-", "LI")
                    t_out["leg_open_instalments"].append({"LEG_INST_NO": legacy_key, "LEG_TXN_NO": e["legacy_id"], "DUE_DT": ymd(due), "AMOUNT_CENTS": str(amount)})
                    cw.append({"entity": "instalment", "legacy_key": legacy_key, "target_key": row["instalment_id"], "batch_id": t["batch"]})
                    tally("OPEN_INSTALMENT_COUNT", count=1)
    # a few quote and test rows that must not convert
    n_fake = max(1, round(len(converted_terms) * 0.025))
    for i in range(n_fake):
        fake_no += 1
        reason = "QUOTE" if rng.random() < 0.8 else "TEST"
        key = f"LP{fake_no}"
        t_out["leg_policy_master"].append({
            "LEG_POL_NO": key, "INSURED_REF": f"INS-Q{i:05d}", "AGENT_CD": "AG0001", "LOB_CD": "1", "CCY_CD": "840", "EFF_DT": "20251215", "EXP_DT": "20261215",
            "PLAN_CD": "A", "STATUS_CD": "Q" if reason == "QUOTE" else "T", "ANNUAL_PREM_CENTS": "0", "UNEARNED_CENTS": "0", "PRIOR_POL_NO": ""})
        t_out["leg_coverages"].append({"LEG_POL_NO": key, "COV_CD": "10", "LIMIT_CENTS": "100000000", "DED_CENTS": "100000", "REFER_FLG": "N"})
        t_out["conv_exclusions"].append({"legacy_key": key, "reason": reason})

    for c in claim_rows:
        if c["reported"] > CUT:
            continue
        t = c["term"]
        done = [x for x in c["ev"] if x["d"] <= CUT]
        status = "OPEN"
        for x in done:
            status = {"CLOSE": "CLOSED", "REOPEN": "OPEN"}.get(x["t"], status)
        paid = sum(x["a"] for x in done if x["t"] in ("PAY_IND", "PAY_EXP"))
        res = sum(x["a"] for x in done if x["t"] == "RESERVE")
        rec = sum(x["a"] for x in done if x["t"] == "RECOVERY")
        t_out["leg_claims"].append({"LEG_CLM_NO": c["legacy_id"], "LEG_POL_NO": t["legacy"], "COV_CD": COV_CODE[c["cov"]["code"]], "LOSS_DT": ymd(c["loss"]),
                                    "RPT_DT": ymd(c["reported"]), "STATUS_CD": CLAIM_STATUS_CODE[status], "PAID_CENTS": str(paid), "RES_CENTS": str(res), "RECOV_CENTS": str(rec)})
        cw.append({"entity": "claim", "legacy_key": c["legacy_id"], "target_key": c["id"], "batch_id": t["batch"]})
        tally("CLAIM_COUNT", count=1)
        if status == "OPEN":
            tally("OPEN_CLAIMS", "", CCY_CODE[t["currency"]], 1, res)
            tally("OPEN_CLAIMS_PAID", "", CCY_CODE[t["currency"]], 1, paid)
        for x in done:
            t_out["leg_claim_history"].append({"LEG_HIST_NO": x["legacy_id"], "LEG_CLM_NO": c["legacy_id"], "HIST_CD": HIST_CODE[x["t"]], "BOOK_DT": ymd(x["d"]), "AMOUNT_CENTS": str(x["a"])})
            cw.append({"entity": "claim_txn", "legacy_key": x["legacy_id"], "target_key": x["id"], "batch_id": t["batch"]})
            tally("CLAIM_TXN_COUNT", count=1)
    t_out["leg_control_report"] = [{"MEASURE": k[0], "LOB_CD": k[1], "CCY_CD": k[2], "ROW_COUNT": str(v[0]), "AMOUNT_CENTS": str(v[1])}
                                   for k, v in sorted(control.items())]


def serialize(tables: dict[str, list[dict]]) -> dict[str, bytes]:
    out = {}
    for name, cols in COLUMNS.items():
        buf = io.StringIO(newline="")
        w = csv.DictWriter(buf, fieldnames=cols, lineterminator="\n")
        w.writeheader()
        w.writerows(tables[name])
        out[name] = buf.getvalue().encode()
    return out


def write(tables: dict[str, list[dict]], out: Path) -> dict[str, str]:
    out.mkdir(parents=True, exist_ok=True)
    hashes = {}
    for name, data in serialize(tables).items():
        (out / f"{name}.csv").write_bytes(data)
        hashes[name] = hashlib.sha256(data).hexdigest()
    return hashes


def main(argv: list[str]) -> int:
    seed = int(argv[1]) if len(argv) > 1 else SEED
    tables = build(seed)
    hashes = write(tables, Path(argv[0]))
    combined = hashlib.sha256("".join(hashes[k] for k in sorted(hashes)).encode()).hexdigest()
    for k in COLUMNS:
        print(f"{k:24s} {len(tables[k]):7d}")
    print(f"VERDICT: PASS (seed {seed}; {len(hashes)} tables; combined sha256 {combined})")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
