"""The five new check families (DESIGN-rails.md section 4), run at a month-end close E on the billing extracts, the
payment-rail records and the ledger, with every record dated up to E plus 5 days. Each returns the keys it flags; a
family fires at a close when it flags at least one key.

The tolerances and windows below are the declared ones; they are pinned by hash with this file (DESIGN-rails.md
section 10) and never change after a result is seen.
"""
from __future__ import annotations

import bisect
import datetime as dt
from decimal import Decimal

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

D = dt.date
FAMILIES = ["three_way_match", "payout_reconciliation", "cash_application", "month_end_cutoff", "ledger_tieout"]
WINDOW_DAYS = 5                       # the close is worked with records dated up to E + 5
CUTOFF_DAYS = 5                       # cut-off looks at records posting within 5 days either side of E
MATCH_TOL = Decimal("0.01")           # three-way match, payout reconciliation and cash application, per item
TIEOUT_TOL = Decimal("1.00")          # ledger tie-out, per account
BANK_DAYS = (1, 3)                    # a payout reaches the bank 1 to 3 business days after it is created
ACCOUNTS = [a for a, _, _ in ev.ACCOUNTS]
ZERO = Decimal(0)


def closes() -> list[D]:
    """The 18 month-end closes of the reported period, April 2025 to September 2026."""
    return [g.month_end(m) for m in g.month_starts(g.REPORT_START, g.LAST_DAY)]


def _dec(v) -> Decimal:
    return v if isinstance(v, Decimal) else Decimal(str(v or 0))


class Cum:
    """Amounts by day; at(E) is the sum of every amount dated on or before E."""

    def __init__(self):
        self.rows: list[tuple[D, Decimal]] = []
        self.days: list[D] = []
        self.sums: list[Decimal] = []

    def add(self, day: D, amount: Decimal):
        self.rows.append((day, amount))

    def done(self) -> "Cum":
        self.rows.sort(key=lambda r: r[0])
        total = ZERO
        for d, a in self.rows:
            total += a
            self.days.append(d)
            self.sums.append(total)
        return self

    def at(self, day: D) -> Decimal:
        i = bisect.bisect_right(self.days, day)
        return self.sums[i - 1] if i else ZERO


