"""The twelve blind faults, each a literal implementation of its spec in bordereaux/author-specs.json (DESIGN-bordereaux.md section 7).

An independent author who never saw the checks wrote the specs. Each function here edits a copy of the clean book in place, returns a census of
what it touched, and raises NotApplied when no row qualifies, so a fault that does not apply can never score as a miss. A spec is never rewritten.
The readings an ambiguous phrase forced are in bordereaux/JUDGEMENTS.md.
"""
from __future__ import annotations

from decimal import Decimal

from bordereaux import book

PREMIUM_FIELDS = ("gross_premium_usd", "broker_commission_usd", "mga_commission_usd", "net_due_usd")


class NotApplied(Exception):
    """The spec's selection found no qualifying row, so the spec makes no change."""


def census(**kw) -> dict:
    if not any(kw.values()):
        raise RuntimeError(f"the fault touched nothing: {kw}")
    return kw


def require(rows: list, fid: str) -> list:
    if not rows:
        raise NotApplied(f"{fid}: no row qualifies under the spec's selection")
    return rows


def rnd(d: Decimal) -> int:
    """Round to cents, half up, on an amount held in cents."""
    return book.half_up(d)


def rate(row: dict) -> Decimal:
    return Decimal(row["fx_rate"])


def usd(c: int, fx: Decimal) -> str:
    return book.money(rnd(Decimal(c) * fx))


def fx_lookup(t) -> dict[tuple[str, str], Decimal]:
    return {(r["currency"], r["month"]): Decimal(r["usd_per_unit"]) for r in t["fx_rates"]}


def fx_of(table: dict, currency: str, month: str) -> Decimal:
    return Decimal(1) if currency == "USD" else table[(currency, month)]


def mga_rates(t) -> dict[str, Decimal]:
    return {r["line_of_business"]: Decimal(r["mga_commission_rate"]) for r in t["binding_terms"]}


def commission_cents(t) -> dict[str, int]:
    return {r["transaction_id"]: book.cents(r["amount"]) for r in t["broker_commissions"]}


def set_cover(t, table: str, fields: tuple[str, ...], months: set[str], count_lines: bool = False) -> None:
    """Replace the named cover-sheet fields in the existing rows of the named months with the sums of the named table's lines."""
    for c in t["bdx_cover"]:
        if c["bdx_month"] not in months:
            continue
        lines = [r for r in t[table] if r["bdx_month"] == c["bdx_month"]]
        for f in fields:
            c[f] = book.money(sum(book.cents(r[f]) for r in lines))
        if count_lines:
            c["premium_lines"] = str(len(lines))


def crosswalk(t, entity: str) -> list[dict]:
    return [r for r in t["conv_crosswalk"] if r["entity"] == entity]


def b01(t) -> dict:
    rows = sorted((r for r in t["bdx_premium"] if r["bdx_month"] == "2026-05" and book.cents(r["gross_premium"]) > 0), key=lambda r: (r["transaction_id"], r["line_no"]))[:3]
    require(rows, "B01")
    fx, mga, comm = fx_lookup(t), mga_rates(t), commission_cents(t)
    next_line = max((int(r["line_no"]) for r in t["bdx_premium"] if r["bdx_month"] == "2026-06"), default=0) + 1
    moved = []
    for r in rows:
        new_rate = fx_of(fx, r["currency"], "2026-06")
        gross_usd = rnd(Decimal(book.cents(r["gross_premium"])) * new_rate)
        mga_usd = rnd(Decimal(gross_usd) * mga[r["line_of_business"]])
        r.update(bdx_month="2026-06", line_no=str(next_line), fx_rate=f"{new_rate:.6f}", gross_premium_usd=book.money(gross_usd),
                 broker_commission_usd=usd(comm[r["transaction_id"]], new_rate), mga_commission_usd=book.money(mga_usd), net_due_usd=book.money(gross_usd - mga_usd))
        next_line += 1
        moved.append(r["transaction_id"])
    set_cover(t, "bdx_premium", PREMIUM_FIELDS, {"2026-05", "2026-06"}, count_lines=True)
    return census(transactions=moved)


def b02(t) -> dict:
    rows = sorted((r for r in t["bdx_premium"] if r["bdx_month"] == "2026-05" and r["transaction_type"] == "CAN" and book.cents(r["gross_premium"]) < 0),
                  key=lambda r: (r["transaction_id"], r["line_no"]))[:3]
    require(rows, "B02")
    for r in rows:
        for f in ("gross_premium",) + PREMIUM_FIELDS:
            r[f] = book.money(-book.cents(r[f]))
    set_cover(t, "bdx_premium", PREMIUM_FIELDS, {"2026-05"})
    return census(transactions=[r["transaction_id"] for r in rows])


