"""The payment-rail records (DESIGN-rails.md section 2): what the card processor and the bank emit, explicitly synthetic,
written from the generator's own billing records for a seed, never from an extract a fault has touched.

  processor   processor_events, processor_settlement_items, processor_payouts, processor_fx_rates
  bank        bank_statement_lines
  ledger      gl_accounts (the chart; the journal itself is posted by rails/ledger.py)

Billing documents come from a clean warehouse.generate.build(seed): card invoice lines and refunds, contract invoice lines
and payments, and the CRM contracts' accounts. Every random draw here uses its own random.Random(seed + 9001), so the
generator's own draws, and the original company, are untouched. Every rule is an assumption of this study, not a
description of any processor or bank, and no figure is any vendor's price.

Usage: python -B -m rails.events <out dir> [seed]   writes the processor, bank and ledger tables as CSV
"""
from __future__ import annotations

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

from warehouse import generate as g

D = dt.date
SEED_OFFSET = 9001
END = g.BILL_UNTIL                         # the extract's last billing day: no rail event after it is in the records
FX_START = g.SIM_START
CURRENCIES = [("USD", 0.85), ("CAD", 0.08), ("EUR", 0.04), ("GBP", 0.03)]
FX_BASE = {"CAD": Decimal("0.73"), "EUR": Decimal("1.08"), "GBP": Decimal("1.27")}
FX_PERIOD = {"CAD": 300, "EUR": 400, "GBP": 500}
FX_PHASE = {"CAD": 0, "EUR": 1, "GBP": 2}
FX_AMPLITUDE, FX_WOBBLE = 0.03, 0.002
P_DECLINE, RETRY_DAYS = 0.04, 3
P_PARTIAL, PARTIAL_MIN, PARTIAL_SHARE, SECOND_DAYS = 0.02, Decimal("20"), (0.40, 0.80), (1, 5)
LAGS = [(1, 0.6), (2, 0.3), (3, 0.1)]
FEE_PCT, FEE_FIXED, FEE_FX_PCT = Decimal("0.0225"), Decimal("0.22"), Decimal("0.0100")
P_DISPUTE, DISPUTE_DAYS, DISPUTE_FEE = 0.004, (20, 60), Decimal("17.50")
P_WIN, WIN_DAYS = 0.35, (30, 75)
P_REF_RIGHT, P_REF_WRONG = 0.90, 0.06
PROCESSOR = "card processor"

ACCOUNTS = [("1000", "Cash", "asset"), ("1100", "Receivables", "asset"), ("1150", "Processor clearing", "asset"),
            ("2100", "Unapplied cash", "liability"), ("4000", "Billings", "revenue"), ("4900", "Refunds", "contra revenue"),
            ("4910", "Chargebacks", "contra revenue"), ("6100", "Processor fees", "expense"),
            ("6120", "Dispute fees", "expense"), ("7100", "Currency gains and losses", "other")]

COLUMNS = {
    "processor_fx_rates": ["rate_date", "currency", "usd_per_unit"],
    "processor_events": ["event_id", "event_on", "event_type", "charge_id", "invoice_id", "customer_id", "currency",
                         "amount_presentment", "amount_usd", "reference", "detail"],
    "processor_settlement_items": ["item_id", "available_on", "payout_id", "item_type", "charge_id", "reference", "currency",
                                   "amount_presentment", "fx_rate", "amount_usd"],
    "processor_payouts": ["payout_id", "created_on", "arrival_on", "amount_usd", "item_count"],
    "bank_statement_lines": ["line_id", "posted_on", "amount", "counterparty", "reference"],
    "gl_accounts": ["account", "name", "account_type"],
}


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


def is_business(d: D) -> bool:
    return d.weekday() < 5


def next_business(d: D) -> D:
    """The first business day strictly after d."""
    d += dt.timedelta(days=1)
    while not is_business(d):
        d += dt.timedelta(days=1)
    return d


def add_business(d: D, n: int) -> D:
    for _ in range(n):
        d = next_business(d)
    return d


