"""The 12 blind faults, each implemented once and literally from blind/author-specs.json (DESIGN-blind.md section 6).

The author wrote the specs without seeing the checks. Each function below quotes nothing new: its docstring names the
spec, the code follows the spec's selection rule and changes, and every reading an ambiguous phrase forced is listed in
blind/JUDGEMENTS.md under the fault's id. The author's general rules (blind/author-general-rules.txt) apply to all:
selections are evaluated on the original extract before any change, ids sort ascending, fewer matches than asked
means all of them, money rounds to cents half up.

One rule is replaced by the protocol: where the author says "if none qualify, make no changes", the function raises
FaultDidNotApply instead, and the fault is reported as not applied (a fault that changes nothing would score as a miss
it never was). Each function edits only the build's extracts, in place, and returns a census of what it touched.
"""
from __future__ import annotations

import datetime as dt
from decimal import Decimal

from warehouse import generate as g

D = dt.date
LAST = g.LAST_DAY                      # 2026-09-30
BILL_UNTIL = g.BILL_UNTIL              # 2026-10-05
JUL1, JUL31, AUG31 = D(2026, 7, 1), D(2026, 7, 31), D(2026, 8, 31)
SEP1 = D(2026, 9, 1)
OCT1, OCT5 = D(2026, 10, 1), D(2026, 10, 5)
FAR = D(2030, 1, 1)


class FaultDidNotApply(RuntimeError):
    pass


def _need(n: int, what: str) -> int:
    if n <= 0:
        raise FaultDidNotApply(what)
    return n


# ------------------------------------------------------------------------------------------------- shared lookups

def _by(rows, key):
    out = {}
    for r in rows:
        out.setdefault(r[key], []).append(r)
    return out


def _in_service(c) -> bool:
    return c["service_start"] <= LAST <= c["service_end"]


def _tier_on(tiers, day):
    hits = [t for t in tiers if t["tier_start"] <= day <= t["tier_end"]]
    return hits


def _f(discount) -> Decimal:
    return (Decimal(100) - Decimal(discount)) / Decimal(100)


def _contract_recurring(value: Decimal, discount, freq: str) -> Decimal:
    """SYSTEMS.md: tier x (1 - discount) x months in the period / 12, as the generator computes it."""
    return g.cents(value * _f(discount) * g.STEP[freq] / 12)


def _invoice_totals(lines) -> dict:
    out: dict = {}
    for x in lines:
        out[x["invoice_id"]] = out.get(x["invoice_id"], Decimal(0)) + x["amount"]
    return out


def _events(t) -> dict:
    ev = _by(t["card_seat_changes"], "subscription_id")
    return {k: sorted(v, key=lambda e: (e["effective_date"], e["change_id"])) for k, v in ev.items()}


def _usage_bill(r) -> tuple[D, str]:
    """The author's general rule: billed on day 5 of the next month if loaded before that day's midnight, else day 5 of
    the month after, as usage_late."""
    month = D(r["usage_date"].year, r["usage_date"].month, 1)
    late = r["loaded_at"] >= g.usage_cutoff(month)
    return g.add_months(month, 2 if late else 1).replace(day=5), ("usage_late" if late else "usage")


def _self_serve_workspaces(t) -> list[str]:
    """Shared by B04, B09 and B10: workspaces with exactly one card customer, whose customer has exactly one
    subscription in total, that subscription started on or before 2026-07-01 and has not ended, with no CRM account
    linked to the workspace, whose latest plan change on or before 2026-07-01 is self_serve and with no plan change
    after 2026-07-01 through 2026-09-30 (JUDGEMENTS.md, B04 and B09)."""
    customers = _by(t["card_customers"], "workspace_id")
    subs = _by(t["card_subscriptions"], "customer_id")
    linked = {a["workspace_id"] for a in t["crm_accounts"] if a["workspace_id"]}
    plans = _by(t["product_plan_changes"], "workspace_id")
    out = []
    for w in sorted(r["workspace_id"] for r in t["product_workspaces"]):
        cs = customers.get(w, [])
        if len(cs) != 1:
            continue
        ss = subs.get(cs[0]["customer_id"], [])
        if len(ss) != 1 or not (ss[0]["started_on"] <= JUL1 and ss[0]["ended_on"] is None):
            continue
        if w in linked:
            continue
        ps = sorted(plans.get(w, []), key=lambda p: p["effective_date"])
        before = [p for p in ps if p["effective_date"] <= JUL1]
        if not before or before[-1]["plan_kind"] != "self_serve":
            continue
        if any(JUL1 < p["effective_date"] <= LAST for p in ps):
            continue
        out.append(w)
    return out