def b03(t) -> dict:
    rows = sorted((r for r in t["bdx_premium"] if r["bdx_month"] == "2026-06" and r["currency"] == "CAD" and book.cents(r["gross_premium"]) > 0 and 0 < rate(r) < 1),
                  key=lambda r: (r["transaction_id"], r["line_no"]))[:3]
    require(rows, "B03")
    mga, comm = mga_rates(t), commission_cents(t)
    for r in rows:
        gross = book.cents(r["gross_premium"])
        mga_usd = rnd(Decimal(gross) * mga[r["line_of_business"]])
        r.update(fx_rate="1.000000", gross_premium_usd=book.money(gross), broker_commission_usd=book.money(comm[r["transaction_id"]]),
                 mga_commission_usd=book.money(mga_usd), net_due_usd=book.money(gross - mga_usd))
    set_cover(t, "bdx_premium", PREMIUM_FIELDS, {"2026-06"})
    return census(transactions=[r["transaction_id"] for r in rows])


def b04(t) -> dict:
    exp = [r for r in t["claim_transactions"] if r["txn_type"] == "PAY_EXP"]
    in_month: dict[str, int] = {}
    to_date: dict[str, int] = {}
    for r in exp:
        if r["booked_date"][:7] == "2026-05":
            in_month[r["claim_id"]] = in_month.get(r["claim_id"], 0) + book.cents(r["amount"])
        if r["booked_date"] <= "2026-05-31":
            to_date[r["claim_id"]] = to_date.get(r["claim_id"], 0) + book.cents(r["amount"])
    rows = sorted((r for r in t["bdx_claims"] if r["bdx_month"] == "2026-05" and in_month.get(r["claim_id"], 0) > 0), key=lambda r: r["claim_id"])[:3]
    require(rows, "B04")
    for r in rows:
        paid = book.cents(r["paid_in_month"]) - in_month[r["claim_id"]]
        paid_to = book.cents(r["paid_to_date"]) - to_date[r["claim_id"]]
        incurred = paid_to + book.cents(r["reserve_outstanding"]) - book.cents(r["recovered_to_date"])
        r.update(paid_in_month=book.money(paid), paid_to_date=book.money(paid_to), incurred=book.money(incurred),
                 paid_in_month_usd=usd(paid, rate(r)), incurred_usd=usd(incurred, rate(r)))
    set_cover(t, "bdx_claims", ("paid_in_month_usd",), {"2026-05"})
    return census(claims=[r["claim_id"] for r in rows])


def b05(t) -> dict:
    legacy = {r["LEG_INST_NO"] for r in t["leg_open_instalments"]}
    target = {r["instalment_id"] for r in t["billing_instalments"] if r["source_system"] == "LEGACY"}
    rows = sorted((r for r in crosswalk(t, "instalment") if r["legacy_key"] in legacy and r["target_key"] in target), key=lambda r: (r["legacy_key"], r["target_key"]))[:3]
    require(rows, "B05")
    gone = {r["target_key"] for r in rows}
    before = len(t["billing_instalments"])
    t["billing_instalments"] = [r for r in t["billing_instalments"] if r["instalment_id"] not in gone]
    return census(instalments=sorted(gone), rows_removed=before - len(t["billing_instalments"]))


def next_ctx(t) -> str:
    ids = [r["claim_txn_id"] for r in t["claim_transactions"]]
    numeric = [i for i in ids if i.startswith("CTX-") and i[4:].isdigit()]
    width = max(len(i) - 4 for i in numeric)
    return f"CTX-{max(int(i[4:]) for i in numeric) + 1:0{width}d}"