def business_days_between(a: D, b: D) -> int:
    """Business days after a up to and including b (0 when b <= a)."""
    n, d = 0, a
    while d < b:
        d = next_business(d)
        if d <= b:
            n += 1
    return n


def fx_rate(currency: str, day: D) -> Decimal:
    """US$ per unit on a day, on the declared path; 1 for USD."""
    if currency == "USD":
        return Decimal(1)
    t = (day - FX_START).days
    wave = 1 + FX_AMPLITUDE * math.sin(2 * math.pi * t / FX_PERIOD[currency] + FX_PHASE[currency])
    h = int(hashlib.sha256(f"fx|{currency}|{day.isoformat()}".encode()).hexdigest()[:8], 16) / 0xFFFFFFFF
    wobble = 1 + FX_WOBBLE * (2 * h - 1)
    return (FX_BASE[currency] * Decimal(repr(wave * wobble))).quantize(Decimal("0.000001"), rounding=ROUND_HALF_UP)


def present(usd: Decimal, currency: str, day: D) -> Decimal:
    return usd if currency == "USD" else cents(usd / fx_rate(currency, day))


def to_usd(amount: Decimal, currency: str, day: D) -> Decimal:
    return amount if currency == "USD" else cents(amount * fx_rate(currency, day))


def fee(settled_usd: Decimal, currency: str) -> Decimal:
    pct = FEE_PCT + (FEE_FX_PCT if currency != "USD" else Decimal(0))
    return cents(settled_usd * pct + FEE_FIXED)


def pick(rng: random.Random, options):
    r, acc = rng.random(), 0.0
    for value, w in options:
        acc += w
        if r < acc:
            return value
    return options[-1][0]


def card_invoices(tables: dict) -> list[dict]:
    """One row per card invoice, in invoice id order: id, customer, date, total."""
    out: dict = {}
    for x in tables["card_invoice_lines"]:
        r = out.setdefault(x["invoice_id"], {"invoice_id": x["invoice_id"], "customer_id": x["customer_id"],
                                              "invoice_date": x["invoice_date"], "total": Decimal(0)})
        r["total"] += x["amount"]
    return [out[k] for k in sorted(out)]


def contract_invoices(tables: dict) -> list[dict]:
    """One row per contract invoice, in invoice id order: id, contract, account, date, total."""
    account = {c["contract_id"]: c["account_id"] for c in tables["crm_contracts"]}
    out: dict = {}
    for x in tables["contract_invoice_lines"]:
        r = out.setdefault(x["invoice_id"], {"invoice_id": x["invoice_id"], "contract_id": x["contract_id"],
                                              "account_id": account.get(x["contract_id"]), "invoice_date": x["invoice_date"],
                                              "total": Decimal(0)})
        r["total"] += x["amount"]
    return [out[k] for k in sorted(out)]


