"""The faults of the payment-rails round (DESIGN-rails.md): the 8 declared faults of section 6 (the self-test) and the 10
held-out faults, each implemented once and literally from rails/author-specs.json (section 8, with the rules of
DESIGN-blind.md section 6).

Each function edits the records it is given in place: {"tables": the 17 extracts, "sources": the outside records of
DESIGN-independent.md, "rails": the processor, bank and ledger tables of rails/events.py and rails/ledger.py}, and
returns a census of what it touched. Selections are evaluated on the original records before any change, ids sort
ascending, fewer matches than asked means all of them, and money rounds to cents half up. A selection that finds
nothing raises FaultDidNotApply and the fault is reported as not applied. Every reading an ambiguous phrase forced is
listed in rails/JUDGEMENTS.md under the fault's id.
"""
from __future__ import annotations

import datetime as dt
import math
from decimal import ROUND_HALF_UP, Decimal

from blind.faults import FaultDidNotApply
from rails import events as ev

D = dt.date
ZERO = Decimal("0.00")
__all__ = ["DECLARED", "HELD_OUT", "FaultDidNotApply"]


# ---------------------------------------------------------------------------------------------------- helpers

def _num(id_: str) -> int:
    return int(id_.split("-")[1])


def _next_id(rows: list[dict], key: str, n: int = 1) -> list[str]:
    """New ids continuing a table's sequence: the highest number plus one, same prefix and width."""
    top = max(rows, key=lambda r: _num(r[key]))[key]
    prefix, digits = top.split("-")
    return [f"{prefix}-{_num(top) + i:0{len(digits)}d}" for i in range(1, n + 1)]


def _entries(gl: list[dict]) -> dict[str, list[dict]]:
    out: dict = {}
    for ln in gl:
        out.setdefault(ln["entry_id"], []).append(ln)
    return out


def _entry_for(gl: list[dict], source_type: str, source_id: str, posted_on: D | None = None) -> list[str]:
    """Entry ids posted from a source record (optionally on one day), in id order."""
    return sorted({ln["entry_id"] for ln in gl if ln["source_type"] == source_type and ln["source_id"] == source_id
                   and (posted_on is None or ln["posted_on"] == posted_on)})


def _add_entry(gl: list[dict], day: D, source_type: str, source_id: str, lines: list[tuple]) -> str:
    """Append one balanced entry, its id continuing the journal's sequence; lines are (account, debit, credit, invoice)."""
    eid = _next_id(gl, "entry_id")[0]
    for n, (acct, debit, credit, inv) in enumerate(lines, start=1):
        gl.append({"entry_id": eid, "line_no": n, "posted_on": day, "account": acct, "debit": debit, "credit": credit,
                   "source_type": source_type, "source_id": source_id, "invoice_id": inv})
    return eid


def _cents(x: Decimal) -> Decimal:
    return x.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)


def _in(d: D, a: D, b: D) -> bool:
    return a <= d <= b


SEP1, SEP30 = D(2026, 9, 1), D(2026, 9, 30)


# ---------------------------------------------------------------------------------------------------- declared (section 6)