# ------------------------------------------------------------------------------------------------- the 12 faults

def b01_contract_prices_doubled(b: dict) -> dict:
    """B01 (systems agree): contract prices doubled during CRM import."""
    t = b["tables"]
    tiers = _by(t["crm_contract_tiers"], "contract_id")
    opps = {o["opportunity_id"]: o for o in t["crm_opportunities"]}
    service_credit = {c["contract_id"] for c in t["contract_credits"] if c["credit_type"] == "service"}
    picks = []
    for c in sorted(t["crm_contracts"], key=lambda c: c["contract_id"]):
        ts = tiers.get(c["contract_id"], [])
        cover = _tier_on(ts, LAST)
        o = opps.get(c["opportunity_id"])
        if not (_in_service(c) and c["discount_pct"] < 100 and len(cover) == 1 and cover[0]["annual_list_value"] > 0
                and c["contract_id"] not in service_credit and o is not None and o["stage"] == "closed_won"
                and len(ts) == 1 and ts[0]["tier_start"] == c["service_start"] and ts[0]["tier_end"] == c["service_end"]):
            continue
        picks.append(c)
        if len(picks) == 2:
            break
    _need(len(picks), "no contract qualifies")
    lines_changed, payments_changed = 0, 0
    for c in picks:
        ts = tiers[c["contract_id"]]
        for tr in ts:
            tr["annual_list_value"] = tr["annual_list_value"] * 2
        f = _f(c["discount_pct"])
        opps[c["opportunity_id"]]["amount"] = g.cents(sum(
            tr["annual_list_value"] * f * Decimal(g.months_between(tr["tier_start"], tr["tier_end"] + dt.timedelta(days=1))) / 12
            for tr in ts))
        invoices = set()
        for x in t["contract_invoice_lines"]:
            if x["contract_id"] == c["contract_id"] and x["line_type"] == "recurring":
                tier = _tier_on(ts, x["period_start"])[0]
                x["amount"] = _contract_recurring(tier["annual_list_value"], c["discount_pct"], c["billing_frequency"])
                invoices.add(x["invoice_id"])
                lines_changed += 1
        totals = _invoice_totals(t["contract_invoice_lines"])
        for p in t["contract_payments"]:
            if p["invoice_id"] in invoices:
                p["amount"] = totals[p["invoice_id"]]
                payments_changed += 1
    return {"contracts": [c["contract_id"] for c in picks], "recurring_lines_changed": lines_changed,
            "payments_changed": payments_changed}


def b02_discount_omitted(b: dict) -> dict:
    """B02 (systems agree): negotiated contract discount omitted everywhere."""
    t = b["tables"]
    tiers = _by(t["crm_contract_tiers"], "contract_id")
    opps = {o["opportunity_id"]: o for o in t["crm_opportunities"]}
    per_account = _by(t["crm_contracts"], "account_id")
    service_credit = {c["contract_id"] for c in t["contract_credits"] if c["credit_type"] == "service"}
    picks = []
    for c in sorted(t["crm_contracts"], key=lambda c: c["contract_id"]):
        cover = _tier_on(tiers.get(c["contract_id"], []), LAST)
        o = opps.get(c["opportunity_id"])
        if not (_in_service(c) and 0 < c["discount_pct"] < 100 and len(cover) == 1 and cover[0]["annual_list_value"] > 0
                and o is not None and o["stage"] == "closed_won" and o["opportunity_type"] == "new"
                and len(per_account[c["account_id"]]) == 1 and c["contract_id"] not in service_credit):
            continue
        picks.append(c)
        if len(picks) == 2:
            break
    _need(len(picks), "no contract qualifies")
    original = {c["contract_id"]: c["discount_pct"] for c in picks}
    lines_changed, payments_changed = 0, 0
    for c in picks:
        c["discount_pct"] = 0
        ts = tiers[c["contract_id"]]
        opps[c["opportunity_id"]]["amount"] = g.cents(sum(
            tr["annual_list_value"] * Decimal(g.months_between(tr["tier_start"], tr["tier_end"] + dt.timedelta(days=1))) / 12
            for tr in ts))
        invoices = set()
        for x in t["contract_invoice_lines"]:
            if x["contract_id"] == c["contract_id"] and x["line_type"] == "recurring":
                tier = _tier_on(ts, x["period_start"])[0]
                x["amount"] = _contract_recurring(tier["annual_list_value"], 0, c["billing_frequency"])
                invoices.add(x["invoice_id"])
                lines_changed += 1
        totals = _invoice_totals(t["contract_invoice_lines"])
        for p in t["contract_payments"]:
            if p["invoice_id"] in invoices:
                p["amount"] = totals[p["invoice_id"]]
                payments_changed += 1
    return {"contracts": [c["contract_id"] for c in picks], "original_discounts": original,
            "recurring_lines_changed": lines_changed, "payments_changed": payments_changed}


