#!/usr/bin/env python3
# Source: q2-stats-probability.html
import numpy as np
from typing import Callable


def bootstrap(
    data: np.ndarray,
    stat: Callable[[np.ndarray], float],
    n_boot: int = 5000,
    alpha: float = 0.05,
    seed: int = 0,
) -> tuple[float, float, tuple[float, float]]:
    """Bootstrap the standard error and a percentile CI of any statistic.

    Args:
        data: 1-D array of iid observations.
        stat: Function that maps an array to a number, such as np.median.
        n_boot: Number of resamples.
        alpha: 1 - confidence level. 0.05 gives a 95% interval.
        seed: Random seed.

    Returns:
        (point estimate, standard error, (ci_low, ci_high)).
    """
    rng = np.random.default_rng(seed)
    n = len(data)
    # Each row is one resample: n indices drawn with replacement.
    idx = rng.integers(0, n, size=(n_boot, n))
    stats = np.array([stat(data[row]) for row in idx])
    se = stats.std(ddof=1)
    lo, hi = np.quantile(stats, [alpha / 2, 1 - alpha / 2])
    return stat(data), se, (lo, hi)


# Example: SE of the median of skewed revenue data.
rng = np.random.default_rng(1)
revenue = rng.lognormal(mean=3.0, sigma=1.2, size=2000)
est, se, ci = bootstrap(revenue, np.median)
print(f"median={est:.2f}  se={se:.2f}  95% CI=({ci[0]:.2f}, {ci[1]:.2f})")

# Sanity check: for the mean, the bootstrap SE should match s / sqrt(n).
_, se_mean, _ = bootstrap(revenue, np.mean)
print(se_mean, revenue.std(ddof=1) / np.sqrt(len(revenue)))
