"""Post-hoc power analysis for observed effect sizes."""

from __future__ import annotations

import numpy as np
from scipy import stats


def posthoc_power(
    n_pairs: int,
    effect_size_d: float,
    alpha: float = 0.05,
) -> float:
    """Approximate power for paired Wilcoxon test.

    Uses normal approximation: power ~ Phi(|d| * sqrt(n) - z_{alpha/2})
    """
    z_alpha = stats.norm.ppf(1 - alpha / 2)
    z_power = abs(effect_size_d) * np.sqrt(n_pairs) - z_alpha
    return float(stats.norm.cdf(z_power))


def required_sample_size(
    target_delta: float = 0.5,
    target_power: float = 0.80,
    alpha: float = 0.05,
) -> int:
    """How many text pairs needed to detect *target_delta* with *target_power*?"""
    z_alpha = stats.norm.ppf(1 - alpha / 2)
    z_beta = stats.norm.ppf(target_power)
    n = ((z_alpha + z_beta) / target_delta) ** 2
    return int(np.ceil(n))
