"""Lawlor 2016 triangulation 5-criterion + design diversity bonus.

Lawlor DA, Tilling K, Davey Smith G. Triangulation in aetiological epidemiology.
Int J Epidemiol. 2016;45(6):1866-1886.

5 기준:
1. different sources of bias (different designs have different biases)
2. expected direction of bias known
3. similar effect size across designs (point estimate convergence)
4. dose-response across designs
5. magnitude of effect supports causal interpretation
"""
from __future__ import annotations

from typing import Dict, List, Optional

from .grid import concordance_score, get_pair_rows, DESIGN_WEIGHT


def lawlor_score(intervention: str, outcome: str) -> Dict:
    """5-criterion + diversity 보너스 (0~10 점수)."""
    rows = get_pair_rows(intervention, outcome)
    if not rows:
        return {"intervention": intervention, "outcome": outcome,
                "total": 0, "criteria": {}, "note": "no data"}

    conc = concordance_score(rows)

    # 1. different sources of bias = design diversity
    c1 = min(2.0, conc["n_designs"] / 3.0)

    # 2. expected direction of bias known = always documented in our taxonomy
    c2 = 1.5

    # 3. similar effect size = CI overlap
    c3 = 2.0 * (conc["ci_overlap_frac"] or conc["direction_agreement"])

    # 4. dose-response: 약물 + bariatric은 weight loss 크기와 효과 관계 검토 가능
    # bariatric_natural (largest weight loss) + RCT (moderate) + lifestyle (small) 모두 있으면 보너스
    designs = set(r["design"] for r in rows)
    has_bariatric = "bariatric_natural" in designs
    has_rct = "RCT" in designs
    c4 = 1.5 if (has_bariatric and has_rct) else (0.7 if has_rct else 0.3)

    # 5. magnitude supports causal: weighted average |log(effect)| > some threshold
    from .grid import _to_float
    log_effs = []
    for r in rows:
        e = _to_float(r.get("effect_estimate"))
        if e is not None and e > 0:
            import math
            log_effs.append(abs(math.log(e)))
    avg_log = sum(log_effs) / len(log_effs) if log_effs else 0.0
    c5 = min(2.0, avg_log * 4.0)

    # diversity bonus: 6-design 모두 채우면 +1
    diversity_bonus = 1.0 * conc["design_diversity"]

    total = c1 + c2 + c3 + c4 + c5 + diversity_bonus
    return {
        "intervention": intervention,
        "outcome": outcome,
        "total": round(total, 2),
        "max": 10.0,
        "criteria": {
            "1_design_diversity": round(c1, 2),
            "2_bias_direction_known": round(c2, 2),
            "3_effect_size_convergence": round(c3, 2),
            "4_dose_response_coverage": round(c4, 2),
            "5_magnitude_supports_causal": round(c5, 2),
            "diversity_bonus": round(diversity_bonus, 2),
        },
        "concordance": conc,
    }


if __name__ == "__main__":
    for iv, oc in [("semaglutide", "CV death"),
                   ("bariatric_RYGB", "all_cause_mortality"),
                   ("intermittent_fasting", "CV death")]:
        s = lawlor_score(iv, oc)
        print(f"{iv} × {oc}: {s['total']}/{s['max']} | {s['criteria']}")
