"""The well-powered rule (plan section 6): whether a claim's outcome study could confirm it if it were true.

map_claims.py applies it to the claims and controls.py to their controls, before registration, from the proteins' own
statistics, gnomAD's allele frequencies, and the outcome studies' counts of cases and controls; analysis.py applies it
again with other effects for the claims that give none. It needs only pandas, so it runs in the container.
"""

import math
from pathlib import Path

import pandas as pd

# A claim is well powered if its outcome study's expected |z| at the lead of the protein's strongest cis set reaches
# WELL_POWERED_Z for a true effect of the claim's own odds ratio per SD, at most WELL_POWERED_CAP, or of WELL_POWERED_DEFAULT
# where the claim gives none per SD, about the median that claims of the same power give.
WELL_POWERED_CAP = 1.2
WELL_POWERED_DEFAULT = 1.1
WELL_POWERED_Z = 5


def z_per_log_or(z_x: float, n_x: float, cases: float, controls: float, af_nfe: float, af_out: float) -> float:
    """The outcome's expected |z| at a lead per unit of log odds ratio per SD of the protein: the lead's effect on the
    protein, |z_x| / sqrt(2 f (1 - f) n_x) SD per allele, with f its frequency in non-Finnish Europeans as the re-test's
    Wald ratio takes it, over the outcome's standard error, 2 / sqrt(2 g (1 - g) N_eff), with g its frequency in the
    outcome's population and N_eff = 4 / (1/cases + 1/controls). Zero where the re-test can't use the lead: f or g
    missing or not strictly between 0 and 1."""
    if not (0 < af_nfe < 1 and 0 < af_out < 1):
        return 0.0
    n_eff = 4 / (1 / cases + 1 / controls)
    return abs(z_x) * math.sqrt(n_eff * af_out * (1 - af_out) / (n_x * af_nfe * (1 - af_nfe))) / 2


def own_log_or(odds_ratio, unit) -> float:
    """A claim's own effect as |log odds ratio| per SD, where it gives one per SD (stated or inferred, as the re-test's
    power takes it); else NaN."""
    try:
        odds_ratio = float(odds_ratio)
    except (TypeError, ValueError):
        return math.nan
    return abs(math.log(odds_ratio)) if str(unit).lower() == "per standard deviation" and odds_ratio > 0 else math.nan


def rule_log_or(odds_ratio, unit, cap: float = WELL_POWERED_CAP, default: float = WELL_POWERED_DEFAULT) -> float:
    """The effect the rule tests a claim at, as a log odds ratio per SD: the claim's own, at most the cap's; else the
    default's."""
    own = own_log_or(odds_ratio, unit)
    return math.log(default) if math.isnan(own) else min(own, math.log(cap))


def strongest_leads(proteins: Path) -> pd.DataFrame:
    """Each assay's strongest cis set, by its lead's |z| for the protein, as the re-test's instrument falls back to:
    the lead's z, the assay's sample size, and the lead's frequency in non-Finnish Europeans and in Finns."""
    leads = (pd.read_parquet(proteins / "pqtl_sets.parquet", columns=["studyLocusId", "studyId"])
             .merge(pd.read_parquet(proteins / "pqtl_marginal.parquet", columns=["studyLocusId", "lead_z", "n", "lead_af_nfe"]), on="studyLocusId")
             .merge(pd.read_parquet(proteins / "pqtl_lead_af.parquet"), on="studyLocusId", how="left"))
    leads = leads.assign(z=leads.lead_z.abs()).sort_values(["z", "studyLocusId"])
    return leads.groupby("studyId").tail(1).set_index("studyId")


def lead_power(lead, source: str, cases: float, controls: float) -> float:
    """The outcome's expected |z| per unit of log odds ratio at a set's lead, the outcome's population being FinnGen's
    Finns or Pan-UKBB's non-Finnish Europeans."""
    out = lead.lead_af_fin if source == "finngen" else lead.lead_af_nfe
    return z_per_log_or(lead.z, lead.n, cases, controls, lead.lead_af_nfe, out)
