"""Small statistics helpers used in data science interview answers.

Standard library only (Python 3.8+). Each function mirrors a question in the README.
"""
from __future__ import annotations

import math
import random
from statistics import NormalDist, fmean

_Z = NormalDist()


def two_proportion_ztest(conv_a: int, n_a: int, conv_b: int, n_b: int) -> tuple[float, float]:
    """Two-sided z-test for a difference in conversion rates (pooled standard error).

    Returns (z, p_value). Positive z means B converted better than A.
    """
    if min(n_a, n_b) <= 0:
        raise ValueError("sample sizes must be positive")
    p_a, p_b = conv_a / n_a, conv_b / n_b
    pooled = (conv_a + conv_b) / (n_a + n_b)
    se = math.sqrt(pooled * (1 - pooled) * (1 / n_a + 1 / n_b))
    if se == 0:
        return 0.0, 1.0
    z = (p_b - p_a) / se
    p_value = 2 * (1 - _Z.cdf(abs(z)))
    return z, p_value


def sample_size_per_group(baseline: float, mde_abs: float, alpha: float = 0.05, power: float = 0.8) -> int:
    """Users needed in EACH arm to detect an absolute lift `mde_abs` on a conversion rate.

    Uses the common normal-approximation formula with unpooled variances.
    Example: baseline 10%, detect +1 percentage point -> about 14,750 per group.
    """
    if not 0 < baseline < 1 or mde_abs <= 0 or baseline + mde_abs >= 1:
        raise ValueError("need 0 < baseline < baseline + mde < 1")
    z_alpha = _Z.inv_cdf(1 - alpha / 2)
    z_beta = _Z.inv_cdf(power)
    p1, p2 = baseline, baseline + mde_abs
    variance = p1 * (1 - p1) + p2 * (1 - p2)
    return math.ceil((z_alpha + z_beta) ** 2 * variance / mde_abs ** 2)


def srm_chi_square(n_a: int, n_b: int, expected_ratio: float = 0.5) -> float:
    """Sample ratio mismatch check. Returns the p-value of a 1-df chi-square test.

    A tiny p-value (people often use < 0.001) means the split itself is broken,
    so the experiment's results should not be trusted until the cause is found.
    """
    total = n_a + n_b
    exp_a, exp_b = total * expected_ratio, total * (1 - expected_ratio)
    chi2 = (n_a - exp_a) ** 2 / exp_a + (n_b - exp_b) ** 2 / exp_b
    # chi-square with 1 df is the square of a standard normal
    return 2 * (1 - _Z.cdf(math.sqrt(chi2)))


def bootstrap_ci(values: list[float], stat=fmean, n_resamples: int = 2000, level: float = 0.95, seed: int = 0) -> tuple[float, float]:
    """Percentile bootstrap confidence interval for any statistic (mean by default)."""
    if not values:
        raise ValueError("values must not be empty")
    rng = random.Random(seed)
    n = len(values)
    stats = sorted(stat([values[rng.randrange(n)] for _ in range(n)]) for _ in range(n_resamples))
    lo_idx = int(((1 - level) / 2) * n_resamples)
    hi_idx = int((1 - (1 - level) / 2) * n_resamples) - 1
    return stats[lo_idx], stats[hi_idx]


def bayes_posterior(prior: float, sensitivity: float, false_positive_rate: float) -> float:
    """P(condition | positive test). The classic 'rare disease' interview question."""
    p_pos = sensitivity * prior + false_positive_rate * (1 - prior)
    return sensitivity * prior / p_pos


def reservoir_sample(stream, k: int, seed: int = 0) -> list:
    """Uniformly sample k items from a stream of unknown length (Algorithm R)."""
    rng = random.Random(seed)
    reservoir: list = []
    for i, item in enumerate(stream):
        if i < k:
            reservoir.append(item)
        else:
            j = rng.randint(0, i)
            if j < k:
                reservoir[j] = item
    return reservoir