def s1_duplicate_capture(rec: dict) -> dict:
    """The lowest-id card invoice dated 2026-09-15 or later with one USD capture is captured a second time on the same day."""
    r = rec["rails"]
    caps: dict = {}
    for e in r["processor_events"]:
        if e["event_type"] == "capture":
            caps.setdefault(e["invoice_id"], []).append(e)
    items = {x["charge_id"]: x for x in r["processor_settlement_items"] if x["item_type"] == "charge" and x["payout_id"]}
    payouts = {p["payout_id"]: p for p in r["processor_payouts"]}
    banked = {b["reference"]: b for b in r["bank_statement_lines"] if b["counterparty"] == ev.PROCESSOR}
    inv = sorted(i for i, cs in caps.items() if len(cs) == 1 and cs[0]["currency"] == "USD" and i.startswith("CI-")
                 and _in(cs[0]["event_on"], D(2026, 9, 15), SEP30) and cs[0]["charge_id"] in items
                 and items[cs[0]["charge_id"]]["payout_id"] in banked
                 and any(x["invoice_date"] >= D(2026, 9, 15) for x in rec["tables"]["card_invoice_lines"] if x["invoice_id"] == i))
    if not inv:
        raise FaultDidNotApply("no USD card invoice dated 2026-09-15 or later with one settled, paid-out capture")
    cap = caps[inv[0]][0]
    item = items[cap["charge_id"]]
    new_charge = _next_id(r["processor_events"], "charge_id")[0]
    new_events = _next_id(r["processor_events"], "event_id", 2)
    for eid, kind in zip(new_events, ("authorization", "capture")):
        r["processor_events"].append({**cap, "event_id": eid, "event_type": kind, "charge_id": new_charge, "detail": ""})
    fee_item = next(x for x in r["processor_settlement_items"] if x["item_type"] == "fee" and x["charge_id"] == cap["charge_id"])
    new_items = _next_id(r["processor_settlement_items"], "item_id", 2)
    r["processor_settlement_items"].append({**item, "item_id": new_items[0], "charge_id": new_charge})
    r["processor_settlement_items"].append({**fee_item, "item_id": new_items[1], "charge_id": new_charge})
    net = item["amount_usd"] + fee_item["amount_usd"]
    p = payouts[item["payout_id"]]
    p["amount_usd"] += net
    p["item_count"] += 2
    bank = banked[p["payout_id"]]
    bank["amount"] += net
    gl = r["gl_journal_lines"]
    _add_entry(gl, cap["event_on"], "capture", new_charge, [("1150", cap["amount_usd"], ZERO, ""), ("1100", ZERO, cap["amount_usd"], cap["invoice_id"])])
    _add_entry(gl, item["available_on"], "fee", new_charge, [("6100", -fee_item["amount_usd"], ZERO, ""), ("1150", ZERO, -fee_item["amount_usd"], "")])
    for ln in gl:
        if ln["source_type"] == "payout" and ln["source_id"] == p["payout_id"]:
            if ln["account"] == "1000":
                ln["debit"] += net
            else:
                ln["credit"] += net
    return {"invoice": inv[0], "duplicate_charge": new_charge, "payout": p["payout_id"], "net_usd": float(net)}


def s2_missing_settlement_file(rec: dict) -> dict:
    """The settlement report's items for the business day 2026-09-15 are missing."""
    r = rec["rails"]
    gone = [x["item_id"] for x in r["processor_settlement_items"] if x["available_on"] == D(2026, 9, 15)]
    if not gone:
        raise FaultDidNotApply("no settlement items available on 2026-09-15")
    r["processor_settlement_items"] = [x for x in r["processor_settlement_items"] if x["available_on"] != D(2026, 9, 15)]
    return {"items_removed": len(gone)}


def s3_fees_booked_gross(rec: dict) -> dict:
    """Payouts arriving in September 2026 booked at the gross of their settled charges; no fee entries that month."""
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    arriving = {p["payout_id"] for p in r["processor_payouts"] if _in(p["arrival_on"], SEP1, SEP30)}
    fees: dict = {}
    for x in r["processor_settlement_items"]:
        if x["item_type"] == "fee" and x["payout_id"] in arriving:
            fees[x["payout_id"]] = fees.get(x["payout_id"], ZERO) - x["amount_usd"]
    fee_entries = {ln["entry_id"] for ln in gl if ln["source_type"] == "fee" and _in(ln["posted_on"], SEP1, SEP30)}
    if not arriving or not fee_entries:
        raise FaultDidNotApply("no payout arriving or fee posted in September 2026")
    for ln in gl:
        if ln["source_type"] == "payout" and ln["source_id"] in arriving:
            add = fees.get(ln["source_id"], ZERO)
            if ln["account"] == "1000":
                ln["debit"] += add
            else:
                ln["credit"] += add
    r["gl_journal_lines"] = [ln for ln in gl if ln["entry_id"] not in fee_entries]
    return {"payouts_grossed_up": len(arriving), "fee_entries_removed": len(fee_entries), "fees_usd": float(sum(fees.values(), ZERO))}


def s4_refund_never_posted(rec: dict) -> dict:
    """The first card refund the processor debits in September 2026 has no ledger entry."""
    r = rec["rails"]
    items = sorted((x for x in r["processor_settlement_items"] if x["item_type"] == "refund" and _in(x["available_on"], SEP1, SEP30)),
                   key=lambda x: (x["available_on"], x["item_id"]))
    if not items:
        raise FaultDidNotApply("the processor debits no card refund in September 2026")
    ref = items[0]["reference"]
    entries = set(_entry_for(r["gl_journal_lines"], "refund", ref))
    r["gl_journal_lines"] = [ln for ln in r["gl_journal_lines"] if ln["entry_id"] not in entries]
    return {"refund": ref, "entries_removed": len(entries)}


