"""Multiple-testing correction."""

from __future__ import annotations

import numpy as np


def adjust_pvalues(pvalues: list[float], method: str = "bh") -> np.ndarray:
    p = np.asarray(pvalues, dtype=float)
    if np.any((p < 0) | (p > 1)):
        raise ValueError("p-values must be within [0, 1]")

    n = len(p)
    if n == 0:
        return np.array([])

    method_norm = method.lower()
    order = np.argsort(p)
    ranked = p[order]

    if method_norm in {"bh", "fdr_bh"}:
        factors = n / (np.arange(1, n + 1))
        q_ranked = np.minimum.accumulate((ranked * factors)[::-1])[::-1]
    elif method_norm in {"by", "fdr_by"}:
        c_m = np.sum(1.0 / np.arange(1, n + 1))
        factors = n * c_m / (np.arange(1, n + 1))
        q_ranked = np.minimum.accumulate((ranked * factors)[::-1])[::-1]
    elif method_norm == "bonferroni":
        q_ranked = np.minimum(1.0, ranked * n)
    else:
        raise ValueError("Unknown adjustment method. Use 'bh', 'by', or 'bonferroni'.")

    q = np.empty_like(q_ranked)
    q[order] = np.clip(q_ranked, 0.0, 1.0)
    return q