def b06(t) -> dict:
    walk: dict[str, list[dict]] = {}
    for r in crosswalk(t, "claim_txn"):
        walk.setdefault(r["target_key"], []).append(r)
    rows = sorted((r for r in t["claim_transactions"] if r["source_system"] == "LEGACY" and r["txn_type"] == "PAY_EXP" and book.cents(r["amount"]) > 0
                   and r["booked_date"][:7] == "2025-12" and r["claim_txn_id"] in walk), key=lambda r: r["claim_txn_id"])
    require(rows, "B06")
    pick = rows[0]
    match = min(walk[pick["claim_txn_id"]], key=lambda r: (r["legacy_key"], r["batch_id"]))
    new_id = next_ctx(t)
    t["claim_transactions"].append({**pick, "claim_txn_id": new_id})
    t["conv_crosswalk"].append({"entity": "claim_txn", "legacy_key": match["legacy_key"], "target_key": new_id, "batch_id": match["batch_id"]})
    a = book.cents(pick["amount"])
    touched = set()
    for r in t["bdx_claims"]:
        if r["claim_id"] == pick["claim_id"] and r["bdx_month"] >= "2025-12":
            paid = book.cents(r["paid_in_month"]) + (a if r["bdx_month"] == "2025-12" else 0)
            incurred = book.cents(r["incurred"]) + a
            r.update(paid_to_date=book.money(book.cents(r["paid_to_date"]) + a), incurred=book.money(incurred), paid_in_month=book.money(paid),
                     paid_in_month_usd=usd(paid, rate(r)), incurred_usd=usd(incurred, rate(r)))
            touched.add(r["bdx_month"])
    set_cover(t, "bdx_claims", ("paid_in_month_usd",), touched)
    return census(claim=pick["claim_id"], source_row=pick["claim_txn_id"], new_row=new_id, amount=pick["amount"], months=len(touched))


def b07(t) -> dict:
    to_monthly = {r["legacy_code"] for r in t["conv_code_map"] if r["code_set"] == "PLAN" and r["target_code"] == "MONTHLY"}
    plan = {r["LEG_POL_NO"]: r["PLAN_CD"] for r in t["leg_policy_master"]}
    walk: dict[str, list[str]] = {}
    for r in crosswalk(t, "policy"):
        walk.setdefault(r["target_key"], []).append(r["legacy_key"])
    rows = sorted((r for r in t["pas_policies"] if r["source_system"] == "LEGACY" and r["billing_plan"] == "MONTHLY"
                   and any(k in plan and plan[k] in to_monthly for k in walk.get(r["policy_id"], []))), key=lambda r: r["policy_id"])[:3]
    require(rows, "B07")
    for r in rows:
        r["billing_plan"] = "ANNUAL"
    return census(policies=[r["policy_id"] for r in rows])


def b08(t) -> dict:
    history = {r["LEG_HIST_NO"] for r in t["leg_claim_history"]}
    matched = {r["target_key"] for r in crosswalk(t, "claim_txn") if r["legacy_key"] in history}
    rows = sorted((r for r in t["claim_transactions"] if r["source_system"] == "LEGACY" and r["txn_type"] == "RESERVE" and book.cents(r["amount"]) >= 10000
                   and r["booked_date"] <= "2025-12-31" and r["claim_txn_id"] in matched), key=lambda r: r["claim_txn_id"])[:3]
    require(rows, "B08")
    delta: dict[str, int] = {}
    for r in rows:
        original = book.cents(r["amount"])
        new = rnd(Decimal(original) / Decimal(100))
        r["amount"] = book.money(new)
        delta[r["claim_id"]] = delta.get(r["claim_id"], 0) + new - original
    touched = set()
    for r in t["bdx_claims"]:
        if r["claim_id"] in delta and r["bdx_month"] >= "2025-12":
            d = delta[r["claim_id"]]
            reserve = book.cents(r["reserve_outstanding"]) + d
            incurred = book.cents(r["incurred"]) + d
            r.update(reserve_outstanding=book.money(reserve), incurred=book.money(incurred), reserve_usd=usd(reserve, rate(r)), incurred_usd=usd(incurred, rate(r)))
            touched.add(r["bdx_month"])
    set_cover(t, "bdx_claims", ("reserve_usd",), touched)
    return census(rows=[r["claim_txn_id"] for r in rows], claims=sorted(delta), months=len(touched))


