"""The six new check families (DESIGN-independent.md section 3), run at a month-end close on the extracts and the
independent sources. Each returns the keys it flags; a family fires at a close when it flags at least one key.

The bands, the sample size, the sample's salt and the value threshold below are the declared ones; they are pinned by
hash with this file (DESIGN-independent.md section 10) and never change after a result is seen.
"""
from __future__ import annotations

import datetime as dt
import hashlib
import math
from decimal import Decimal

from warehouse import generate as g

D = dt.date
FAMILIES = ["price_reasonableness", "discount_provenance", "order_form_sample", "coupon_provenance",
            "metering_vs_telemetry", "link_loss"]
SEAT_BAND = (Decimal("0.80"), Decimal("1.25"))
STEP_BAND = (Decimal("0.90"), Decimal("1.35"))
METER_BAND = (Decimal("0.90"), Decimal("1.02"))
SAMPLE_SHARE = Decimal("0.10")
SAMPLE_SALT = "order-form-sample"
VALUE_THRESHOLD = Decimal("100000")
FORM_FIELDS = ("account_id", "service_start", "service_end", "term_months", "discount_pct", "billing_frequency",
               "onboarding_fee")


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


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


def _money(v) -> Decimal:
    return g.cents(_dec(v or 0))


def sample_rank(month: D, contract_id: str) -> str:
    return hashlib.sha256(f"{SAMPLE_SALT}|{month:%Y-%m}|{contract_id}".encode()).hexdigest()


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

    def __init__(self, tables: dict, sources: dict):
        t, s = tables, sources
        self.t, self.s = t, s
        self.contracts = sorted(t["crm_contracts"], key=lambda c: c["contract_id"])
        self.tiers = {k: sorted(v, key=lambda x: x["tier"]) for k, v in _by(t["crm_contract_tiers"], "contract_id").items()}
        self.opps = {o["opportunity_id"]: o for o in t["crm_opportunities"]}
        self.accounts = {a["account_id"]: a for a in t["crm_accounts"]}
        self.monthly = {(r["workspace_id"], r["month_end"]): r for r in t["product_workspace_monthly"]}
        self.by_account = _by(t["crm_contracts"], "account_id")
        self.forms = {f["contract_id"]: f for f in s["deal_desk_order_forms"]}
        self.form_tiers = {k: sorted(v, key=lambda x: x["tier"]) for k, v in _by(s["deal_desk_order_form_tiers"], "contract_id").items()}
        self.rate = {r["item_id"]: _dec(r["list_price"]) for r in s["pricing_rate_card"]}
        self.card_items = {r["item_id"] for r in s["pricing_rate_card"] if r["item_id"] != "CONTRACT-SEAT"}
        self.guide = self.rate["CONTRACT-SEAT"]
        self.approvals = _by(s["deal_desk_discount_approvals"], "opportunity_id")
        self.coupons = _by(s["promotion_registry"], "subscription_id")
        self.subs = sorted(t["card_subscriptions"], key=lambda x: x["subscription_id"])
        self.card_lines = _by([x for x in t["card_invoice_lines"] if x["line_type"] == "recurring"], "subscription_id")
        self.billed: dict = {}
        for x in t["card_invoice_lines"] + t["contract_invoice_lines"]:
            if x["line_type"] == "usage":
                k = (x["workspace_id"], x["period_start"])
                self.billed[k] = self.billed.get(k, 0) + int(x["quantity"])
        self.events: dict = {}
        for r in s["product_run_events_daily"]:
            k = (r["workspace_id"], D(r["event_date"].year, r["event_date"].month, 1))
            self.events[k] = self.events.get(k, 0) + int(r["run_events"])

    # ---- shared
    def in_service(self, close: D) -> list[dict]:
        return [c for c in self.contracts if c["service_start"] <= close <= c["service_end"]]

    def tier_value(self, c: dict, day: D) -> Decimal | None:
        hits = [x for x in self.tiers.get(c["contract_id"], []) if x["tier_start"] <= day <= x["tier_end"]]
        return _dec(hits[0]["annual_list_value"]) if len(hits) == 1 else None

    def net_value(self, c: dict, day: D) -> Decimal | None:
        v = self.tier_value(c, day)
        return None if v is None else v * (100 - _dec(c["discount_pct"])) / 100

    # ---- 1. price reasonableness
    def price_reasonableness(self, close: D) -> list[str]:
        out = set()
        listed = {p["price_id"]: _dec(p["unit_amount"]) for p in self.t["card_price_list"]}
        for pid in sorted(set(listed) | self.card_items):
            if listed.get(pid) is None or pid not in self.card_items or listed[pid] != self.rate[pid]:
                out.add(f"price_list:{pid}")
        for c in self.in_service(close):
            a = self.accounts.get(c["account_id"])
            w = a["workspace_id"] if a else None
            row = self.monthly.get((w, close)) if w else None
            net = self.net_value(c, close)
            if row is not None and row["plan_kind"] == "contract" and int(row["active_seats"]) > 0 and net is not None:
                r = net / int(row["active_seats"]) / self.guide
                if not SEAT_BAND[0] <= r <= SEAT_BAND[1]:
                    out.add(f"seat_price:{c['contract_id']}")
            ts = self.tiers.get(c["contract_id"], [])
            steps = [(ts[i - 1]["annual_list_value"], ts[i]["annual_list_value"]) for i in range(1, len(ts))]
            o = self.opps.get(c["opportunity_id"])
            if o is not None and o["opportunity_type"] == "renewal" and ts:
                prev = [p for p in self.by_account.get(c["account_id"], [])
                        if p["service_end"] == c["service_start"] - dt.timedelta(days=1) and self.tiers.get(p["contract_id"])]
                if len(prev) == 1:
                    steps.append((self.tiers[prev[0]["contract_id"]][-1]["annual_list_value"], ts[0]["annual_list_value"]))
            for before, after in steps:
                before, after = _dec(before), _dec(after)
                if before <= 0 or not STEP_BAND[0] <= after / before <= STEP_BAND[1]:
                    out.add(f"term_step:{c['contract_id']}")
        return sorted(out)

    # ---- 2. discount provenance
    def discount_provenance(self, close: D) -> list[str]:
        out = set()
        for c in self.in_service(close):
            caps = [int(a["approved_discount_pct"]) for a in self.approvals.get(c["opportunity_id"], [])]
            d = int(c["discount_pct"])
            if d > 0 and (not caps or d > max(caps)):
                out.add(c["contract_id"])
            if caps and d == 0:
                out.add(c["contract_id"])
        return sorted(out)

    # ---- 3. order-form sample
    def sample(self, close: D) -> list[str]:
        live = self.in_service(close)
        k = math.ceil(SAMPLE_SHARE * len(live))
        month = D(close.year, close.month, 1)
        picked = {c["contract_id"] for c in sorted(live, key=lambda c: sample_rank(month, c["contract_id"]))[:k]}
        picked |= {c["contract_id"] for c in live if (self.net_value(c, close) or 0) >= VALUE_THRESHOLD}
        return sorted(picked)

    def order_form_sample(self, close: D) -> list[str]:
        out = []
        crm = {c["contract_id"]: c for c in self.contracts}
        for cid in self.sample(close):
            c, f = crm[cid], self.forms.get(cid)
            if f is None:
                out.append(cid)
                continue
            same = all((_money(c[k]) == _money(f[k])) if k == "onboarding_fee" else (str(c[k]) == str(f[k])) for k in FORM_FIELDS)
            mine = [(x["tier"], x["tier_start"], x["tier_end"], _money(x["annual_list_value"])) for x in self.tiers.get(cid, [])]
            theirs = [(x["tier"], x["tier_start"], x["tier_end"], _money(x["annual_list_value"])) for x in self.form_tiers.get(cid, [])]
            if not same or mine != theirs:
                out.append(cid)
        return out

    # ---- 4. coupon provenance
    def coupon_provenance(self, close: D) -> list[str]:
        out = set()
        for s in self.subs:
            if not (s["started_on"] <= close and (s["ended_on"] is None or s["ended_on"] >= close)):
                continue
            sid, pct = s["subscription_id"], int(s["recurring_discount_pct"])
            coupons = self.coupons.get(sid, [])
            if pct > 0 and not any(int(c["percent_off"]) == pct for c in coupons):
                out.add(sid)
            for cp in coupons:
                off = int(cp["percent_off"])
                if pct != off:
                    out.add(sid)
                unit = self.rate.get(s["price_id"])
                for x in self.card_lines.get(sid, []):
                    if x["invoice_date"] <= close and (unit is None or _money(x["amount"]) != g.cents(int(x["quantity"]) * unit * (100 - off) / 100)):
                        out.add(sid)
        return sorted(out)

    # ---- 5. metering against telemetry
    def metering_vs_telemetry(self, close: D) -> list[str]:
        month = D(close.year, close.month, 1)
        out = []
        for w in sorted({k[0] for k in self.billed if k[1] == month} | {k[0] for k in self.events if k[1] == month}):
            billed, events = self.billed.get((w, month), 0), self.events.get((w, month), 0)
            if events == 0:
                if billed > 0:
                    out.append(w)
            elif not METER_BAND[0] <= Decimal(billed) / Decimal(events) <= METER_BAND[1]:
                out.append(w)
        return out

    # ---- 6. link loss, stateful
    def link_loss(self, previous: dict[str, str]) -> list[str]:
        return sorted(a for a, w in previous.items() if a not in self.accounts or self.accounts[a]["workspace_id"] != w)

    def flags(self, close: D, previous_links: dict[str, str]) -> dict[str, list[str]]:
        return {"price_reasonableness": self.price_reasonableness(close),
                "discount_provenance": self.discount_provenance(close),
                "order_form_sample": self.order_form_sample(close),
                "coupon_provenance": self.coupon_provenance(close),
                "metering_vs_telemetry": self.metering_vs_telemetry(close),
                "link_loss": self.link_loss(previous_links)}


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


def new_flags(flags: dict[str, list[str]], clean: dict[str, list[str]]) -> dict[str, list[str]]:
    """Flags at a close that the clean company does not raise at the same close."""
    return {f: sorted(set(flags[f]) - set(clean[f])) for f in FAMILIES if set(flags[f]) - set(clean[f])}