def b03_card_coupon_lost(b: dict) -> dict:
    """B03 (systems agree): lifetime card coupon lost at subscription creation."""
    t = b["tables"]
    customers = {c["customer_id"]: c for c in t["card_customers"]}
    subs_per_customer = _by(t["card_subscriptions"], "customer_id")
    linked = {a["workspace_id"] for a in t["crm_accounts"] if a["workspace_id"]}
    prices = {p["price_id"]: p for p in t["card_price_list"]}
    events = _events(t)
    picks = []
    for s in sorted(t["card_subscriptions"], key=lambda s: s["subscription_id"]):
        seats = g.seats_on([(e["effective_date"], e["seats_after"]) for e in events.get(s["subscription_id"], [])], LAST)
        p = prices.get(s["price_id"])
        if not (s["started_on"] <= LAST and s["ended_on"] is None and s["recurring_discount_pct"] == 20 and seats > 0
                and len(subs_per_customer[s["customer_id"]]) == 1
                and customers[s["customer_id"]]["workspace_id"] not in linked
                and p is not None and p["billing_interval"] in ("monthly", "annual")):
            continue
        picks.append(s)
        if len(picks) == 3:
            break
    _need(len(picks), "no subscription qualifies")
    by_sub = {s["subscription_id"]: s for s in picks}
    changed = {"recurring": 0, "proration": 0, "refunds": 0}
    line_ids = set()
    for x in t["card_invoice_lines"]:
        s = by_sub.get(x["subscription_id"])
        if s is None or x["line_type"] not in ("recurring", "proration"):
            continue
        unit = prices[s["price_id"]]["unit_amount"]
        if x["line_type"] == "recurring":
            x["amount"] = g.cents(x["quantity"] * unit)
        else:
            interval = prices[s["price_id"]]["billing_interval"]
            ps, pe = next((a, z) for a, z in g.card_periods(s["started_on"], interval, None, FAR) if a <= x["invoice_date"] <= z)
            x["amount"] = g.cents(x["quantity"] * unit * ((pe - x["invoice_date"]).days + 1) / ((pe - ps).days + 1))
        changed[x["line_type"]] += 1
        line_ids.add(x["line_id"])
    lines = {x["line_id"]: x for x in t["card_invoice_lines"]}
    for r in t["card_refunds"]:
        if r["line_id"] in line_ids:   # none expected: the selected subscriptions have not ended
            x, s = lines[r["line_id"]], by_sub[lines[r["line_id"]]["subscription_id"]]
            r["amount"] = g.cents(x["amount"] * (x["period_end"] - s["ended_on"]).days
                                  / ((x["period_end"] - x["period_start"]).days + 1))
            changed["refunds"] += 1
    for s in picks:
        s["recurring_discount_pct"] = 0
    return {"subscriptions": [s["subscription_id"] for s in picks], **{f"{k}_changed": v for k, v in changed.items()}}