def b09(t) -> dict:
    txn = {r["transaction_id"]: r for r in t["pas_transactions"]}
    legacy = {r["LEG_TXN_NO"]: r for r in t["leg_commissions"] if Decimal(r["RATE_PCT"]) > 0}
    walk = {}
    for r in crosswalk(t, "transaction"):
        if r["legacy_key"] in legacy:
            walk.setdefault(r["target_key"], r["legacy_key"])
    rows = sorted((r for r in t["broker_commissions"] if r["source_system"] == "LEGACY" and book.cents(r["amount"]) > 0 and Decimal(r["rate"]) > 0
                   and txn[r["transaction_id"]]["source_system"] == "LEGACY" and txn[r["transaction_id"]]["booked_date"][:7] == "2025-12"
                   and r["transaction_id"] in walk), key=lambda r: r["commission_id"])[:3]
    require(rows, "B09")
    new_amounts = {}
    for r in rows:
        pct = legacy[walk[r["transaction_id"]]]["RATE_PCT"]
        amount = rnd(Decimal(book.cents(txn[r["transaction_id"]]["written_premium"])) * Decimal(pct))
        r.update(rate=pct, amount=book.money(amount))
        new_amounts[r["transaction_id"]] = amount
    touched = set()
    for r in t["bdx_premium"]:
        if r["transaction_id"] in new_amounts and r["bdx_month"] >= "2025-12":
            r["broker_commission_usd"] = usd(new_amounts[r["transaction_id"]], rate(r))
            touched.add(r["bdx_month"])
    set_cover(t, "bdx_premium", ("broker_commission_usd",), touched)
    return census(commissions=[r["commission_id"] for r in rows], months=len(touched))


def b10(t) -> dict:
    def targets(entity):
        return {r["target_key"] for r in crosswalk(t, entity)}

    def all_new(rows, id_field, entity):
        walked = targets(entity) if entity else set()
        return all(r["source_system"] == "NEW" and r[id_field] not in walked for r in rows)

    picked = None
    for p in sorted((r for r in t["pas_policies"] if r["source_system"] == "NEW" and r["currency"] == "USD" and r["effective_date"][:7] == "2026-01"), key=lambda r: r["policy_id"]):
        pid = p["policy_id"]
        txns = [r for r in t["pas_transactions"] if r["policy_id"] == pid]
        if not any(r["booked_date"][:7] == "2026-01" for r in txns) or any(r["booked_date"] < "2026-01-01" for r in txns):
            continue
        claims = [r for r in t["claims"] if r["policy_id"] == pid]
        if any(r["reported_date"] < "2026-01-01" for r in claims):
            continue
        txn_ids = {r["transaction_id"] for r in txns}
        claim_ids = {r["claim_id"] for r in claims}
        groups = (
            ([p], "policy_id", "policy"),
            (txns, "transaction_id", "transaction"),
            ([r for r in t["pas_coverages"] if r["policy_id"] == pid], "coverage_id", "coverage"),
            (claims, "claim_id", "claim"),
            ([r for r in t["claim_transactions"] if r["claim_id"] in claim_ids], "claim_txn_id", "claim_txn"),
            ([r for r in t["broker_commissions"] if r["transaction_id"] in txn_ids], "commission_id", "commission"),
            ([r for r in t["billing_instalments"] if r["policy_id"] == pid], "instalment_id", "instalment"),
        )
        if all(all_new(*g) for g in groups):
            picked = p
            break
    require([picked] if picked else [], "B10")
    pid = picked["policy_id"]
    picked["currency"] = "CAD"
    fx, mga, comm = fx_lookup(t), mga_rates(t), commission_cents(t)
    premium_months, claim_months, risk = set(), set(), 0
    for r in t["bdx_premium"]:
        if r["policy_id"] == pid:
            new_rate = fx[("CAD", r["bdx_month"])]
            gross_usd = rnd(Decimal(book.cents(r["gross_premium"])) * new_rate)
            mga_usd = rnd(Decimal(gross_usd) * mga[r["line_of_business"]])
            r.update(currency="CAD", fx_rate=f"{new_rate:.6f}", gross_premium_usd=book.money(gross_usd), broker_commission_usd=usd(comm[r["transaction_id"]], new_rate),
                     mga_commission_usd=book.money(mga_usd), net_due_usd=book.money(gross_usd - mga_usd))
            premium_months.add(r["bdx_month"])
    for r in t["bdx_risk"]:
        if r["policy_id"] == pid:
            r["currency"] = "CAD"
            risk += 1
    for r in t["bdx_claims"]:
        if r["policy_id"] == pid:
            new_rate = fx[("CAD", r["bdx_month"])]
            r.update(currency="CAD", fx_rate=f"{new_rate:.6f}", paid_in_month_usd=usd(book.cents(r["paid_in_month"]), new_rate),
                     reserve_usd=usd(book.cents(r["reserve_outstanding"]), new_rate), incurred_usd=usd(book.cents(r["incurred"]), new_rate))
            claim_months.add(r["bdx_month"])
    months = premium_months | claim_months
    set_cover(t, "bdx_premium", PREMIUM_FIELDS, months)
    set_cover(t, "bdx_claims", ("paid_in_month_usd", "reserve_usd"), months)
    return census(policy=pid, premium_months=len(premium_months), claim_months=len(claim_months), risk_lines=risk)