def s5_chargeback_reversed_twice(rec: dict) -> dict:
    """The last dispute won up to 2026-09-30 has its P7 entry posted twice."""
    r = rec["rails"]
    won = sorted((e for e in r["processor_events"] if e["event_type"] == "dispute_won" and e["event_on"] <= SEP30),
                 key=lambda e: (e["event_on"], e["event_id"]))
    if not won:
        raise FaultDidNotApply("no dispute won up to 2026-09-30")
    e = won[-1]
    eid = _entry_for(r["gl_journal_lines"], "dispute_won", e["reference"])[0]
    lines = [ln for ln in r["gl_journal_lines"] if ln["entry_id"] == eid]
    new = _add_entry(r["gl_journal_lines"], lines[0]["posted_on"], "dispute_won", e["reference"],
                     [(ln["account"], ln["debit"], ln["credit"], ln["invoice_id"]) for ln in lines])
    return {"dispute": e["reference"], "won_on": e["event_on"].isoformat(), "entry_copied": eid, "new_entry": new}


def s6_payout_split_across_months(rec: dict) -> dict:
    """The last payout arriving in September 2026 is posted half on its arrival day, half on the first business day of October."""
    r = rec["rails"]
    arriving = sorted((p for p in r["processor_payouts"] if _in(p["arrival_on"], SEP1, SEP30)), key=lambda p: (p["arrival_on"], p["payout_id"]))
    if not arriving:
        raise FaultDidNotApply("no payout arriving in September 2026")
    p = arriving[-1]
    gl = r["gl_journal_lines"]
    eid = _entry_for(gl, "payout", p["payout_id"])[0]
    lines = [ln for ln in gl if ln["entry_id"] == eid]
    amount = lines[0]["debit"] + lines[0]["credit"]
    half = _cents(amount / 2)
    for ln in lines:
        if ln["debit"]:
            ln["debit"] = half
        else:
            ln["credit"] = half
    oct1 = ev.next_business(SEP30)
    new = _add_entry(gl, oct1, "payout", p["payout_id"], [("1000", amount - half, ZERO, ""), ("1150", ZERO, amount - half, "")])
    return {"payout": p["payout_id"], "arrival_on": p["arrival_on"].isoformat(), "posted_in_october": float(amount - half), "new_entry": new}


def s7_currency_wrong_date(rec: dict) -> dict:
    """Non-USD charges settled in September 2026 converted at the capture day's rate: no currency difference booked."""
    r = rec["rails"]
    gone = {ln["entry_id"] for ln in r["gl_journal_lines"] if ln["source_type"] == "settlement" and _in(ln["posted_on"], SEP1, SEP30)}
    if not gone:
        raise FaultDidNotApply("no currency difference posted in September 2026")
    total = sum((ln["debit"] - ln["credit"] for ln in r["gl_journal_lines"] if ln["entry_id"] in gone and ln["account"] == "7100"), ZERO)
    r["gl_journal_lines"] = [ln for ln in r["gl_journal_lines"] if ln["entry_id"] not in gone]
    return {"entries_removed": len(gone), "net_7100_removed": float(total)}


