"""Colocalisation of two fine-mapped signals and the Wald ratio of a single-variant instrument."""

import math

import numpy as np
from scipy import stats

# coloc's defaults for comparing fine-mapped signals (coloc.bf_bf, coloc.susie).
P1, P2, P12 = 1e-4, 1e-4, 5e-6
# coloc.bf_bf compares two signals only when each puts at least this much posterior on shared variants.
OVERLAP_MIN = 0.5


def logsum(x: np.ndarray) -> float:
    m = float(np.max(x))
    return m + math.log(float(np.sum(np.exp(x - m))))


def logdiff(a: float, b: float) -> float:
    """log(exp(a) - exp(b)) for a >= b."""
    if b >= a:
        return -math.inf
    return a + math.log1p(-math.exp(b - a))


def coloc(a: dict, b: dict) -> dict:
    """Posterior probabilities of coloc's five hypotheses for two credible sets.

    Each set is {variantId: (logBF, posterior probability)} from SuSiE. As coloc.bf_bf does, the
    comparison runs over the variants both sets hold, and only when each set puts at least
    OVERLAP_MIN of its posterior there; otherwise it returns None (not testable, so not colocalised).
    """
    shared = sorted(set(a) & set(b))
    if not shared:
        return None
    ov_a = sum(a[v][1] for v in shared)
    ov_b = sum(b[v][1] for v in shared)
    if ov_a < OVERLAP_MIN or ov_b < OVERLAP_MIN:
        return None
    l1 = np.array([a[v][0] for v in shared])
    l2 = np.array([b[v][0] for v in shared])
    s1, s2, s12 = logsum(l1), logsum(l2), logsum(l1 + l2)
    lh = np.array([
        0.0,
        math.log(P1) + s1,
        math.log(P2) + s2,
        math.log(P1) + math.log(P2) + logdiff(s1 + s2, s12),
        math.log(P12) + s12,
    ])
    pp = np.exp(lh - logsum(lh))
    top = shared[int(np.argmax(l1 + l2))]
    return {"h3": float(pp[3]), "h4": float(pp[4]), "shared": len(shared), "top_shared": top,
            "overlap_a": ov_a, "overlap_b": ov_b}


def coloc_window(a: dict, labf: dict, log_sum_abf: float) -> dict:
    """Posterior probabilities for a fine-mapped exposure signal against an outcome's full statistics.

    `a` is the exposure's credible set, {variantId: (logBF, posterior probability)} from SuSiE, whose
    Bayes factors outside the set are taken as zero; `labf` holds the outcome's Wakefield log
    approximate Bayes factors at the set's variants, and `log_sum_abf` the log of their sum over every
    variant in the window around the set's lead. This is coloc.abf's sum over the window with the
    exposure's single-signal Bayes factors in place of its own. The comparison runs over the set's
    variants the outcome has, and only when they hold at least OVERLAP_MIN of its posterior;
    otherwise it returns None.
    """
    shared = sorted(v for v in a if v in labf)
    if not shared:
        return None
    cover = sum(a[v][1] for v in shared)
    if cover < OVERLAP_MIN:
        return None
    l1 = np.array([a[v][0] for v in shared])
    l2 = np.array([labf[v] for v in shared])
    s1, s12 = logsum(l1), logsum(l1 + l2)
    s2 = max(log_sum_abf, logsum(l2))
    lh = np.array([
        0.0,
        math.log(P1) + s1,
        math.log(P2) + s2,
        math.log(P1) + math.log(P2) + logdiff(s1 + s2, s12),
        math.log(P12) + s12,
    ])
    pp = np.exp(lh - logsum(lh))
    top = shared[int(np.argmax(l1 + l2))]
    return {"h3": float(pp[3]), "h4": float(pp[4]), "shared": len(shared), "top_shared": top, "coverage": cover}


def wald(beta_x: float, beta_y: float, se_y: float) -> dict:
    """Log odds ratio of the outcome per unit of the exposure, from one variant (first-order SE)."""
    est = beta_y / beta_x
    se = se_y / abs(beta_x)
    z = est / se
    return {"est": est, "se": se, "z": z, "log10p": log10p_from_z(z)}


def log10p_from_z(z: float) -> float:
    """log10 of the two-sided normal p-value, exact far into the tail."""
    return float((stats.norm.logsf(abs(z)) + math.log(2)) / math.log(10))


def power_same_sign(true_est: float, se: float, alpha: float = 0.05) -> float:
    """Chance that an estimate with this SE comes out with the true sign and two-sided p < alpha."""
    zc = stats.norm.isf(alpha / 2)
    return float(stats.norm.sf(zc - abs(true_est) / se))


def ivw(ests: list, ses: list) -> dict:
    """Fixed-effect inverse-variance weighted mean of Wald ratios, with Cochran's Q."""
    e, s = np.array(ests), np.array(ses)
    w = 1 / s**2
    est = float(np.sum(w * e) / np.sum(w))
    se = float(1 / math.sqrt(np.sum(w)))
    q = float(np.sum(w * (e - est) ** 2))
    df = len(e) - 1
    return {"est": est, "se": se, "log10p": log10p_from_z(est / se), "q": q, "df": df,
            "q_log10p": float(stats.chi2.logsf(q, df) / math.log(10)) if df > 0 else None}
