"""The bunching estimator: a Poisson log-link fit with round-number multipliers and excluded windows.

Pure numpy. Takes bin counts, returns the counterfactual and the measures at a figure. See DESIGN-r1.md.
"""
import numpy as np

BIN = 500
LO, HI = 12500, 160000
ALWAYS = (25000, 40000, 100000)
WINDOW = 2500
EDGES = np.arange(LO + BIN, HI + BIN, BIN)  # right edge of each bin; a bin is (edge - 500, edge]
N_BINS = len(EDGES)
CLASSES = ("k1", "k5", "k10", "k25", "k50")
PLACEBOS = tuple(r for r in range(15000, 155001, 5000) if r not in ALWAYS)


def bin_index(value):
    """Index of the right-closed bin holding value, or -1 outside (LO, HI]."""
    if value <= LO or value > HI:
        return -1
    q = int(np.ceil((value - LO) / BIN)) - 1
    return q


def round_class(edge):
    """The largest round class of a bin's right edge, or None."""
    if edge % 50000 == 0:
        return "k50"
    if edge % 25000 == 0:
        return "k25"
    if edge % 10000 == 0:
        return "k10"
    if edge % 5000 == 0:
        return "k5"
    if edge % 1000 == 0:
        return "k1"
    return None


def window_bins(figure, below=True):
    """Indices of (figure - WINDOW, figure] or of (figure, figure + WINDOW]."""
    if below:
        return [i for i, e in enumerate(EDGES) if figure - WINDOW < e <= figure]
    return [i for i, e in enumerate(EDGES) if figure < e <= figure + WINDOW]


def excluded(figures):
    out = set()
    for f in figures:
        out.update(window_bins(f, True))
        out.update(window_bins(f, False))
    return sorted(out)


def design(figures, degree):
    """The smooth columns, the class columns and one free column per excluded bin."""
    mid = np.log(EDGES - BIN / 2.0)
    z = (mid - mid.mean()) / mid.std()
    smooth = np.vander(z, degree + 1, increasing=True)
    cls = np.zeros((N_BINS, len(CLASSES)))
    for i, e in enumerate(EDGES):
        c = round_class(int(e))
        if c:
            cls[i, CLASSES.index(c)] = 1.0
    ex = excluded(figures)
    free = np.zeros((N_BINS, len(ex)))
    for j, i in enumerate(ex):
        free[i, j] = 1.0
    return smooth, cls, free


def fit(counts, figures=ALWAYS, degree=7, iters=60, tol=1e-9):
    """Fit by iteratively reweighted least squares. Returns the counterfactual and the round multipliers.

    A round class whose members are all excluded, or that has no contracts, gets a multiplier of 1 by the ridge term.
    The counterfactual keeps the smooth part and the round multipliers and drops the free columns.
    """
    y = np.asarray(counts, dtype=float)
    smooth, cls, free = design(figures, degree)
    keep_cls = [j for j in range(cls.shape[1]) if (cls[:, j] * (free.sum(axis=1) == 0)).sum() > 0]
    x_cf = np.hstack([smooth, cls[:, keep_cls]])
    x = np.hstack([x_cf, free])
    ridge = 1e-6 * np.eye(x.shape[1])
    beta = np.linalg.lstsq(x, np.log(y + 0.5), rcond=None)[0]
    last = None
    for _ in range(iters):
        eta = np.clip(x @ beta, -30, 30)
        mu = np.exp(eta)
        w = mu
        zz = eta + (y - mu) / mu
        a = (x * w[:, None]).T @ x + ridge
        b = (x * w[:, None]).T @ zz
        beta = np.linalg.solve(a, b)
        dev = float(np.sum(mu - y * eta))
        if last is not None and abs(dev - last) < tol * (abs(last) + 1):
            break
        last = dev
    cf = np.exp(np.clip(x_cf @ beta[: x_cf.shape[1]], -30, 30))
    mult = {c: 1.0 for c in CLASSES}
    for pos, j in enumerate(keep_cls):
        mult[CLASSES[j]] = float(np.exp(beta[smooth.shape[1] + pos]))
    return cf, mult


def measures(counts, figure, degree=7, extra=()):
    """E, H and B at a figure, with that figure's window excluded alongside the always-excluded ones."""
    y = np.asarray(counts, dtype=float)
    figs = tuple(sorted(set(ALWAYS) | {figure} | set(extra)))
    cf, mult = fit(y, figs, degree)
    below, above = window_bins(figure, True), window_bins(figure, False)
    obs_b, cf_b = float(y[below].sum()), float(cf[below].sum())
    obs_a, cf_a = float(y[above].sum()), float(cf[above].sum())
    return {"figure": figure, "observed_below": obs_b, "counterfactual_below": cf_b, "E": obs_b / cf_b if cf_b > 0 else None,
            "observed_above": obs_a, "counterfactual_above": cf_a, "H": obs_a / cf_a if cf_a > 0 else None,
            "B": obs_b - cf_b, "multipliers": mult}


def label_limit(e_value, ci, same_class_placebos, all_placebos):
    """The declared labelling rule."""
    if ci[0] <= 1 <= ci[1] or e_value is None:
        return "not separable from round-number pricing"
    if same_class_placebos and e_value <= max(same_class_placebos):
        return "not separable from round-number pricing"
    if e_value <= float(np.percentile(all_placebos, 90)):
        return "not separable from round-number pricing"
    return "beyond round-number pricing"


def label_natural(d40_ci, d25_ci):
    a, b = d40_ci[0] > 0, d25_ci[1] < 0
    return "the pattern moved with the rule" if a and b else "partly" if a or b else "no movement shown"