class Company:
    """One company's extracts and records, indexed once; flags(close) runs every family at that close."""

    def __init__(self, tables: dict, rails: dict):
        t, r = tables, rails
        self.t, self.r = t, r
        self.card_inv = {x["invoice_id"]: x for x in ev.card_invoices(t)}
        self.con_inv = {x["invoice_id"]: x for x in ev.contract_invoices(t)}
        self.captures = [e for e in r["processor_events"] if e["event_type"] == "capture"]
        self.capture_of = {}
        for e in self.captures:
            self.capture_of.setdefault(e["charge_id"], e)
        self.caps_by_invoice: dict = {}
        for e in self.captures:
            self.caps_by_invoice.setdefault(e["invoice_id"], []).append(e)
        items = r["processor_settlement_items"]
        self.charge_items: dict = {}
        for x in items:
            if x["item_type"] == "charge":
                self.charge_items.setdefault(x["charge_id"], []).append(x)
        self.items_by_payout: dict = {}
        for x in items:
            if x["payout_id"]:
                self.items_by_payout.setdefault(x["payout_id"], []).append(x)
        self.payouts = {p["payout_id"]: p for p in r["processor_payouts"]}
        self.bank = sorted(r["bank_statement_lines"], key=lambda b: (b["posted_on"], b["line_id"]))
        self.bank_by_ref: dict = {}
        for b in self.bank:
            if b["counterparty"] == ev.PROCESSOR:
                self.bank_by_ref.setdefault(b["reference"], []).append(b)
        self.gl = r["gl_journal_lines"]
        self.gl_by_source: dict = {}
        for line in self.gl:
            self.gl_by_source.setdefault((line["source_type"], line["source_id"]), []).append(line)
        self.disputes = {e["reference"]: e for e in r["processor_events"] if e["event_type"] == "dispute_opened"}
        self._cash_rule()
        self._rule_days()
        self._balances()

    # ---- family 3's rule, applied once over the whole bank history (each line depends only on earlier lines)
    def _cash_rule(self):
        open_bal = {k: v["total"] for k, v in self.con_inv.items()}
        by_account: dict = {}
        for v in sorted(self.con_inv.values(), key=lambda v: (v["invoice_date"], v["invoice_id"])):
            by_account.setdefault(v["account_id"], []).append(v)
        self.rule: dict = {}
        for b in self.bank:
            if b["counterparty"] == ev.PROCESSOR:
                continue
            day, amt, payer = b["posted_on"], _dec(b["amount"]), b["counterparty"]
            target = None
            named = self.con_inv.get(b["reference"])
            if (named is not None and named["account_id"] == payer and named["invoice_date"] <= day
                    and open_bal[named["invoice_id"]] > 0 and amt <= open_bal[named["invoice_id"]] + MATCH_TOL):
                target = named["invoice_id"]
            else:
                same = [v for v in by_account.get(payer, []) if v["invoice_date"] <= day and open_bal[v["invoice_id"]] > 0
                        and abs(open_bal[v["invoice_id"]] - amt) <= MATCH_TOL]
                if same:
                    target = same[0]["invoice_id"]
            if target is not None:
                open_bal[target] -= amt
            self.rule[b["line_id"]] = (target or "2100", amt)

    # ---- family 4: each record's posting day under the rules of DESIGN-rails.md section 3
    def _rule_days(self):
        days: dict = {}
        for k, v in self.card_inv.items():
            days[("invoice", k)] = v["invoice_date"]
        for k, v in self.con_inv.items():
            days[("invoice", k)] = v["invoice_date"]
        for e in self.r["processor_events"]:
            kind = {"capture": "capture", "refund": "refund", "dispute_opened": "dispute", "dispute_won": "dispute_won"}.get(e["event_type"])
            if kind:
                days[(kind, e["charge_id"] if kind == "capture" else e["reference"])] = e["event_on"]
        for x in self.r["processor_settlement_items"]:
            if x["item_type"] in ("charge", "fee"):
                days[("settlement" if x["item_type"] == "charge" else "fee", x["charge_id"])] = x["available_on"]
        for p in self.payouts.values():
            days[("payout", p["payout_id"])] = p["arrival_on"]
        for b in self.bank:
            if b["counterparty"] == ev.PROCESSOR:
                days[("payout", b["reference"])] = b["posted_on"]
            else:
                days[("transfer", b["line_id"])] = b["posted_on"]
        self.rule_days = sorted((d, k) for k, d in days.items())
        self.rule_day_list = [d for d, _ in self.rule_days]

    # ---- family 5: the ledger's balances and the balances rebuilt from the source records
    def _balances(self):
        self.gl_cum = {a: Cum() for a in ACCOUNTS}
        for line in self.gl:
            self.gl_cum.setdefault(line["account"], Cum()).add(line["posted_on"], _dec(line["debit"]) - _dec(line["credit"]))
        for c in self.gl_cum.values():
            c.done()
        s = {a: Cum() for a in ACCOUNTS}
        for b in self.bank:
            s["1000"].add(b["posted_on"], _dec(b["amount"]))
            if b["counterparty"] != ev.PROCESSOR:
                s["2100"].add(b["posted_on"], _dec(b["amount"]))
        for v in list(self.card_inv.values()) + list(self.con_inv.values()):
            s["1100"].add(v["invoice_date"], v["total"])
            s["4000"].add(v["invoice_date"], -v["total"])
        for e in self.captures:
            s["1100"].add(e["event_on"], -_dec(e["amount_usd"]))
            s["1150"].add(e["event_on"], _dec(e["amount_usd"]))
        for p in self.t["contract_payments"]:
            s["1100"].add(p["paid_on"], -_dec(p["amount"]))
            s["2100"].add(p["paid_on"], -_dec(p["amount"]))
        for x in self.r["processor_settlement_items"]:
            usd = _dec(x["amount_usd"])
            if x["item_type"] == "charge":
                cap = self.capture_of.get(x["charge_id"])
                diff = usd - (_dec(cap["amount_usd"]) if cap else ZERO)
                s["1150"].add(x["available_on"], diff)
                s["7100"].add(x["available_on"], -diff)
            elif x["item_type"] == "fee":
                s["1150"].add(x["available_on"], usd)
                s["6100"].add(x["available_on"], -usd)
            elif x["item_type"] == "dispute_fee":
                opened = self.disputes.get(x["reference"])
                day = opened["event_on"] if opened else x["available_on"]
                s["1150"].add(day, usd)
                s["6120"].add(day, -usd)
        for e in self.r["processor_events"]:
            if e["event_type"] == "refund":
                proc = ev.to_usd(_dec(e["amount_presentment"]), e["currency"], e["event_on"])
                s["1150"].add(e["event_on"], -proc)
                s["7100"].add(e["event_on"], -(_dec(e["amount_usd"]) - proc))
            elif e["event_type"] == "dispute_opened":
                s["1150"].add(e["event_on"], -_dec(e["amount_usd"]))
                s["4910"].add(e["event_on"], _dec(e["amount_usd"]))
            elif e["event_type"] == "dispute_won":
                s["1150"].add(e["event_on"], _dec(e["amount_usd"]))
                s["4910"].add(e["event_on"], -_dec(e["amount_usd"]))
        for p in self.payouts.values():
            s["1150"].add(p["arrival_on"], -_dec(p["amount_usd"]))
        for rf in self.t["card_refunds"]:
            s["4900"].add(rf["refund_date"], _dec(rf["amount"]))
        self.sub = {a: c.done() for a, c in s.items()}

    # ---- the families
    def three_way_match(self, close: D) -> list[str]:
        m, w = close.replace(day=1), close + dt.timedelta(days=WINDOW_DAYS)
        out = set()
        for k, v in self.card_inv.items():
            if m <= v["invoice_date"] <= close:
                paid = sum((_dec(e["amount_usd"]) for e in self.caps_by_invoice.get(k, []) if e["event_on"] <= w), ZERO)
                if abs(paid - v["total"]) > MATCH_TOL:
                    out.add(k)
        for e in self.captures:
            if m <= e["event_on"] <= close:
                its = [x for x in self.charge_items.get(e["charge_id"], []) if x["available_on"] <= w]
                if (len(its) != 1 or abs(_dec(its[0]["amount_presentment"]) - _dec(e["amount_presentment"])) > MATCH_TOL
                        or e["invoice_id"] not in self.card_inv):
                    out.add(e["charge_id"])
        for cid, its in self.charge_items.items():
            if cid not in self.capture_of and any(m <= x["available_on"] <= close for x in its):
                out.add(cid)
        return sorted(out)

    def payout_reconciliation(self, close: D) -> list[str]:
        m, w = close.replace(day=1), close + dt.timedelta(days=WINDOW_DAYS)
        out = set()
        for pid, p in self.payouts.items():
            if not m <= p["created_on"] <= close:
                continue
            items = sum((_dec(x["amount_usd"]) for x in self.items_by_payout.get(pid, [])), ZERO)
            lines = [b for b in self.bank_by_ref.get(pid, []) if b["posted_on"] <= w]
            ok_line = (len(lines) == 1 and abs(_dec(lines[0]["amount"]) - _dec(p["amount_usd"])) <= MATCH_TOL
                       and BANK_DAYS[0] <= ev.business_days_between(p["created_on"], lines[0]["posted_on"]) <= BANK_DAYS[1])
            if abs(items - _dec(p["amount_usd"])) > MATCH_TOL or not ok_line:
                out.add(pid)
        for ref, lines in self.bank_by_ref.items():
            for b in lines:
                if m <= b["posted_on"] <= close and (ref not in self.payouts or len(lines) > 1):
                    out.add(b["line_id"])
        return sorted(out)

    def cash_application(self, close: D) -> list[str]:
        m = close.replace(day=1)
        out = []
        for b in self.bank:
            if b["counterparty"] == ev.PROCESSOR or not m <= b["posted_on"] <= close:
                continue
            target, amt = self.rule[b["line_id"]]
            booked = sorted((ln["invoice_id"] if ln["account"] == "1100" else ln["account"], _dec(ln["credit"]))
                            for ln in self.gl_by_source.get(("transfer", b["line_id"]), []) if _dec(ln["credit"]) > 0)
            if booked != [(target, amt)]:
                out.append(b["line_id"])
        return sorted(out)

    def month_end_cutoff(self, close: D) -> list[str]:
        lo = bisect.bisect_left(self.rule_day_list, close - dt.timedelta(days=CUTOFF_DAYS))
        hi = bisect.bisect_right(self.rule_day_list, close + dt.timedelta(days=CUTOFF_DAYS))
        out = []
        for day, key in self.rule_days[lo:hi]:
            for ln in self.gl_by_source.get(key, []):
                if (ln["posted_on"].year, ln["posted_on"].month) != (day.year, day.month):
                    out.append(f"{key[0]}:{key[1]}")
                    break
        return sorted(out)

    def ledger_tieout(self, close: D) -> list[str]:
        out = []
        for a in sorted(set(self.gl_cum) | set(self.sub)):
            gl = self.gl_cum[a].at(close) if a in self.gl_cum else ZERO
            sub = self.sub[a].at(close) if a in self.sub else ZERO
            if abs(gl - sub) > TIEOUT_TOL:
                out.append(a)
        return out

    def tieout_gaps(self, close: D) -> dict:
        """Ledger minus rebuilt balance per account at a close (reporting only)."""
        return {a: float((self.gl_cum[a].at(close) if a in self.gl_cum else ZERO) - (self.sub[a].at(close) if a in self.sub else ZERO))
                for a in sorted(set(self.gl_cum) | set(self.sub))}

    def flags(self, close: D) -> dict[str, list[str]]:
        return {f: getattr(self, f)(close) for f in FAMILIES}


def new_flags(flags: dict, clean_flags: dict) -> dict[str, list[str]]:
    """Flags not raised on the clean company at the same close, per family (families with none left out)."""
    out = {}
    for f in FAMILIES:
        fresh = sorted(set(flags.get(f, [])) - set(clean_flags.get(f, [])))
        if fresh:
            out[f] = fresh
    return out