def s8_remittance_wrong_customer(rec: dict) -> dict:
    """The last September 2026 contract payment that names its invoice correctly is credited to another account's open invoice."""
    r, t = rec["rails"], rec["tables"]
    account = {c["contract_id"]: c["account_id"] for c in t["crm_contracts"]}
    inv_account, inv_date, inv_total = {}, {}, {}
    for x in t["contract_invoice_lines"]:
        inv_account[x["invoice_id"]] = account[x["contract_id"]]
        inv_date[x["invoice_id"]] = x["invoice_date"]
        inv_total[x["invoice_id"]] = inv_total.get(x["invoice_id"], ZERO) + x["amount"]
    gl = r["gl_journal_lines"]
    credited = {ln["source_id"]: ln for ln in gl if ln["source_type"] == "transfer" and ln["account"] == "1100"}
    lines = [b for b in r["bank_statement_lines"] if b["counterparty"] != ev.PROCESSOR and _in(b["posted_on"], SEP1, SEP30)
             and b["line_id"] in credited and credited[b["line_id"]]["invoice_id"] == b["reference"]]
    if not lines:
        raise FaultDidNotApply("no September 2026 contract payment names its invoice")
    b = sorted(lines, key=lambda b: (b["posted_on"], b["line_id"]))[-1]
    paid: dict = {}
    for p in t["contract_payments"]:
        if p["paid_on"] <= b["posted_on"]:
            paid[p["invoice_id"]] = paid.get(p["invoice_id"], ZERO) + p["amount"]
    open_inv = sorted((inv_account[i], i) for i in inv_total if inv_date[i] <= b["posted_on"] and inv_account[i] != b["counterparty"]
                      and inv_total[i] - paid.get(i, ZERO) > 0)
    if not open_inv:
        raise FaultDidNotApply("no other account has an open invoice that day")
    acct = open_inv[0][0]
    target = next(i for a, i in open_inv if a == acct)
    credited[b["line_id"]]["invoice_id"] = target
    return {"bank_line": b["line_id"], "named": b["reference"], "credited_instead": target, "account_instead": acct}


DECLARED = [
    ("duplicate_capture", s1_duplicate_capture),
    ("missing_settlement_file", s2_missing_settlement_file),
    ("fees_booked_gross", s3_fees_booked_gross),
    ("refund_never_posted", s4_refund_never_posted),
    ("chargeback_reversed_twice", s5_chargeback_reversed_twice),
    ("payout_split_across_months", s6_payout_split_across_months),
    ("currency_wrong_date_rate", s7_currency_wrong_date),
    ("remittance_wrong_customer", s8_remittance_wrong_customer),
]


# ---------------------------------------------------------------------------------------------------- held out (R01 to R10)

def r01_duplicate_payout_receipt(rec: dict) -> dict:
    r = rec["rails"]
    payouts = {p["payout_id"]: p for p in r["processor_payouts"]}
    gl = r["gl_journal_lines"]
    sel = sorted(b["line_id"] for b in r["bank_statement_lines"]
                 if b["counterparty"] == ev.PROCESSOR and _in(b["posted_on"], D(2026, 6, 1), D(2026, 6, 30)) and b["amount"] > 0
                 and b["reference"] in payouts and payouts[b["reference"]]["arrival_on"] == b["posted_on"]
                 and payouts[b["reference"]]["amount_usd"] == b["amount"] and _entry_for(gl, "payout", b["reference"]))[:2]
    if not sel:
        raise FaultDidNotApply("no June 2026 payout line qualifies")
    by_id = {b["line_id"]: b for b in r["bank_statement_lines"]}
    originals = [dict(by_id[i]) for i in sel]
    new_lines = _next_id(r["bank_statement_lines"], "line_id", len(originals))
    added = []
    for nid, b in zip(new_lines, originals):
        r["bank_statement_lines"].append({"line_id": nid, "posted_on": b["posted_on"], "amount": b["amount"],
                                          "counterparty": b["counterparty"], "reference": b["reference"]})
        eid = _add_entry(gl, b["posted_on"], "payout", b["reference"], [("1000", b["amount"], ZERO, ""), ("1150", ZERO, b["amount"], "")])
        added.append({"bank_line": nid, "entry": eid, "payout": b["reference"], "amount": float(b["amount"])})
    return {"selected": sel, "added": added}


