"""Simulated label delay and the four label views (DESIGN.md, "Label delay" and "2. Arms").

Every function is pure: arrays in, arrays out, randomness only from the Generator passed in.
"""
import math

import numpy as np
from scipy.special import erf

SIGMA = 0.6                      # log-scale spread of the report delay (declared)
Z95 = 1.6448536269514722         # 95th percentile of the standard normal
WEIGHT_CAP = 10.0                # cap on 1 / G(age) for the weighted arm
SAMPLE_SHARE = 0.10              # share of non-fraud-labelled rows kept for training
ARMS = ("full", "naive", "drop_recent", "weighted")


def maturity_horizon(m):
    """95th percentile of a log-normal delay with median m hours."""
    return m * math.exp(Z95 * SIGMA)


def simulate_report_delay(y, m, q, rng):
    """Hours from transaction to fraud report; inf for legitimate rows and for frauds never reported.

    Draws one uniform and one normal per row whatever its class, so a seed gives the same draws for every q and m
    (common random numbers across the sweep): the never-reported set grows with q, the delays scale with m.
    """
    n = len(y)
    u = rng.random(n)
    z = rng.standard_normal(n)
    delay = np.exp(math.log(m) + SIGMA * z)
    reported = (y == 1) & (u >= q)
    return np.where(reported, delay, np.inf)


def arrival_cdf(age, m):
    """G(age): probability that a fraud that does get reported has been reported by the given age (hours)."""
    age = np.asarray(age, dtype=float)
    out = np.zeros_like(age)
    pos = age > 0
    out[pos] = 0.5 * (1.0 + erf((np.log(age[pos]) - math.log(m)) / (SIGMA * math.sqrt(2.0))))
    return out


def label_view(arm, hour, y, report_delay, t, m):
    """Rows usable at decision time t, their labels and their weights, for one arm.

    hour, y, report_delay cover the candidate training rows (all with hour < t). Returns (keep_mask, labels, weights)
    before the training sample is drawn.
    """
    arrived = (hour + report_delay) <= t
    if arm == "full":
        return np.ones(len(y), bool), y.astype(int), np.ones(len(y))
    labels = arrived.astype(int)
    if arm == "naive":
        return np.ones(len(y), bool), labels, np.ones(len(y))
    if arm == "drop_recent":
        keep = ((t - hour) >= maturity_horizon(m)) | arrived
        return keep, labels, np.ones(len(y))
    if arm == "weighted":
        g = arrival_cdf(t - hour, m)
        w = np.ones(len(y))
        pos = labels == 1
        w[pos] = np.minimum(1.0 / np.maximum(g[pos], 1e-12), WEIGHT_CAP)
        return np.ones(len(y), bool), labels, w
    raise ValueError(arm)


def training_sample(keep, labels, weights, sample_u):
    """Every kept row labelled fraud, plus kept rows whose sample draw is under SAMPLE_SHARE at weight 1 / SAMPLE_SHARE."""
    sampled = sample_u < SAMPLE_SHARE
    use = keep & ((labels == 1) | sampled)
    w = weights * np.where(labels == 1, 1.0, 1.0 / SAMPLE_SHARE)
    return use, w
