"""EASL-CLIF ACLF grade classification.

Reference (built-in, offline):
- Moreau et al., Gastroenterology 2013 (CANONIC)
- Jalan et al., J Hepatol 2014 (CLIF-C ACLF)

Grading rule (simplified):
- ACLF-1: single kidney failure OR single non-renal organ failure + (creatinine 1.5-1.9 OR brain grade I-II)
- ACLF-2: 2 organ failures
- ACLF-3: >=3 organ failures
- "Organ failure" thresholds per CLIF-SOFA: liver>=3, kidney>=3 (creat>=3.5), coag>=3,
   brain>=3 (HE grade III-IV), circ>=3 (vasopressor), resp>=3.

For research / QI use only.
"""
from __future__ import annotations
from typing import Dict


ORGANS = ["liver", "kidney", "coag", "brain", "circ", "resp"]


def organ_failures(subscores: Dict[str, int]) -> Dict[str, bool]:
    return {o: subscores.get(o, 0) >= 3 for o in ORGANS}


def aclf_grade(subscores: Dict[str, int], creatinine: float, he_grade: int) -> Dict[str, object]:
    """Return ACLF grade and supporting flags."""
    fails = organ_failures(subscores)
    n_fail = sum(fails.values())

    grade = "no ACLF"
    if n_fail >= 3:
        grade = "ACLF-3"
    elif n_fail == 2:
        grade = "ACLF-2"
    elif n_fail == 1:
        # ACLF-1: single kidney failure OR
        # single non-renal failure + (1.5<=creat<1.9 OR brain grade I-II)
        if fails["kidney"]:
            grade = "ACLF-1"
        else:
            if (1.5 <= creatinine < 2.0) or he_grade in (1, 2):
                grade = "ACLF-1"
            else:
                grade = "no ACLF"
    else:
        grade = "no ACLF"

    return {
        "grade": grade,
        "n_failures": n_fail,
        "failures": fails,
    }


def expected_28d_mortality(grade: str) -> float:
    """CANONIC-derived approximate 28-day mortality (research reference)."""
    return {
        "no ACLF": 0.05,
        "ACLF-1": 0.22,
        "ACLF-2": 0.32,
        "ACLF-3": 0.77,
    }.get(grade, 0.05)