def b04_usage_runs_doubled(b: dict) -> dict:
    """B04 (systems agree): metering counts every run twice before billing."""
    t = b["tables"]
    monthly = _by(t["product_workspace_monthly"], "workspace_id")
    usage = _by(t["usage_daily"], "workspace_id")
    card_usage = [x for x in t["card_invoice_lines"] if x["line_type"] in ("usage", "usage_late")]
    picks, groups_by_ws = [], {}
    for w in _self_serve_workspaces(t):
        ok = all(sum(1 for r in monthly.get(w, []) if r["month_end"] == me and r["plan_kind"] == "self_serve") == 1
                 for me in (JUL31, AUG31, LAST))
        rows = [r for r in usage.get(w, []) if JUL1 <= r["usage_date"] <= LAST]
        timely = any(r["runs"] > 0 and r["loaded_at"] < g.usage_cutoff(D(r["usage_date"].year, r["usage_date"].month, 1))
                     for r in rows)
        if not (ok and timely):
            continue
        groups = {}
        for r in rows:
            bill, kind = _usage_bill(r)
            month = D(r["usage_date"].year, r["usage_date"].month, 1)
            groups.setdefault((month, bill, kind), []).append(r)
        matched = {}
        for (month, bill, kind) in groups:
            if bill > BILL_UNTIL:
                continue
            hits = [x for x in card_usage if x["workspace_id"] == w and x["period_start"] == month
                    and x["period_end"] == g.month_end(month) and x["invoice_date"] == bill and x["line_type"] == kind]
            if len(hits) != 1:
                break
            matched[(month, bill, kind)] = hits[0]
        else:
            picks.append(w)
            groups_by_ws[w] = (groups, matched)
            if len(picks) == 2:
                break
    _need(len(picks), "no workspace qualifies")
    rows_doubled, lines_changed = 0, 0
    for w in picks:
        groups, matched = groups_by_ws[w]
        for rows in groups.values():
            for r in rows:
                r["runs"] = r["runs"] * 2
                rows_doubled += 1
        for key, x in matched.items():
            x["quantity"] = sum(r["runs"] for r in groups[key])
            x["amount"] = g.cents(x["quantity"] * g.RUN_PRICE)
            lines_changed += 1
    return {"workspaces": picks, "usage_rows_doubled": rows_doubled, "invoice_lines_changed": lines_changed}


def b05_ramp_tier_overwritten(b: dict) -> dict:
    """B05 (systems disagree): current ramp price overwritten with the prior year's price."""
    t = b["tables"]
    tiers = _by(t["crm_contract_tiers"], "contract_id")
    lines = _by(t["contract_invoice_lines"], "contract_id")
    picks = []
    for c in sorted(t["crm_contracts"], key=lambda c: c["contract_id"]):
        if not (_in_service(c) and c["discount_pct"] < 100):
            continue
        ts = tiers.get(c["contract_id"], [])
        cover = _tier_on(ts, LAST)
        if len(cover) != 1 or cover[0]["tier"] < 2:
            continue
        cur = cover[0]
        prev = [x for x in ts if x["tier"] == cur["tier"] - 1]
        if len(prev) != 1 or not (0 < prev[0]["annual_list_value"] < cur["annual_list_value"]):
            continue
        want = _contract_recurring(cur["annual_list_value"], c["discount_pct"], c["billing_frequency"])
        if not any(x["line_type"] == "recurring" and cur["tier_start"] <= x["period_start"] <= cur["tier_end"]
                   and x["invoice_date"] <= BILL_UNTIL and x["amount"] == want for x in lines.get(c["contract_id"], [])):
            continue
        picks.append((c, cur, prev[0]))
        if len(picks) == 2:
            break
    _need(len(picks), "no contract qualifies")
    out = []
    for c, cur, prev in picks:
        out.append({"contract": c["contract_id"], "tier": cur["tier"], "from": float(cur["annual_list_value"]),
                    "to": float(prev["annual_list_value"])})
        cur["annual_list_value"] = prev["annual_list_value"]
    return {"tiers_changed": out}


def b06_seat_increase_missing(b: dict) -> dict:
    """B06 (systems disagree): latest billed seat increase missing from the extract."""
    t = b["tables"]
    events = _events(t)
    prorations = [x for x in t["card_invoice_lines"] if x["line_type"] == "proration"]
    picks = []
    for s in sorted(t["card_subscriptions"], key=lambda s: s["subscription_id"]):
        if not (s["ended_on"] is None and s["started_on"] < SEP1):
            continue
        ev = events.get(s["subscription_id"], [])
        if len(ev) < 2:
            continue
        latest, pred = ev[-1], ev[-2]
        if not (SEP1 <= latest["effective_date"] <= LAST and latest["seats_after"] > pred["seats_after"]):
            continue
        if sum(1 for e in ev if e["effective_date"] == latest["effective_date"]) != 1:
            continue
        inc = latest["seats_after"] - pred["seats_after"]
        if not any(x["subscription_id"] == s["subscription_id"] and x["invoice_date"] == latest["effective_date"]
                   and x["amount"] > 0 and x["quantity"] == inc for x in prorations):
            continue
        picks.append(latest)
        if len(picks) == 3:
            break
    _need(len(picks), "no subscription qualifies")
    gone = {e["change_id"] for e in picks}
    t["card_seat_changes"] = [e for e in t["card_seat_changes"] if e["change_id"] not in gone]
    return {"seat_changes_deleted": sorted(gone), "subscriptions": [e["subscription_id"] for e in picks]}