def build_rails(seed: int = g.SEED, clean: dict | None = None) -> dict:
    """The processor, bank and chart-of-accounts tables for a seed. `clean` is the generator's clean build for the same
    seed (built here when not given); only its billing documents and CRM contracts are read."""
    clean = g.build(seed) if clean is None else clean
    t = clean["tables"]
    rng = random.Random(seed + SEED_OFFSET)

    # ---- card currencies, one per customer
    currency = {c["customer_id"]: pick(rng, CURRENCIES) for c in sorted(t["card_customers"], key=lambda c: c["customer_id"])}

    # ---- charges: every card invoice charged in full on its invoice date (declines retried, partial approvals completed)
    attempts = []    # (day, invoice, usd, kind) where kind is declined / approved / partial
    for inv in card_invoices(t):
        if inv["total"] <= 0:
            continue
        day, total = inv["invoice_date"], inv["total"]
        if rng.random() < P_DECLINE:
            attempts.append((day, inv, total, "declined"))
            day = day + dt.timedelta(days=RETRY_DAYS)
        if total >= PARTIAL_MIN and rng.random() < P_PARTIAL:
            part = cents(total * Decimal(repr(round(rng.uniform(*PARTIAL_SHARE), 4))))
            attempts.append((day, inv, part, "partial"))
            attempts.append((day + dt.timedelta(days=rng.randint(*SECOND_DAYS)), inv, total - part, "approved"))
        else:
            attempts.append((day, inv, total, "approved"))
    attempts = [a for a in attempts if a[0] <= END]
    attempts.sort(key=lambda a: (a[0], a[1]["invoice_id"], a[3] != "declined", a[3] != "partial"))
    charges = []
    for i, (day, inv, usd, kind) in enumerate(attempts, start=1):
        cur = currency[inv["customer_id"]]
        charges.append({"charge_id": f"CH-{i:07d}", "day": day, "invoice_id": inv["invoice_id"], "customer_id": inv["customer_id"],
                        "currency": cur, "usd": usd, "presentment": present(usd, cur, day), "kind": kind})
    captured = [c for c in charges if c["kind"] != "declined"]
    by_invoice: dict = {}
    for c in captured:
        by_invoice.setdefault(c["invoice_id"], []).append(c)

    # ---- settlement lag, one draw per calendar day
    lag, d = {}, FX_START
    while d <= END:
        lag[d] = pick(rng, LAGS)
        d += dt.timedelta(days=1)

    def settle_day(day: D) -> D:
        start = day if is_business(day) else next_business(day)
        return add_business(start, lag[day])

    # ---- refunds: to the card that paid the refunded line's invoice
    line_invoice = {x["line_id"]: x["invoice_id"] for x in t["card_invoice_lines"]}
    refunds = []
    refunded = set()
    for rf in sorted(t["card_refunds"], key=lambda r: r["refund_id"]):
        paid = by_invoice.get(line_invoice[rf["line_id"]])
        if not paid:
            continue
        ch = paid[0]
        day = max(rf["refund_date"], max(c["day"] for c in paid) + dt.timedelta(days=1))
        if day > END:
            continue
        pres = present(rf["amount"], ch["currency"], day)
        refunds.append({"refund_id": rf["refund_id"], "charge": ch, "day": day, "billing_usd": rf["amount"],
                        "presentment": pres, "usd": to_usd(pres, ch["currency"], day)})
        refunded.add(ch["charge_id"])

    # ---- disputes
    disputes = []
    for ch in captured:
        if ch["charge_id"] in refunded or rng.random() >= P_DISPUTE:
            continue
        opened = ch["day"] + dt.timedelta(days=rng.randint(*DISPUTE_DAYS))
        won = rng.random() < P_WIN
        closed = opened + dt.timedelta(days=rng.randint(*WIN_DAYS))
        if opened > END:
            continue
        disputes.append({"dispute_id": f"DP-{len(disputes) + 1:04d}", "charge": ch, "opened": opened,
                         "usd": to_usd(ch["presentment"], ch["currency"], opened), "won": won,
                         "closed": closed if closed <= END else None})

    # ---- processor events
    events = []
    for ch in charges:
        base = {"charge_id": ch["charge_id"], "invoice_id": ch["invoice_id"], "customer_id": ch["customer_id"],
                "currency": ch["currency"], "amount_presentment": ch["presentment"], "amount_usd": ch["usd"], "reference": ""}
        if ch["kind"] == "declined":
            events.append({**base, "event_on": ch["day"], "event_type": "authorization_declined", "detail": "declined"})
            continue
        events.append({**base, "event_on": ch["day"], "event_type": "authorization",
                       "detail": "partial approval" if ch["kind"] == "partial" else ""})
        events.append({**base, "event_on": ch["day"], "event_type": "capture", "detail": ""})
    for rf in refunds:
        ch = rf["charge"]
        events.append({"charge_id": ch["charge_id"], "invoice_id": ch["invoice_id"], "customer_id": ch["customer_id"],
                       "currency": ch["currency"], "amount_presentment": rf["presentment"], "amount_usd": rf["billing_usd"],
                       "reference": rf["refund_id"], "event_on": rf["day"], "event_type": "refund", "detail": ""})
    for dp in disputes:
        ch = dp["charge"]
        base = {"charge_id": ch["charge_id"], "invoice_id": ch["invoice_id"], "customer_id": ch["customer_id"],
                "currency": ch["currency"], "amount_presentment": ch["presentment"], "amount_usd": dp["usd"],
                "reference": dp["dispute_id"], "detail": ""}
        events.append({**base, "event_on": dp["opened"], "event_type": "dispute_opened"})
        if dp["closed"] is not None:
            events.append({**base, "event_on": dp["closed"], "event_type": "dispute_won" if dp["won"] else "dispute_lost",
                           "amount_usd": dp["usd"] if dp["won"] else Decimal(0)})
    order = {"authorization_declined": 0, "authorization": 1, "capture": 2, "refund": 3, "dispute_opened": 4,
             "dispute_won": 5, "dispute_lost": 6}
    events.sort(key=lambda e: (e["event_on"], e["charge_id"], order[e["event_type"]], e["reference"]))
    for i, e in enumerate(events, start=1):
        e["event_id"] = f"EV-{i:07d}"

    # ---- settlement items
    items = []
    for ch in captured:
        day = settle_day(ch["day"])
        if day > END:
            continue
        rate = fx_rate(ch["currency"], day)
        gross = to_usd(ch["presentment"], ch["currency"], day)
        items.append({"available_on": day, "item_type": "charge", "charge_id": ch["charge_id"], "reference": "",
                      "currency": ch["currency"], "amount_presentment": ch["presentment"], "fx_rate": rate, "amount_usd": gross})
        items.append({"available_on": day, "item_type": "fee", "charge_id": ch["charge_id"], "reference": "",
                      "currency": "USD", "amount_presentment": -fee(gross, ch["currency"]), "fx_rate": Decimal(1),
                      "amount_usd": -fee(gross, ch["currency"])})
    for rf in refunds:
        ch, day = rf["charge"], next_business(rf["day"])
        if day <= END:
            items.append({"available_on": day, "item_type": "refund", "charge_id": ch["charge_id"], "reference": rf["refund_id"],
                          "currency": ch["currency"], "amount_presentment": -rf["presentment"],
                          "fx_rate": fx_rate(ch["currency"], rf["day"]), "amount_usd": -rf["usd"]})
    for dp in disputes:
        ch = dp["charge"]
        day = next_business(dp["opened"])
        if day <= END:
            items.append({"available_on": day, "item_type": "dispute", "charge_id": ch["charge_id"], "reference": dp["dispute_id"],
                          "currency": ch["currency"], "amount_presentment": -ch["presentment"],
                          "fx_rate": fx_rate(ch["currency"], dp["opened"]), "amount_usd": -dp["usd"]})
            items.append({"available_on": day, "item_type": "dispute_fee", "charge_id": ch["charge_id"], "reference": dp["dispute_id"],
                          "currency": "USD", "amount_presentment": -DISPUTE_FEE, "fx_rate": Decimal(1), "amount_usd": -DISPUTE_FEE})
        if dp["won"] and dp["closed"] is not None and next_business(dp["closed"]) <= END:
            items.append({"available_on": next_business(dp["closed"]), "item_type": "dispute_reversal", "charge_id": ch["charge_id"],
                          "reference": dp["dispute_id"], "currency": ch["currency"], "amount_presentment": ch["presentment"],
                          "fx_rate": fx_rate(ch["currency"], dp["opened"]), "amount_usd": dp["usd"]})
    korder = {"charge": 0, "fee": 1, "refund": 2, "dispute": 3, "dispute_fee": 4, "dispute_reversal": 5}
    items.sort(key=lambda x: (x["available_on"], x["charge_id"], korder[x["item_type"]], x["reference"]))

    # ---- payouts: each business day, the whole available balance (a negative balance is carried)
    payouts, carried, pending = [], Decimal(0), []
    by_day: dict = {}
    for x in items:
        by_day.setdefault(x["available_on"], []).append(x)
    for day in sorted(by_day):
        pending += by_day[day]
        balance = carried + sum((x["amount_usd"] for x in by_day[day]), Decimal(0))
        if balance > 0:
            pid = f"PO-{len(payouts) + 1:05d}"
            for x in pending:
                x["payout_id"] = pid
            payouts.append({"payout_id": pid, "created_on": day, "arrival_on": next_business(day), "amount_usd": balance,
                            "item_count": len(pending)})
            carried, pending = Decimal(0), []
        else:
            carried = balance
    for x in pending:
        x["payout_id"] = ""
    for i, x in enumerate(items, start=1):
        x["item_id"] = f"SI-{i:07d}"

    # ---- the bank: payouts on arrival, contract payments on their paid day
    cinv = contract_invoices(t)
    inv_by_id = {r["invoice_id"]: r for r in cinv}
    by_account: dict = {}
    for r in cinv:
        by_account.setdefault(r["account_id"], []).append(r)
    bank = [{"posted_on": p["arrival_on"], "amount": p["amount_usd"], "counterparty": PROCESSOR, "reference": p["payout_id"],
             "_order": (0, p["payout_id"])} for p in payouts if p["arrival_on"] <= END]
    for p in sorted(t["contract_payments"], key=lambda r: r["payment_id"]):
        inv = inv_by_id[p["invoice_id"]]
        r = rng.random()
        if r < P_REF_RIGHT:
            ref = p["invoice_id"]
        elif r < P_REF_RIGHT + P_REF_WRONG:
            earlier = [x for x in by_account[inv["account_id"]] if x["invoice_id"] < p["invoice_id"]]
            ref = earlier[-1]["invoice_id"] if earlier else f"KI-{int(p['invoice_id'][3:]) + 1:05d}"
        else:
            ref = ""
        bank.append({"posted_on": p["paid_on"], "amount": p["amount"], "counterparty": inv["account_id"], "reference": ref,
                     "_order": (1, p["payment_id"]), "_payment_id": p["payment_id"]})
    bank.sort(key=lambda b: (b["posted_on"], b["_order"]))
    for i, b in enumerate(bank, start=1):
        b["line_id"] = f"BL-{i:06d}"

    rates = []
    d = FX_START
    while d <= END:
        for cur in ("CAD", "EUR", "GBP"):
            rates.append({"rate_date": d, "currency": cur, "usd_per_unit": fx_rate(cur, d)})
        d += dt.timedelta(days=1)

    return {"processor_fx_rates": rates, "processor_events": events, "processor_settlement_items": items,
            "processor_payouts": payouts, "bank_statement_lines": bank,
            "gl_accounts": [{"account": a, "name": n, "account_type": k} for a, n, k in ACCOUNTS]}


RATE_COLUMNS = {"fx_rate", "usd_per_unit"}


def fmt(v, column: str = "") -> str:
    if column in RATE_COLUMNS and isinstance(v, Decimal):
        return f"{v:.6f}"
    return g.fmt(v)


def serialize(tables: dict, columns: dict | None = None) -> dict[str, bytes]:
    out = {}
    for name, cols in (columns or COLUMNS).items():
        buf = io.StringIO()
        w = csv.writer(buf, lineterminator="\n")
        w.writerow(cols)
        for row in tables[name]:
            w.writerow([fmt(row.get(c), c) for c in cols])
        out[name] = buf.getvalue().encode("utf-8")
    return out


def write(tables: dict, out: Path, columns: dict | None = None) -> dict[str, int]:
    out.mkdir(parents=True, exist_ok=True)
    for name, data in serialize(tables, columns).items():
        (out / f"{name}.csv").write_bytes(data)
    return {name: len(tables[name]) for name in (columns or COLUMNS)}


if __name__ == "__main__":
    import sys
    target = Path(sys.argv[1] if len(sys.argv) > 1 else "runtime/rails/records")
    print(write(build_rails(int(sys.argv[2]) if len(sys.argv) > 2 else g.SEED), target))
