"""How often a link between discount depth and renewal could be seen (DESIGN-pricing.md section 5). Generator only, no dbt.

The study's generator with one change: the renewal decision draws its random number exactly as the generator does and
compares it with a probability set by the contract's discount depth (deep 0.85 + g/2, shallow 0.85 less g/2) instead of
0.85. At g = 0 this is the study's own generator; `check_reproduces` refuses to go on unless it reproduces the clean
company's decisions exactly.
"""
from __future__ import annotations

import datetime as dt
from decimal import Decimal

from pricing import truth as T
from warehouse import generate as g

GAPS = [0.0, 0.10, 0.20, 0.30]
SEEDS = list(range(60001, 60201))


class PlantedCompany(g.Company):
    """The generator's Company with renewal probability set by discount depth."""

    def __init__(self, seed: int, gap: float):
        super().__init__(seed)
        self.gap = gap

    def renew(self, c: dict):
        rng = self.rng
        c["done"] = True
        p = T.BASE_RENEW + self.gap / 2 if c["discount_pct"] >= T.DEEP else T.BASE_RENEW - self.gap / 2
        if rng.random() >= p:
            return
        acct = next(a for a in self.accounts if a["account_id"] == c["account_id"])
        ws = self.ws_index[c["workspace_id"]]
        last = c["tiers"][-1]["annual_list_value"]
        listv = Decimal(int(last * Decimal(str(round(rng.uniform(0.95, 1.25), 3))) / 100) * 100)
        signed = c["service_end"] - dt.timedelta(days=rng.randint(5, 30))
        self.new_contract(acct, ws, "renewal", signed, c["service_end"] + dt.timedelta(days=1), 12, [listv],
                          c["discount_pct"], c["billing_frequency"], Decimal(0))


def decisions(co: g.Company) -> list[dict]:
    rec = T.renewals(co)
    return [{"contract_id": k, **v} for k, v in sorted(rec.items())]


def check_reproduces() -> None:
    """At g = 0 and the study's seed, the planted generator must give the clean company's decisions exactly."""
    plain = decisions(g.Company(g.SEED).run())
    planted = decisions(PlantedCompany(g.SEED, 0.0).run())
    if plain != planted or not plain:
        raise SystemExit("the planted generator at gap 0 does not reproduce the study's renewal decisions")


def one(seed: int, gap: float) -> dict:
    co = PlantedCompany(seed, gap).run()
    return {"seed": seed, **T.renewal_gap(decisions(co))}


def summary(rows: list[dict], gap: float) -> dict:
    n = len(rows)
    groups = sorted(min(r["decisions_deep"], r["decisions_shallow"]) for r in rows)
    deep = sorted(r["decisions_deep"] for r in rows)
    shallow = sorted(r["decisions_shallow"] for r in rows)
    med = lambda xs: (xs[(len(xs) - 1) // 2] + xs[len(xs) // 2]) / 2  # noqa: E731
    return {"gap": gap, "companies": n, "seen": sum(r["seen"] for r in rows),
            "seen_share": sum(r["seen"] for r in rows) / n,
            "excludes_zero": sum(r["excludes_zero"] for r in rows),
            "excludes_zero_share": sum(r["excludes_zero"] for r in rows) / n,
            "median_decisions_deep": med(deep), "median_decisions_shallow": med(shallow),
            "no_decision_in_a_group": sum(1 for x in groups if x == 0),
            "decisions_per_group_for_80_power": T.size_needed(gap) if gap > 0 else None}