def b11(t) -> dict:
    claims = {r["claim_id"]: r for r in t["claims"]}
    walked_claims = {r["target_key"] for r in crosswalk(t, "claim")}
    walked_moves = {r["target_key"] for r in crosswalk(t, "claim_txn")}
    moves: dict[str, list[dict]] = {}
    for r in t["claim_transactions"]:
        moves.setdefault(r["claim_id"], []).append(r)
    rows = sorted((r for r in t["claim_transactions"] if r["source_system"] == "NEW" and r["txn_type"] == "PAY_EXP" and book.cents(r["amount"]) > 0
                   and r["booked_date"][:7] == "2026-01" and claims[r["claim_id"]]["source_system"] == "NEW" and claims[r["claim_id"]]["reported_date"][:7] == "2026-01"
                   and r["claim_id"] not in walked_claims and not any(m["claim_txn_id"] in walked_moves for m in moves[r["claim_id"]])), key=lambda r: r["claim_txn_id"])
    require(rows, "B11")
    pick = rows[0]
    extra = 100000
    pick["amount"] = book.money(book.cents(pick["amount"]) + extra)
    touched = set()
    for r in t["bdx_claims"]:
        if r["claim_id"] == pick["claim_id"] and r["bdx_month"] >= "2026-01":
            paid = book.cents(r["paid_in_month"]) + (extra if r["bdx_month"] == "2026-01" else 0)
            incurred = book.cents(r["incurred"]) + extra
            r.update(paid_to_date=book.money(book.cents(r["paid_to_date"]) + extra), incurred=book.money(incurred), paid_in_month=book.money(paid),
                     paid_in_month_usd=usd(paid, rate(r)), incurred_usd=usd(incurred, rate(r)))
            touched.add(r["bdx_month"])
    set_cover(t, "bdx_claims", ("paid_in_month_usd",), touched)
    return census(row=pick["claim_txn_id"], claim=pick["claim_id"], months=len(touched))


def b12(t) -> dict:
    pols = {r["policy_id"]: r for r in t["pas_policies"]}
    walked_cov = {r["target_key"] for r in crosswalk(t, "coverage")}
    walked_txn = {r["target_key"] for r in crosswalk(t, "transaction")}
    txns: dict[str, list[dict]] = {}
    for r in t["pas_transactions"]:
        txns.setdefault(r["coverage_id"], []).append(r)

    def qualifies(c: dict) -> bool:
        p = pols[c["policy_id"]]
        if c["source_system"] != "NEW" or book.cents(c["limit_amount"]) < 200 or p["source_system"] != "NEW" or p["effective_date"][:7] != "2026-01":
            return False
        rows = txns.get(c["coverage_id"], [])
        if not any(r["booked_date"][:7] == "2026-01" for r in rows):
            return False
        limit = book.cents(c["limit_amount"])
        if not all(r["source_system"] == "NEW" and r["booked_date"] >= "2026-01-01" and book.cents(r["limit_after"]) == limit and r["transaction_id"] not in walked_txn for r in rows):
            return False
        return c["coverage_id"] not in walked_cov

    rows = sorted((c for c in t["pas_coverages"] if qualifies(c)), key=lambda c: c["coverage_id"])
    require(rows, "B12")
    pick = rows[0]
    new_limit = book.money(rnd(Decimal(book.cents(pick["limit_amount"])) / Decimal(2)))
    original = pick["limit_amount"]
    pick["limit_amount"] = new_limit
    n_txn = n_risk = 0
    for r in t["pas_transactions"]:
        if r["coverage_id"] == pick["coverage_id"]:
            r["limit_after"] = new_limit
            n_txn += 1
    for r in t["bdx_risk"]:
        if r["coverage_id"] == pick["coverage_id"]:
            r["limit_amount"] = new_limit
            n_risk += 1
    return census(coverage=pick["coverage_id"], original_limit=original, new_limit=new_limit, transactions=n_txn, risk_lines=n_risk)


BLIND = {"B01": b01, "B02": b02, "B03": b03, "B04": b04, "B05": b05, "B06": b06, "B07": b07, "B08": b08, "B09": b09, "B10": b10, "B11": b11, "B12": b12}