def b07_seat_decrease_backdated(b: dict) -> dict:
    """B07 (systems disagree): scheduled seat decrease backdated by one billing period."""
    t = b["tables"]
    events = _events(t)
    prices = {p["price_id"]: p for p in t["card_price_list"]}
    recurring = [x for x in t["card_invoice_lines"] if x["line_type"] == "recurring"]
    picks = []
    for s in sorted(t["card_subscriptions"], key=lambda s: s["subscription_id"]):
        if not (prices[s["price_id"]]["billing_interval"] == "monthly" and s["ended_on"] is None):
            continue
        ev = events.get(s["subscription_id"], [])
        if len(ev) < 2:
            continue
        latest, pred = ev[-1], ev[-2]
        starts = [a for a, _ in g.card_periods(s["started_on"], "monthly", None, FAR)]
        if not (OCT1 <= latest["effective_date"] <= OCT5 and latest["effective_date"] in starts):
            continue
        before = [a for a in starts if a < latest["effective_date"] and a.year == 2026 and a.month == 9]
        if not before:
            continue
        p = before[-1]
        if not (pred["effective_date"] < p and pred["seats_after"] > latest["seats_after"] > 0):
            continue
        if any(e is not latest and e["effective_date"] >= p for e in ev):
            continue
        if not any(x["subscription_id"] == s["subscription_id"] and x["period_start"] == p
                   and x["quantity"] == pred["seats_after"] for x in recurring):
            continue
        picks.append((latest, p))
        if len(picks) == 2:
            break
    _need(len(picks), "no monthly subscription has a seat decrease effective 1 to 5 October 2026 in the extract")
    for e, p in picks:
        e["effective_date"] = p
    return {"seat_changes_backdated": [e["change_id"] for e, _ in picks]}


def b08_migration_link_erased(b: dict) -> dict:
    """B08 (systems disagree): workspace link erased on migrated CRM accounts."""
    t = b["tables"]
    opps = {o["opportunity_id"]: o for o in t["crm_opportunities"]}
    contracts = _by(t["crm_contracts"], "account_id")
    customers = _by(t["card_customers"], "workspace_id")
    subs = _by(t["card_subscriptions"], "customer_id")
    picks = []
    for a in sorted(t["crm_accounts"], key=lambda a: a["account_id"]):
        if not a["workspace_id"]:
            continue
        eligible = False
        for c in sorted(contracts.get(a["account_id"], []), key=lambda c: c["contract_id"]):
            o = opps.get(c["opportunity_id"])
            if not (_in_service(c) and o and o["stage"] == "closed_won" and o["opportunity_type"] == "migration"):
                continue
            day_before = c["service_start"] - dt.timedelta(days=1)
            if any(s["ended_on"] == day_before for cu in customers.get(a["workspace_id"], [])
                   for s in subs.get(cu["customer_id"], [])):
                eligible = True
                break
        if eligible:
            picks.append(a)
            if len(picks) == 2:
                break
    _need(len(picks), "no account qualifies")
    out = [(a["account_id"], a["workspace_id"]) for a in picks]
    for a in picks:
        a["workspace_id"] = None
    return {"accounts_unlinked": [x[0] for x in out], "workspaces": [x[1] for x in out]}


def _sep_usage_workspace(t) -> tuple[str, list[dict]]:
    """B09 and B10: the lowest qualifying workspace and its timely positive September rows (usage_date, usage_id)."""
    usage = _by(t["usage_daily"], "workspace_id")
    cutoff = dt.datetime(2026, 10, 5, 0, 0, 0)
    for w in _self_serve_workspaces(t):
        sep_lines = [x for x in t["card_invoice_lines"] if x["workspace_id"] == w and x["line_type"] in ("usage", "usage_late")
                     and x["invoice_date"] == OCT5 and x["period_start"] == SEP1 and x["period_end"] == LAST]
        if len(sep_lines) != 1:
            continue
        rows = sorted((r for r in usage.get(w, []) if SEP1 <= r["usage_date"] <= LAST and r["runs"] > 0
                       and r["loaded_at"] < cutoff), key=lambda r: (r["usage_date"], r["usage_id"]))
        if rows:
            return w, rows
    raise FaultDidNotApply("no workspace qualifies")


