"""The ledger (DESIGN-rails.md section 3): gl_journal_lines posted by rules P1 to P9 from the billing documents and the
payment-rail records of rails/events.py. Each entry balances. The journal is posted once, from the clean company's
records, and is then a record like any other: a fault that edits it edits these rows.

Usage: python -B -m rails.ledger <out dir> [seed]   writes gl_journal_lines.csv beside the rail tables
"""
from __future__ import annotations

from decimal import Decimal
from pathlib import Path

from rails import events as ev
from warehouse import generate as g

COLUMNS = {"gl_journal_lines": ["entry_id", "line_no", "posted_on", "account", "debit", "credit", "source_type", "source_id",
                                "invoice_id"]}
TYPE_ORDER = {"invoice": 0, "capture": 1, "settlement": 2, "fee": 3, "refund": 4, "dispute": 5, "dispute_won": 6,
              "payout": 7, "transfer": 8}
ZERO = Decimal(0)


def entries(tables: dict, rails: dict) -> list[dict]:
    """Every journal entry as {posted_on, source_type, source_id, lines: [(account, debit, credit, invoice_id)]}."""
    out = []

    def add(day, kind, sid, lines):
        out.append({"posted_on": day, "source_type": kind, "source_id": sid, "lines": lines})

    # P1 invoices
    for inv in ev.card_invoices(tables) + ev.contract_invoices(tables):
        add(inv["invoice_date"], "invoice", inv["invoice_id"],
            [("1100", inv["total"], ZERO, inv["invoice_id"]), ("4000", ZERO, inv["total"], "")])
    captures = {}
    for e in rails["processor_events"]:
        if e["event_type"] == "capture":
            captures[e["charge_id"]] = e
            # P2 capture
            add(e["event_on"], "capture", e["charge_id"],
                [("1150", e["amount_usd"], ZERO, ""), ("1100", ZERO, e["amount_usd"], e["invoice_id"])])
        elif e["event_type"] == "refund":
            # P5 refund: billing US$ to 4900, the processor's US$ out of clearing, the difference to 7100
            proc = ev.to_usd(e["amount_presentment"], e["currency"], e["event_on"])
            lines = [("4900", e["amount_usd"], ZERO, ""), ("1150", ZERO, proc, "")]
            diff = e["amount_usd"] - proc
            if diff > 0:
                lines.append(("7100", ZERO, diff, ""))
            elif diff < 0:
                lines.append(("7100", -diff, ZERO, ""))
            add(e["event_on"], "refund", e["reference"], lines)
        elif e["event_type"] == "dispute_opened":
            # P6 dispute and its fee
            add(e["event_on"], "dispute", e["reference"],
                [("4910", e["amount_usd"], ZERO, ""), ("6120", ev.DISPUTE_FEE, ZERO, ""),
                 ("1150", ZERO, e["amount_usd"] + ev.DISPUTE_FEE, "")])
        elif e["event_type"] == "dispute_won":
            # P7 dispute won
            add(e["event_on"], "dispute_won", e["reference"], [("1150", e["amount_usd"], ZERO, ""), ("4910", ZERO, e["amount_usd"], "")])
    for x in rails["processor_settlement_items"]:
        if x["item_type"] == "charge":
            # P3 settlement: the currency difference against the capture
            diff = x["amount_usd"] - captures[x["charge_id"]]["amount_usd"]
            if diff > 0:
                add(x["available_on"], "settlement", x["charge_id"], [("1150", diff, ZERO, ""), ("7100", ZERO, diff, "")])
            elif diff < 0:
                add(x["available_on"], "settlement", x["charge_id"], [("7100", -diff, ZERO, ""), ("1150", ZERO, -diff, "")])
        elif x["item_type"] == "fee":
            # P4 fee
            add(x["available_on"], "fee", x["charge_id"], [("6100", -x["amount_usd"], ZERO, ""), ("1150", ZERO, -x["amount_usd"], "")])
    paid = {p["payment_id"]: p["invoice_id"] for p in tables["contract_payments"]}
    for b in rails["bank_statement_lines"]:
        if b["counterparty"] == ev.PROCESSOR:
            # P8 payout, on the bank arrival day
            add(b["posted_on"], "payout", b["reference"], [("1000", b["amount"], ZERO, ""), ("1150", ZERO, b["amount"], "")])
        else:
            # P9 contract payment: to the invoice the receivables team applied it to, else unapplied
            inv = paid.get(b.get("_payment_id", ""))
            credit = ("1100", ZERO, b["amount"], inv) if inv else ("2100", ZERO, b["amount"], "")
            add(b["posted_on"], "transfer", b["line_id"], [("1000", b["amount"], ZERO, ""), credit])
    out.sort(key=lambda x: (x["posted_on"], TYPE_ORDER[x["source_type"]], x["source_id"]))
    return out


def post(tables: dict, rails: dict) -> list[dict]:
    """gl_journal_lines rows, one per entry line, entries numbered in posting order."""
    rows = []
    for i, e in enumerate(entries(tables, rails), start=1):
        dr = sum((l[1] for l in e["lines"]), ZERO)
        cr = sum((l[2] for l in e["lines"]), ZERO)
        assert dr == cr, f"entry {i} does not balance"
        for n, (acct, debit, credit, inv) in enumerate(e["lines"], start=1):
            rows.append({"entry_id": f"JE-{i:07d}", "line_no": n, "posted_on": e["posted_on"], "account": acct, "debit": debit,
                         "credit": credit, "source_type": e["source_type"], "source_id": e["source_id"], "invoice_id": inv})
    return rows


def build_records(seed: int = g.SEED, clean: dict | None = None) -> dict:
    """The rail tables and the ledger for a seed, from the clean company's billing documents."""
    clean = g.build(seed) if clean is None else clean
    rails = ev.build_rails(seed, clean)
    rails["gl_journal_lines"] = post(clean["tables"], rails)
    return rails


ALL_COLUMNS = {**ev.COLUMNS, **COLUMNS}


def serialize(rails: dict) -> dict[str, bytes]:
    return ev.serialize(rails, ALL_COLUMNS)


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