def r02_fee_rows_dropped(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    ent = _entries(gl)

    def p4(x):
        ids = _entry_for(gl, "fee", x["charge_id"], x["available_on"])
        return [i for i in ids if sorted((ln["account"], ln["debit"], ln["credit"]) for ln in ent[i])
                == sorted([("6100", -x["amount_usd"], ZERO), ("1150", ZERO, -x["amount_usd"])])]
    sel = sorted((x for x in r["processor_settlement_items"] if x["item_type"] == "fee" and _in(x["available_on"], D(2025, 5, 1), D(2025, 5, 31))
                  and x["amount_usd"] < 0 and x["payout_id"] and p4(x)), key=lambda x: x["item_id"])[:3]
    if not sel:
        raise FaultDidNotApply("no May 2025 fee item qualifies")
    drop_items = {x["item_id"] for x in sel}
    drop_entries = {p4(x)[0] for x in sel}
    r["processor_settlement_items"] = [x for x in r["processor_settlement_items"] if x["item_id"] not in drop_items]
    r["gl_journal_lines"] = [ln for ln in gl if ln["entry_id"] not in drop_entries]
    return {"items_deleted": sorted(drop_items), "entries_deleted": sorted(drop_entries),
            "fees_usd": float(-sum((x["amount_usd"] for x in sel), ZERO))}


def r03_capture_webhooks_lost(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    ev_rows = r["processor_events"]
    n_caps: dict = {}
    for e in ev_rows:
        if e["event_type"] == "capture":
            n_caps[e["charge_id"]] = n_caps.get(e["charge_id"], 0) + 1
    authorized = {e["charge_id"] for e in ev_rows if e["event_type"] == "authorization"}
    settled = {x["charge_id"] for x in r["processor_settlement_items"] if x["item_type"] == "charge"}
    sel = sorted((e for e in ev_rows if e["event_type"] == "capture" and _in(e["event_on"], D(2025, 7, 1), D(2025, 7, 31))
                  and e["amount_usd"] > 0 and n_caps[e["charge_id"]] == 1 and e["charge_id"] in authorized
                  and e["charge_id"] in settled and _entry_for(gl, "capture", e["charge_id"], e["event_on"])),
                 key=lambda e: e["event_id"])[:2]
    if not sel:
        raise FaultDidNotApply("no July 2025 capture qualifies")
    drop_events = {e["event_id"] for e in sel}
    drop_entries = {_entry_for(gl, "capture", e["charge_id"], e["event_on"])[0] for e in sel}
    r["processor_events"] = [e for e in ev_rows if e["event_id"] not in drop_events]
    r["gl_journal_lines"] = [ln for ln in gl if ln["entry_id"] not in drop_entries]
    return {"events_deleted": sorted(drop_events), "entries_deleted": sorted(drop_entries),
            "captures_usd": float(sum((e["amount_usd"] for e in sel), ZERO))}


def r04_receipt_stranded_unapplied(rec: dict) -> dict:
    r, t = rec["rails"], rec["tables"]
    gl = r["gl_journal_lines"]
    contracts: dict = {}
    for x in t["contract_invoice_lines"]:
        contracts.setdefault(x["invoice_id"], set()).add(x["contract_id"])
    account = {c["contract_id"]: c["account_id"] for c in t["crm_contracts"]}
    chosen = None
    for p in sorted(t["contract_payments"], key=lambda p: p["payment_id"]):
        if not (_in(p["paid_on"], SEP1, SEP30) and p["amount"] > 0) or len(contracts.get(p["invoice_id"], ())) != 1:
            continue
        acct = account.get(next(iter(contracts[p["invoice_id"]])))
        lines = [b for b in r["bank_statement_lines"] if b["posted_on"] == p["paid_on"] and b["amount"] == p["amount"]
                 and b["counterparty"] == acct and b["reference"] == p["invoice_id"]]
        if len(lines) != 1:
            continue
        rows = [ln for ln in gl if ln["source_type"] == "transfer" and ln["source_id"] == lines[0]["line_id"]]
        if (any(ln["account"] == "1000" and ln["debit"] == p["amount"] for ln in rows)
                and any(ln["account"] == "1100" and ln["credit"] == p["amount"] and ln["invoice_id"] == p["invoice_id"] for ln in rows)):
            chosen = (p, lines[0], rows)
            break
    if chosen is None:
        raise FaultDidNotApply("no September 2026 contract payment qualifies")
    p, b, rows = chosen
    for ln in rows:
        if ln["account"] == "1100" and ln["credit"] == p["amount"]:
            ln["account"], ln["invoice_id"] = "2100", ""
    return {"payment": p["payment_id"], "bank_line": b["line_id"], "amount": float(p["amount"])}


def r05_october_payout_in_september(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    oct1 = D(2026, 10, 1)
    sel = sorted(p["payout_id"] for p in r["processor_payouts"] if p["created_on"] == SEP30 and p["arrival_on"] == oct1
                 and p["amount_usd"] > 0
                 and len([b for b in r["bank_statement_lines"] if b["counterparty"] == ev.PROCESSOR and b["reference"] == p["payout_id"]
                          and b["posted_on"] == oct1 and b["amount"] == p["amount_usd"]]) == 1
                 and _entry_for(gl, "payout", p["payout_id"], oct1))[:1]
    if not sel:
        raise FaultDidNotApply("no payout created 2026-09-30 arriving 2026-10-01")
    eid = _entry_for(gl, "payout", sel[0], oct1)[0]
    for ln in gl:
        if ln["entry_id"] == eid:
            ln["posted_on"] = SEP30
    return {"payout": sel[0], "entry": eid}


def r06_fx_rate_inverted(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    ent = _entries(gl)
    caps: dict = {}
    for e in r["processor_events"]:
        if e["event_type"] == "capture":
            caps.setdefault(e["charge_id"], []).append(e)
    chosen = []
    for x in sorted(r["processor_settlement_items"], key=lambda x: x["item_id"]):
        if not (x["item_type"] == "charge" and x["currency"] == "CAD" and _in(x["available_on"], SEP1, D(2026, 9, 25))
                and 0 < x["fx_rate"] < 1) or len(caps.get(x["charge_id"], [])) != 1:
            continue
        c, s = caps[x["charge_id"]][0]["amount_usd"], x["amount_usd"]
        s_bad = _cents(x["amount_presentment"] / x["fx_rate"])
        ids = [i for i in _entry_for(gl, "settlement", x["charge_id"], x["available_on"]) if len(ent[i]) == 2
               and sum(ln["debit"] for ln in ent[i] if ln["account"] == "1150") - sum(ln["credit"] for ln in ent[i] if ln["account"] == "1150") == s - c]
        if s_bad > s and s_bad > c and s != c and len(ids) == 1:
            chosen.append((x, c, s, s_bad, ids[0]))
        if len(chosen) == 2:
            break
    if not chosen:
        raise FaultDidNotApply("no CAD settlement in 2026-09-01 to 2026-09-25 qualifies")
    out = []
    for x, c, s, s_bad, eid in chosen:
        d_bad = s_bad - c
        first, second = sorted(ent[eid], key=lambda ln: ln["line_no"])
        first.update(account="1150", debit=d_bad, credit=ZERO, invoice_id="")
        second.update(account="7100", debit=ZERO, credit=d_bad, invoice_id="")
        out.append({"item": x["item_id"], "charge": x["charge_id"], "entry": eid, "d_bad": float(d_bad), "excess": float(s_bad - s)})
    return {"changed": out}


def r07_refund_as_fee(rec: dict) -> dict:
    r, t = rec["rails"], rec["tables"]
    gl = r["gl_journal_lines"]
    ent = _entries(gl)
    billing = {}
    for rf in t["card_refunds"]:
        billing.setdefault(rf["refund_id"], []).append(rf)
    chosen = None
    for e in sorted((e for e in r["processor_events"] if e["event_type"] == "refund" and _in(e["event_on"], D(2026, 8, 1), D(2026, 8, 31))
                     and e["amount_usd"] > 0), key=lambda e: e["event_id"]):
        if len(billing.get(e["reference"], [])) != 1:
            continue
        amount = billing[e["reference"]][0]["amount"]
        for i in _entry_for(gl, "refund", e["reference"], e["event_on"]):
            rows = [ln for ln in ent[i] if ln["account"] == "4900"]
            if len(ent[i]) in (2, 3) and len(rows) == 1 and rows[0]["debit"] == amount and rows[0]["credit"] == 0:
                chosen = (e, rows[0], i)
                break
        if chosen:
            break
    if chosen is None:
        raise FaultDidNotApply("no August 2026 refund qualifies")
    e, row, eid = chosen
    row["account"] = "6100"
    return {"refund": e["reference"], "entry": eid, "amount": float(row["debit"])}


def r08_dispute_fee_reimbursed(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    opened = {(e["reference"], e["charge_id"]): e for e in r["processor_events"] if e["event_type"] == "dispute_opened"}
    sel = None
    for e in sorted((e for e in r["processor_events"] if e["event_type"] == "dispute_won" and _in(e["event_on"], D(2026, 8, 1), D(2026, 8, 31))
                     and e["amount_usd"] > 0), key=lambda e: e["event_id"]):
        o = opened.get((e["reference"], e["charge_id"]))
        fees = [x for x in r["processor_settlement_items"] if x["item_type"] == "dispute_fee" and x["reference"] == e["reference"]
                and x["charge_id"] == e["charge_id"] and x["amount_usd"] == Decimal("-17.50")]
        if _entry_for(gl, "dispute_won", e["reference"], e["event_on"]) and o is not None and o["event_on"] < e["event_on"] and len(fees) == 1:
            sel = e
            break
    if sel is None:
        raise FaultDidNotApply("no August 2026 dispute win qualifies")
    eid = _add_entry(gl, sel["event_on"], "dispute_won", sel["reference"],
                     [("1150", Decimal("17.50"), ZERO, ""), ("6120", ZERO, Decimal("17.50"), "")])
    return {"dispute": sel["reference"], "new_entry": eid}


def r09_fees_netted_against_billings(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    ent = _entries(gl)
    fee_items: dict = {}
    for x in r["processor_settlement_items"]:
        if x["item_type"] == "fee":
            fee_items.setdefault((x["charge_id"], x["available_on"]), []).append(x)
    chosen = None
    for eid in sorted(ent):
        rows = ent[eid]
        day = rows[0]["posted_on"]
        if not _in(day, D(2026, 6, 1), D(2026, 6, 30)) or any(ln["source_type"] != "fee" for ln in rows):
            continue
        dr = [ln for ln in rows if ln["account"] == "6100" and ln["debit"] > 0]
        cr = [ln for ln in rows if ln["account"] == "1150" and ln["credit"] > 0]
        if len(rows) != 2 or len(dr) != 1 or len(cr) != 1 or dr[0]["debit"] != cr[0]["credit"] or dr[0]["source_id"] != cr[0]["source_id"]:
            continue
        f, c = dr[0]["debit"], dr[0]["source_id"]
        items = [x for x in fee_items.get((c, day), []) if x["amount_usd"] == -f]
        if len(fee_items.get((c, day), [])) == 1 and len(items) == 1:
            chosen = (eid, f, c)
            break
    if chosen is None:
        raise FaultDidNotApply("no June 2026 fee entry qualifies")
    eid, f, c = chosen
    new = _add_entry(gl, D(2026, 6, 30), "fee", c, [("4000", f, ZERO, ""), ("6100", ZERO, f, "")])
    return {"entry_copied_from": eid, "fee": float(f), "charge": c, "new_entry": new}


def r10_payout_cents_truncated(rec: dict) -> dict:
    r = rec["rails"]
    gl = r["gl_journal_lines"]
    apr1, apr30 = D(2026, 4, 1), D(2026, 4, 30)
    sel = sorted((p for p in r["processor_payouts"] if _in(p["created_on"], apr1, apr30) and _in(p["arrival_on"], apr1, apr30)
                  and p["amount_usd"] >= 1 and p["amount_usd"] != Decimal(math.floor(p["amount_usd"]))
                  and len([b for b in r["bank_statement_lines"] if b["counterparty"] == ev.PROCESSOR and b["reference"] == p["payout_id"]
                           and b["posted_on"] == p["arrival_on"] and b["amount"] == p["amount_usd"]]) == 1
                  and _entry_for(gl, "payout", p["payout_id"])), key=lambda p: p["payout_id"])[:2]
    if not sel:
        raise FaultDidNotApply("no April 2026 payout qualifies")
    out = []
    for p in sel:
        a = p["amount_usd"]
        tr = Decimal(math.floor(a)).quantize(Decimal("0.01"))
        p["amount_usd"] = tr
        eid = _entry_for(gl, "payout", p["payout_id"])[0]
        for ln in gl:
            if ln["entry_id"] == eid:
                if ln["account"] == "1000":
                    ln["debit"] = tr
                elif ln["account"] == "1150":
                    ln["credit"] = tr
        out.append({"payout": p["payout_id"], "original": float(a), "truncated": float(tr)})
    return {"changed": out, "cents_lost": float(sum((Decimal(str(x["original"])) - Decimal(str(x["truncated"])) for x in out), Decimal(0)))}


HELD_OUT = [
    ("R01", r01_duplicate_payout_receipt),
    ("R02", r02_fee_rows_dropped),
    ("R03", r03_capture_webhooks_lost),
    ("R04", r04_receipt_stranded_unapplied),
    ("R05", r05_october_payout_in_september),
    ("R06", r06_fx_rate_inverted),
    ("R07", r07_refund_as_fee),
    ("R08", r08_dispute_fee_reimbursed),
    ("R09", r09_fees_netted_against_billings),
    ("R10", r10_payout_cents_truncated),
]