def b09_september_usage_partly_missing(b: dict) -> dict:
    """B09 (systems disagree): September usage partition partially omitted."""
    t = b["tables"]
    w, rows = _sep_usage_workspace(t)
    gone = {r["usage_id"] for r in rows[:20]}
    runs = sum(r["runs"] for r in rows[:20])
    t["usage_daily"] = [r for r in t["usage_daily"] if r["usage_id"] not in gone]
    return {"workspace": w, "usage_rows_deleted": _need(len(gone), "no rows"), "runs_deleted": runs}


def b10_usage_load_time_replaced(b: dict) -> dict:
    """B10 (systems disagree): warehouse load timestamps substituted for metering arrival times."""
    t = b["tables"]
    w, rows = _sep_usage_workspace(t)
    picks = rows[:10]
    for r in picks:
        r["loaded_at"] = dt.datetime(2026, 10, 5, 2, 0, 0)
    return {"workspace": w, "usage_rows_retimed": _need(len(picks), "no rows"), "runs_retimed": sum(r["runs"] for r in picks)}


def b11_renewal_charge_missing(b: dict) -> dict:
    """B11 (systems disagree): paid contract renewal charge missing from the invoice extract."""
    t = b["tables"]
    contracts = {c["contract_id"]: c for c in t["crm_contracts"]}
    payments = _by(t["contract_payments"], "invoice_id")
    totals = _invoice_totals(t["contract_invoice_lines"])
    first_per_invoice = {}
    for x in sorted(t["contract_invoice_lines"], key=lambda x: x["line_id"]):
        c = contracts.get(x["contract_id"])
        pays = payments.get(x["invoice_id"], [])
        if not (x["line_type"] == "recurring" and x["amount"] > 0 and SEP1 <= x["invoice_date"] <= LAST
                and c is not None and _in_service(c) and len(pays) == 1 and pays[0]["amount"] == totals[x["invoice_id"]]):
            continue
        first_per_invoice.setdefault(x["invoice_id"], x)
    picks = sorted(first_per_invoice.values(), key=lambda x: x["line_id"])[:2]
    _need(len(picks), "no recurring line qualifies")
    gone = {x["line_id"] for x in picks}
    t["contract_invoice_lines"] = [x for x in t["contract_invoice_lines"] if x["line_id"] not in gone]
    return {"lines_deleted": sorted(gone), "contracts": sorted({x["contract_id"] for x in picks}),
            "amount": float(sum(x["amount"] for x in picks))}


def b12_payment_replayed(b: dict) -> dict:
    """B12 (systems disagree): bank transfer replayed as a second contract payment."""
    t = b["tables"]
    payments = _by(t["contract_payments"], "invoice_id")
    totals = _invoice_totals(t["contract_invoice_lines"])
    pick = None
    for p in sorted(t["contract_payments"], key=lambda p: p["payment_id"]):
        if (SEP1 <= p["paid_on"] <= LAST and p["amount"] > 0 and len(payments[p["invoice_id"]]) == 1
                and p["invoice_id"] in totals and totals[p["invoice_id"]] == p["amount"]):
            pick = p
            break
    _need(1 if pick else 0, "no payment qualifies")
    used = {int(p["payment_id"].split("-")[1]) for p in t["contract_payments"]}
    n = next(i for i in range(1, len(used) + 2) if i not in used)
    new = {"payment_id": f"PAY-{n:05d}", "invoice_id": pick["invoice_id"], "paid_on": pick["paid_on"], "amount": pick["amount"]}
    t["contract_payments"].append(new)
    return {"payment_copied": pick["payment_id"], "payment_added": new["payment_id"], "invoice": pick["invoice_id"],
            "amount": float(pick["amount"])}


FAULTS = [
    ("B01", b01_contract_prices_doubled), ("B02", b02_discount_omitted), ("B03", b03_card_coupon_lost),
    ("B04", b04_usage_runs_doubled), ("B05", b05_ramp_tier_overwritten), ("B06", b06_seat_increase_missing),
    ("B07", b07_seat_decrease_backdated), ("B08", b08_migration_link_erased), ("B09", b09_september_usage_partly_missing),
    ("B10", b10_usage_load_time_replaced), ("B11", b11_renewal_charge_missing), ("B12", b12_payment_replayed),
]
