Cookbook 378: Offline Clinical Allergy, Immunology & Resuscitation Acute Anaphylaxis WAO / EAACI / AAAAI Diagnostic Staging, Brighton Collaboration Level Engine, Weight-Tiered Epinephrine Autoinjector Titrator & Refractory Shock Vasopressor Infusion Protocol

Executive Clinical Overview

Acute Anaphylaxis is a severe, life-threatening, generalized or systemic hypersensitivity reaction characterized by rapid onset of airway, breathing, or circulatory compromise, usually associated with typical skin changes (urticaria, angioedema, flushing). Globally, anaphylaxis affects up to $1.5\% - 3.0\%$ of individuals during their lifetime, with triggers spanning food allergens (peanut, tree nuts, shellfish, milk, eggs), venom stings (Hymenoptera), medications (beta-lactams, neuromuscular blocking agents, NSAIDs, platinum chemotherapies, monoclonal antibodies), and radiocontrast agents.

Despite international clinical consensus guidelines from the World Allergy Organization (WAO), the European Academy of Allergy and Clinical Immunology (EAACI), and the American Academy of Allergy, Asthma & Immunology (AAAAI), severe morbidity and fatal outcomes in anaphylaxis are overwhelmingly driven by preventable clinician errors:

  1. Delayed Epinephrine Administration: Delaying intramuscular (IM) epinephrine while administering second-line antihistamines ($H_1$/$H_2$ blockers) or systemic corticosteroids is the primary risk factor for fatal hypoxic-ischemic encephalopathy and refractory cardiovascular collapse.
  2. Incorrect Route and Injection Site: Administering subcutaneous or deltoid injections instead of direct anterolateral thigh (vastus lateralis) intramuscular delivery, which produces 4- to 5-fold higher and faster peak plasma epinephrine concentrations ($C_{\max}$ in 8 minutes vs. 34 minutes).
  3. Failure to Recognize Beta-Blocker Unresponsiveness: In patients receiving chronic beta-adrenergic antagonist therapy, endogenous and exogenous catecholamines fail to stimulate cardiac $\beta_1$ and $\beta_2$ receptors, requiring immediate alternative second messenger pathway stimulation via intravenous Glucagon (bypassing $\beta$-receptors to directly activate intracellular adenylate cyclase).
  4. Premature Discharge & Biphasic Shock: Biphasic anaphylactic recurrence occurs in up to $5\% - 20\%$ of cases without re-exposure, typically emerging $1 - 72$ hours (median $4 - 12$ hours) after resolution of the index reaction.
+---------------------------------------------------------------------------------------------------------+
|                        ACUTE ANAPHYLAXIS DIAGNOSTIC & RESUSCITATION CASCADE                             |
+---------------------------------------------------------------------------------------------------------+
| 1. RAPID DIAGNOSTIC GATING (WAO / EAACI 2020 CRITERIA)                                                  |
|    - CRITERION 1: Acute onset (min to hrs) with Skin/Mucosal involvement (hives, pruritus, angioedema) |
|      PLUS at least ONE of:                                                                              |
|        (a) Respiratory Compromise (stridor, wheezing, dyspnea, PEF drop, hypoxemia)                     |
|        (b) Circulatory Collapse (hypotension, syncope, incontinence, diaphoresis)                       |
|        (c) Severe Gastrointestinal Symptoms (crampy abdominal pain, vomiting) [WAO 2020 inclusion]     |
|    - CRITERION 2: Acute onset of Hypotension, Bronchospasm, or Laryngeal Obstruction AFTER exposure to  |
|      a KNOWN or HIGHLY PROBABLE allergen for that patient, EVEN WITHOUT cutaneous involvement.          |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 2. IMMEDIATE FIRST-LINE INTERVENTION: INTRAMUSCULAR EPINEPHRINE (1:1000 / 1 mg/mL)                     |
|    - Injected exclusively in ANTEROLATERAL MID-THIGH (Vastus Lateralis).                                |
|    - Weight-Tiered Dosing (0.01 mg/kg; max single dose 0.5 mg):                                         |
|      * Weight < 7.5 kg     : 0.01 mg/kg exact syringe titration                                         |
|      * Weight 7.5 - 15 kg  : 0.1 mg or 0.15 mg Autoinjector (Junior)                                   |
|      * Weight 15 - 30 kg   : 0.15 mg Autoinjector (EpiPen Jr / Auvi-Q 0.15 mg)                           |
|      * Weight >= 30 kg     : 0.3 mg Autoinjector (EpiPen / Auvi-Q 0.3 mg)                               |
|      * Weight >= 50 kg     : 0.5 mg Autoinjector or 0.5 mg IM manual dose for severe adult collapse     |
|    - REPEAT INTERVAL: Every 5 to 15 minutes if symptoms persist or progress.                            |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 3. SECOND-LINE RESUSCITATION & REFRACTORY VASOPRESSOR ESCALATION                                        |
|    - Aggressive IV Isotonic Crystalloid: 20 mL/kg boluses (1-2 L rapid in adults) for vasodilation.      |
|    - Beta-Blocker Refractory Shock: Glucagon 1 - 5 mg IV over 5 min, then 2 - 10 mg/hr infusion.        |
|    - Refractory Anaphylaxis (>= 2 IM doses failed): Continuous IV Epinephrine Infusion                   |
|      (0.05 - 0.5 mcg/kg/min or 2 - 10 mcg/min) via dedicated line with ICU telemetry.                   |
|    - Secondary Adjuncts (ONLY AFTER EPINEPHRINE):                                                       |
|      * Inhaled Beta-2 Agonist (Albuterol 2.5-5 mg) for bronchospasm                                     |
|      * H1/H2 Antagonists (Cetirizine 10mg / Famotidine 20mg IV) for cutaneous pruritus                  |
|      * Corticosteroids (Methylprednisolone 1-2 mg/kg) - no acute impact on shock, theoretical biphasic  |
|    - Monitoring: Minimum 6-8 hours for mild-moderate; 12-24 hours for severe/refractory (biphasic risk).|
+---------------------------------------------------------------------------------------------------------+

Brighton Collaboration Diagnostic Certainty & WAO Severity Classification

To standardize clinical trial surveillance and adverse event reporting (such as vaccine-associated anaphylaxis), the Brighton Collaboration stratifies cases into 3 levels of diagnostic certainty based on multi-system organ involvement:

Brighton Level Diagnostic Certainty Clinical Criteria Requirement
Level 1 Highest Diagnostic Certainty $\ge 1$ Major Dermatological sign AND $\ge 1$ Major Cardiovascular AND/OR $\ge 1$ Major Respiratory sign.
Level 2 Intermediate Diagnostic Certainty $\ge 1$ Major Cardiovascular sign AND $\ge 1$ Major Respiratory sign; OR $\ge 1$ Major Cutaneous sign PLUS $\ge 1$ Minor Cardiovascular/Respiratory sign AND $\ge 1$ Other System (GI/Neuro).
Level 3 Lower Diagnostic Certainty $\ge 1$ Major Cardiovascular OR $\ge 1$ Major Respiratory sign PLUS additional minor multi-system criteria.
Non-Case Insufficient Evidence Fails to meet multi-system or isolated known allergen exposure thresholds.

Major vs. Minor Clinical Manifestations


WAO Clinical Severity Grading Scale

The World Allergy Organization categorizes anaphylaxis into 5 clinical grades:

\[\text{Severity Grade} = \begin{cases} \text{Grade 1 (Mild)}, & \text{Cutaneous/mucosal symptoms only (pruritus, flushing, urticaria, mild angioedema)} \\ \text{Grade 2 (Moderate)}, & \text{Mild respiratory (rhinitis, cough) or GI symptoms (mild cramps, nausea)} \\ \text{Grade 3 (Severe)}, & \text{Bronchospasm, wheeze, stridor, recurrent vomiting, crampy abdominal pain} \\ \text{Grade 4 (Life-Threatening)}, & \text{Hypotension, circulatory collapse, respiratory arrest, hypoxemia, syncope} \\ \text{Grade 5 (Fatal)}, & \text{Cardiorespiratory arrest} \end{cases}\]

Serum Mast Cell Tryptase Kinetics

Total serum tryptase serves as the laboratory gold standard for confirming mast cell degranulation in systemic anaphylaxis:


Production Python Implementation

The following complete, dependency-free Python engine implements the WAO 2020 criteria, Brighton Collaboration certainty stratification, weight-tiered epinephrine autoinjector titrator, beta-blocker glucagon rescue protocol, and IV vasopressor escalation cascade.

#!/usr/bin/env python3
"""
OpenPHR Cookbook 378: Offline Clinical Allergy & Emergency Resuscitation Engine
WAO/EAACI 2020 Anaphylaxis Diagnostic Criteria, Brighton Collaboration Certainty,
Weight-Tiered Epinephrine Autoinjector Titrator & Refractory Shock Vasopressor Engine.

Dependencies: Python 3.8+ (Standard Library Only).
"""

import math
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Tuple, Union


class BrightonCertaintyLevel(Enum):
    LEVEL_1 = "Level 1 (Highest Diagnostic Certainty: Multi-system Major Organ Involvement)"
    LEVEL_2 = "Level 2 (Intermediate Diagnostic Certainty)"
    LEVEL_3 = "Level 3 (Lower Diagnostic Certainty / Probable Anaphylaxis)"
    INSUFFICIENT = "Insufficient Evidence for Anaphylaxis Case Definition"


class WAOSeverityGrade(Enum):
    GRADE_1_MILD = "Grade 1 (Mild: Cutaneous and Subcutaneous Only)"
    GRADE_2_MODERATE = "Grade 2 (Moderate: Mild Respiratory, GI, or Cardiovascular)"
    GRADE_3_SEVERE = "Grade 3 (Severe: Bronchospasm, Stridor, Severe GI)"
    GRADE_4_LIFE_THREATENING = "Grade 4 (Life-Threatening: Hypotension, Shock, Hypoxemia, Syncope)"
    GRADE_5_FATAL = "Grade 5 (Fatal: Cardiopulmonary Arrest)"


class EpinephrineDeliveryDevice(Enum):
    MANUAL_SYRINGE = "Manual 1:1000 (1 mg/mL) Ampule with 1 mL Tuberculin Syringe (IM)"
    AUTOINJECTOR_INFANT_01 = "0.10 mg Epinephrine Autoinjector (Auvi-Q 0.1 mg)"
    AUTOINJECTOR_JUNIOR_015 = "0.15 mg Epinephrine Autoinjector (EpiPen Jr / Auvi-Q 0.15 mg)"
    AUTOINJECTOR_ADULT_03 = "0.30 mg Epinephrine Autoinjector (EpiPen / Auvi-Q 0.3 mg)"
    AUTOINJECTOR_ADULT_05 = "0.50 mg Epinephrine Autoinjector (Emerade 0.5 mg / High-Dose Adult IM)"


@dataclass
class AnaphylaxisPatientPresentation:
    age_years: float
    weight_kg: float
    is_adult: bool
    # Vital signs
    heart_rate_bpm: int
    systolic_bp_mmhg: int
    diastolic_bp_mmhg: int
    spo2_percent: float
    respiratory_rate_bpm: int
    # Allergen exposure history
    known_allergen_exposure: bool
    probable_allergen_exposure: bool
    trigger_type: str  # "Food", "Venom", "Medication", "Contrast", "Idiopathic", "Unknown"
    minutes_since_exposure: int
    # Cutaneous / Mucosal signs
    generalized_urticaria: bool
    generalized_erythema_flushing: bool
    angioedema_lips_tongue_uvula_face: bool
    generalized_pruritus: bool
    # Respiratory signs
    audible_stridor_laryngeal_edema: bool
    wheezing_bronchospasm: bool
    severe_dyspnea_hypoxemia: bool
    rhinorrhea_sneezing_cough: bool
    pef_percent_baseline: Optional[float] = None
    # Cardiovascular signs
    measured_hypotension: bool = False
    shock_capillary_refill_delayed: bool = False
    syncope_loss_of_consciousness: bool = False
    incontinence: bool = False
    # Gastrointestinal signs
    severe_crampy_abdominal_pain: bool = False
    recurrent_vomiting: bool = False
    diarrhea: bool = False
    # Medication and Medical History
    on_chronic_beta_blocker: bool = False
    on_ace_inhibitor: bool = False
    history_of_asthma: bool = False
    history_of_prior_anaphylaxis: bool = False
    history_of_biphasic_reaction: bool = False
    # Diagnostic tests
    acute_serum_tryptase_ug_l: Optional[float] = None
    baseline_serum_tryptase_ug_l: Optional[float] = None


@dataclass
class EpinephrineDosingRecommendation:
    recommended_dose_mg: float
    delivery_device: EpinephrineDeliveryDevice
    route: str
    anatomical_site: str
    needle_gauge_and_length: str
    repeat_frequency_minutes: str
    max_single_dose_mg: float
    clinical_instructions: str


@dataclass
class AnaphylaxisClinicalDecisionReport:
    meets_wao_criteria: bool
    wao_diagnostic_rationale: str
    brighton_level: BrightonCertaintyLevel
    wao_severity_grade: WAOSeverityGrade
    epinephrine_recommendation: EpinephrineDosingRecommendation
    beta_blocker_resistant_protocol: Optional[Dict[str, str]]
    crystalloid_resuscitation_guidelines: Dict[str, Union[float, str]]
    refractory_vasopressor_guidelines: Optional[Dict[str, Union[float, str]]]
    secondary_pharmacotherapy: List[Dict[str, str]]
    tryptase_kinetics_interpretation: Optional[Dict[str, Union[float, str, bool]]]
    biphasic_risk_stratification: Dict[str, Union[str, int]]


class AcuteAnaphylaxisDecisionEngine:
    """
    Clinical Decision Support Engine for Acute Anaphylaxis Staging,
    Diagnostic Certainty, Weight-Tiered Epinephrine Dosing, and Resuscitation.
    """

    @staticmethod
    def evaluate_pediatric_hypotension(age_years: float, sbp: int) -> bool:
        """
        Evaluates pediatric hypotension based on age-specific thresholds (PALS/AHA):
        - Term neonates (0-28 days): SBP < 60 mmHg
        - Infants (1-12 months): SBP < 70 mmHg
        - Children (1-10 years): SBP < 70 + (2 * age) mmHg
        - Children > 10 years and Adults: SBP < 90 mmHg
        """
        if age_years < (1.0 / 12.0):
            return sbp < 60
        elif age_years < 1.0:
            return sbp < 70
        elif age_years <= 10.0:
            return sbp < (70 + int(2 * age_years))
        else:
            return sbp < 90

    @classmethod
    def evaluate_wao_eaaci_criteria(
        cls, p: AnaphylaxisPatientPresentation
    ) -> Tuple[bool, str]:
        """
        Evaluates WAO/EAACI 2020 Diagnostic Criteria for Anaphylaxis:
        Criterion 1: Acute onset (minutes to several hours) of skin/mucosal symptoms
                     AND at least ONE of:
                     - Respiratory compromise
                     - Reduced BP / symptoms of end-organ dysfunction
                     - Severe gastrointestinal symptoms (crampy pain, vomiting)
        Criterion 2: Acute onset of hypotension, bronchospasm, or laryngeal involvement
                     AFTER exposure to a KNOWN or HIGHLY PROBABLE allergen, even WITHOUT skin signs.
        """
        has_skin = (
            p.generalized_urticaria
            or p.generalized_erythema_flushing
            or p.angioedema_lips_tongue_uvula_face
            or p.generalized_pruritus
        )

        has_resp = (
            p.audible_stridor_laryngeal_edema
            or p.wheezing_bronchospasm
            or p.severe_dyspnea_hypoxemia
            or p.spo2_percent < 92.0
            or (p.pef_percent_baseline is not None and p.pef_percent_baseline < 70.0)
        )

        is_hypotensive = p.measured_hypotension or cls.evaluate_pediatric_hypotension(
            p.age_years, p.systolic_bp_mmhg
        )

        has_circ = (
            is_hypotensive
            or p.shock_capillary_refill_delayed
            or p.syncope_loss_of_consciousness
            or p.incontinence
        )

        has_severe_gi = p.severe_crampy_abdominal_pain or p.recurrent_vomiting

        # Criterion 1: Skin + (Resp OR Circ OR Severe GI)
        if has_skin and (has_resp or has_circ or has_severe_gi):
            rationale = (
                "Meets WAO/EAACI 2020 Criterion 1: Acute onset of mucocutaneous symptoms "
                "with associated multi-system compromise ("
            )
            components = []
            if has_resp:
                components.append("Respiratory")
            if has_circ:
                components.append("Circulatory")
            if has_severe_gi:
                components.append("Severe Gastrointestinal")
            rationale += ", ".join(components) + ")."
            return True, rationale

        # Criterion 2: Known/Probable allergen + (Hypotension OR Bronchospasm OR Stridor)
        has_known_or_probable = p.known_allergen_exposure or p.probable_allergen_exposure
        has_isolated_severe_target = (
            is_hypotensive
            or p.wheezing_bronchospasm
            or p.audible_stridor_laryngeal_edema
            or p.syncope_loss_of_consciousness
        )

        if has_known_or_probable and has_isolated_severe_target:
            rationale = (
                "Meets WAO/EAACI 2020 Criterion 2: Acute onset of severe airway, respiratory, "
                "or circulatory collapse following exposure to a known/probable allergen, "
                "without requiring cutaneous manifestations."
            )
            return True, rationale

        return False, "Does not meet WAO/EAACI 2020 clinical criteria for acute anaphylaxis."

    @classmethod
    def evaluate_brighton_certainty(
        cls, p: AnaphylaxisPatientPresentation
    ) -> BrightonCertaintyLevel:
        """
        Stratifies presentation into Brighton Collaboration Diagnostic Certainty Levels.
        """
        # Major dermatological
        major_derm = (
            p.generalized_urticaria
            or p.generalized_erythema_flushing
            or p.angioedema_lips_tongue_uvula_face
        )

        # Major cardiovascular
        is_hypotensive = p.measured_hypotension or cls.evaluate_pediatric_hypotension(
            p.age_years, p.systolic_bp_mmhg
        )
        major_cardio = is_hypotensive or p.shock_capillary_refill_delayed or p.syncope_loss_of_consciousness

        # Major respiratory
        major_resp = (
            p.audible_stridor_laryngeal_edema
            or p.wheezing_bronchospasm
            or p.severe_dyspnea_hypoxemia
            or p.spo2_percent < 92.0
        )

        # Minor signs
        minor_cardio = p.heart_rate_bpm > 100 and not major_cardio
        minor_resp = p.rhinorrhea_sneezing_cough or (p.respiratory_rate_bpm > 24 and not major_resp)
        minor_gi = p.severe_crampy_abdominal_pain or p.recurrent_vomiting or p.diarrhea
        minor_derm = p.generalized_pruritus and not major_derm

        # Level 1: >=1 Major Derm AND (>=1 Major Cardio OR >=1 Major Resp)
        if major_derm and (major_cardio or major_resp):
            return BrightonCertaintyLevel.LEVEL_1

        # Level 2:
        # (a) >=1 Major Cardio AND >=1 Major Resp
        # (b) >=1 Major Derm AND (>=1 Minor Cardio OR Minor Resp) AND >=1 Other System
        if major_cardio and major_resp:
            return BrightonCertaintyLevel.LEVEL_2
        if major_derm and (minor_cardio or minor_resp) and minor_gi:
            return BrightonCertaintyLevel.LEVEL_2

        # Level 3:
        # >=1 Major Cardio OR >=1 Major Resp with minor supporting features
        if (major_cardio or major_resp) and (minor_gi or minor_derm or p.known_allergen_exposure):
            return BrightonCertaintyLevel.LEVEL_3

        return BrightonCertaintyLevel.INSUFFICIENT

    @classmethod
    def evaluate_wao_severity_grade(
        cls, p: AnaphylaxisPatientPresentation
    ) -> WAOSeverityGrade:
        """
        Grades severity based on World Allergy Organization (WAO) clinical scoring.
        """
        is_hypotensive = p.measured_hypotension or cls.evaluate_pediatric_hypotension(
            p.age_years, p.systolic_bp_mmhg
        )

        if p.heart_rate_bpm == 0 or p.systolic_bp_mmhg == 0:
            return WAOSeverityGrade.GRADE_5_FATAL

        if is_hypotensive or p.syncope_loss_of_consciousness or p.spo2_percent < 88.0:
            return WAOSeverityGrade.GRADE_4_LIFE_THREATENING

        if (
            p.wheezing_bronchospasm
            or p.audible_stridor_laryngeal_edema
            or p.recurrent_vomiting
            or p.severe_crampy_abdominal_pain
        ):
            return WAOSeverityGrade.GRADE_3_SEVERE

        if (
            p.rhinorrhea_sneezing_cough
            or p.heart_rate_bpm > 100
            or p.respiratory_rate_bpm > 20
        ):
            return WAOSeverityGrade.GRADE_2_MODERATE

        return WAOSeverityGrade.GRADE_1_MILD

    @staticmethod
    def calculate_epinephrine_dosing(
        weight_kg: float, is_adult: bool, severity: WAOSeverityGrade
    ) -> EpinephrineDosingRecommendation:
        """
        Calculates exact weight-tiered epinephrine autoinjector and manual dosing
        respecting pediatric and adult weight cutoffs.
        Standard IM dose: 0.01 mg/kg of 1:1000 (1 mg/mL); max single dose 0.5 mg.
        """
        calculated_exact_dose = min(0.5, round(weight_kg * 0.01, 2))

        # Device and recommended dose selection
        if weight_kg < 7.5:
            dose = max(0.05, round(weight_kg * 0.01, 2))
            device = EpinephrineDeliveryDevice.MANUAL_SYRINGE
            needle = "25G, 5/8-inch (16 mm) needle"
            instructions = (
                f"Draw {dose:.2f} mL (1 mg/mL = 1:1000) using a 1 mL tuberculin syringe. "
                "Inject into anterolateral mid-thigh. Never delay for autoinjector unavailability."
            )
        elif 7.5 <= weight_kg < 15.0:
            dose = 0.10
            device = EpinephrineDeliveryDevice.AUTOINJECTOR_INFANT_01
            needle = "22-25G, 0.5-inch needle"
            instructions = (
                "Administer 0.10 mg autoinjector (Auvi-Q 0.1 mg) or manual 0.10 mL (1:1000) "
                "into anterolateral mid-thigh."
            )
        elif 15.0 <= weight_kg < 30.0:
            dose = 0.15
            device = EpinephrineDeliveryDevice.AUTOINJECTOR_JUNIOR_015
            needle = "22G, 0.5-inch needle"
            instructions = (
                "Administer 0.15 mg autoinjector (EpiPen Jr / Auvi-Q 0.15 mg) into anterolateral mid-thigh. "
                "Hold firmly against thigh for 3 seconds."
            )
        elif 30.0 <= weight_kg < 50.0:
            dose = 0.30
            device = EpinephrineDeliveryDevice.AUTOINJECTOR_ADULT_03
            needle = "22G, 5/8-inch needle"
            instructions = (
                "Administer 0.30 mg autoinjector (EpiPen / Auvi-Q 0.3 mg) into anterolateral mid-thigh. "
                "Hold firmly against thigh for 3 seconds."
            )
        else:
            # Weight >= 50 kg
            if severity in [WAOSeverityGrade.GRADE_4_LIFE_THREATENING, WAOSeverityGrade.GRADE_5_FATAL]:
                dose = 0.50
                device = EpinephrineDeliveryDevice.AUTOINJECTOR_ADULT_05
                instructions = (
                    "Administer 0.50 mg IM (Emerade 0.5 mg autoinjector or 0.50 mL of 1:1000 solution "
                    "via 21-23G 1-inch needle) into anterolateral mid-thigh for severe circulatory collapse."
                )
            else:
                dose = 0.30
                device = EpinephrineDeliveryDevice.AUTOINJECTOR_ADULT_03
                instructions = (
                    "Administer 0.30 mg autoinjector (EpiPen / Auvi-Q 0.3 mg) into anterolateral mid-thigh. "
                    "If severe symptoms persist at 5 minutes, escalate to 0.50 mg IM."
                )
            needle = "21-23G, 1.0 to 1.5-inch needle (ensure adequate muscle penetration in obesity)"

        return EpinephrineDosingRecommendation(
            recommended_dose_mg=dose,
            delivery_device=device,
            route="Intramuscular (IM) strictly - subcutaneous and IV push bolus PROHIBITED in first-line",
            anatomical_site="Anterolateral Mid-Thigh (Vastus Lateralis)",
            needle_gauge_and_length=needle,
            repeat_frequency_minutes="Every 5 to 15 minutes as needed for persistent or refractory symptoms",
            max_single_dose_mg=0.50,
            clinical_instructions=instructions,
        )

    @staticmethod
    def evaluate_beta_blocker_refractoriness(
        p: AnaphylaxisPatientPresentation
    ) -> Optional[Dict[str, str]]:
        """
        Provides Glucagon rescue protocol for patients taking chronic beta-blockers
        who experience bradycardia, refractory hypotension, or poor response to IM epinephrine.
        """
        if not p.on_chronic_beta_blocker:
            return None

        return {
            "protocol_name": "Glucagon Secondary-Messenger Rescue for Beta-Blocker Anaphylaxis",
            "mechanism": (
                "Glucagon activates adenylate cyclase directly via non-adrenergic cell-surface receptors, "
                "bypassing blocked beta-1 and beta-2 receptors to increase intracellular cAMP, "
                "restoring cardiac inotropy and chronotropy without adrenergic receptor binding."
            ),
            "iv_bolus_dose": "Adult: 1.0 - 5.0 mg IV over 5 minutes (Pediatric: 20 - 30 mcg/kg, max 1.0 mg)",
            "continuous_iv_infusion": "2.0 to 10.0 mg/hour titrated to target MAP >= 65 mmHg",
            "side_effects_sentinel": (
                "Glucagon frequently triggers acute vomiting and nausea. Position patient in left lateral "
                "decubitus or protect airway immediately to prevent aspiration pneumonitis."
            ),
            "adjunct_agents": "Isoproterenol infusion or temporary transcutaneous/transvenous pacing if refractory bradycardia persists.",
        }

    @staticmethod
    def calculate_crystalloid_resuscitation(
        weight_kg: float, is_adult: bool, severity: WAOSeverityGrade
    ) -> Dict[str, Union[float, str]]:
        """
        Calculates rapid crystalloid fluid resuscitation volume for post-capillary venodilation
        and plasma extravasation. Up to 35% of circulating volume can extravasate in 10 minutes.
        """
        if is_adult:
            initial_bolus_ml = 1000.0 if severity != WAOSeverityGrade.GRADE_4_LIFE_THREATENING else 2000.0
            max_first_hour_ml = 4000.0
            rate_desc = "Pressure bag infusion of 1000-2000 mL Normosol-R, Plasmalyte, or Normal Saline over 15-30 min."
        else:
            initial_bolus_ml = round(weight_kg * 20.0, 1)
            max_first_hour_ml = round(weight_kg * 60.0, 1)
            rate_desc = f"Rapid push of 20 mL/kg ({initial_bolus_ml:.0f} mL) isotonic crystalloid over 10-20 min; repeat up to 3x."

        return {
            "fluid_type": "Isotonic Balanced Crystalloid (Plasmalyte-A, Lactated Ringer's, or 0.9% Normal Saline)",
            "initial_bolus_ml": initial_bolus_ml,
            "max_first_hour_ml": max_first_hour_ml,
            "administration_rate": rate_desc,
            "positioning_sentinel": (
                "PLACE PATIENT IN SUPINE POSITION WITH LEGS ELEVATED (Trendelenburg/Passive Leg Raise). "
                "NEVER ALLOW PATIENT TO SUDDENLY SIT UP OR STAND: Abrupt standing causes 'empty ventricle syndrome' "
                "and instantaneous pulseless electrical activity (PEA) arrest due to acute venous return cessation."
            ),
        }

    @staticmethod
    def calculate_refractory_vasopressors(
        weight_kg: float, is_adult: bool
    ) -> Dict[str, Union[float, str]]:
        """
        Provides continuous IV vasopressor infusion parameters for refractory anaphylactic shock
        unresponsive to 2 or more IM epinephrine doses and aggressive fluid resuscitation.
        """
        # IV Epinephrine infusion: 0.05 to 0.5 mcg/kg/min (or 2-10 mcg/min in adults)
        min_epi_rate_mcg_min = 2.0 if is_adult else round(weight_kg * 0.05, 2)
        max_epi_rate_mcg_min = 10.0 if is_adult else round(weight_kg * 0.50, 2)

        return {
            "indication": "Refractory Anaphylaxis failing >= 2 doses of IM Epinephrine + 20 mL/kg IV Crystalloids",
            "first_line_infusion": "Continuous IV Epinephrine Infusion via dedicated IV cannula with continuous cardiac monitoring",
            "adult_infusion_range": "2.0 to 10.0 mcg/min (titrate up by 1 mcg/min every 2-3 minutes to MAP >= 65 mmHg)",
            "pediatric_infusion_range": f"{min_epi_rate_mcg_min:.2f} to {max_epi_rate_mcg_min:.2f} mcg/kg/min",
            "push_dose_epinephrine_bridge": (
                "While preparing infusion: Push-Dose Epinephrine (10 mcg/mL). "
                "Dilute 1 mL of 1:10,000 (0.1 mg) in 9 mL Normal Saline. "
                "Administer 0.5 - 2.0 mL (5 - 20 mcg) IV every 2 to 5 minutes as temporizing bridge."
            ),
            "second_line_vasopressor": "Norepinephrine infusion (0.05 - 0.5 mcg/kg/min) for persistent profound vasodilation.",
            "vasopressin_refractory_rescue": "Vasopressin 0.03 units/min IV infusion for catecholamine-resistant vasodilatory collapse.",
        }

    @staticmethod
    def evaluate_tryptase_kinetics(
        acute_tryptase: Optional[float], baseline_tryptase: Optional[float]
    ) -> Optional[Dict[str, Union[float, str, bool]]]:
        """
        Interprets serum mast cell tryptase kinetics based on the international consensus formula:
        Acute Tryptase >= (1.2 * Baseline Tryptase) + 2.0 ug/L.
        """
        if acute_tryptase is None:
            return None

        if baseline_tryptase is None:
            return {
                "acute_tryptase_ug_l": acute_tryptase,
                "baseline_tryptase_ug_l": "Pending (Draw convalescent sample >= 24h post-resolution)",
                "diagnostic_threshold_calculated": "Requires baseline sample",
                "confirms_mast_cell_activation": acute_tryptase > 11.4,
                "interpretation": (
                    f"Acute serum tryptase is {acute_tryptase} ug/L (normal reference < 11.4 ug/L). "
                    "A convalescent sample must be drawn 24 hours later to evaluate the (1.2 * Baseline + 2) formula."
                ),
            }

        threshold = round((1.2 * baseline_tryptase) + 2.0, 2)
        is_positive = acute_tryptase >= threshold

        return {
            "acute_tryptase_ug_l": acute_tryptase,
            "baseline_tryptase_ug_l": baseline_tryptase,
            "diagnostic_threshold_calculated": threshold,
            "confirms_mast_cell_activation": is_positive,
            "interpretation": (
                f"Acute tryptase ({acute_tryptase} ug/L) vs threshold ({threshold} ug/L) based on "
                f"baseline ({baseline_tryptase} ug/L). "
                + (
                    "CONFIRMS MAST CELL ACTIVATION with high clinical specificity."
                    if is_positive
                    else "Does NOT meet threshold for systemic mast cell degranulation. Note: Clinical diagnosis takes precedence."
                )
            ),
        }

    @staticmethod
    def stratify_biphasic_risk(
        p: AnaphylaxisPatientPresentation, severity: WAOSeverityGrade
    ) -> Dict[str, Union[str, int]]:
        """
        Stratifies risk for biphasic anaphylactic recurrence to determine mandatory observation window.
        Biphasic risk factors: severe initial presentation (Grade 3-4), wide pulse pressure,
        delay in epinephrine > 30 min, multiple epinephrine doses required, history of biphasic reaction.
        """
        risk_score = 0
        reasons = []

        if severity in [WAOSeverityGrade.GRADE_3_SEVERE, WAOSeverityGrade.GRADE_4_LIFE_THREATENING]:
            risk_score += 2
            reasons.append("Severe initial clinical presentation (Grade 3 or 4)")

        if p.minutes_since_exposure > 30:
            risk_score += 1
            reasons.append("Delayed presentation/epinephrine > 30 minutes from exposure")

        if p.history_of_biphasic_reaction:
            risk_score += 2
            reasons.append("Prior history of biphasic anaphylaxis")

        if p.history_of_asthma:
            risk_score += 1
            reasons.append("Underlying active asthma / reactive airway disease")

        if p.trigger_type.lower() == "medication":
            risk_score += 1
            reasons.append("Drug-induced anaphylaxis (higher incidence of protracted/biphasic course)")

        if risk_score >= 3:
            category = "HIGH BIPHASIC RISK"
            observation_hours = 12
            rec = (
                "Mandatory 12 to 24 hour inpatient/ICU observation. High probability of secondary "
                "inflammatory recrudescence. Discharge with two unexpired epinephrine autoinjectors."
            )
        elif risk_score >= 1:
            category = "MODERATE BIPHASIC RISK"
            observation_hours = 6
            rec = (
                "Minimum 6 to 8 hour emergency department observation window following complete "
                "resolution of all symptoms. Prescribe autoinjector pair upon discharge."
            )
        else:
            category = "LOW BIPHASIC RISK"
            observation_hours = 4
            rec = "Minimum 4 to 6 hour observation following symptom resolution and epinephrine response."

        return {
            "risk_category": category,
            "risk_score": risk_score,
            "mandatory_observation_hours": observation_hours,
            "clinical_recommendation": rec,
            "risk_factors_present": "; ".join(reasons) if reasons else "No high-risk features identified",
        }

    @classmethod
    def run_clinical_evaluation(
        cls, p: AnaphylaxisPatientPresentation
    ) -> AnaphylaxisClinicalDecisionReport:
        """
        Runs the full end-to-end clinical anaphylaxis decision-support engine.
        """
        meets_wao, wao_rationale = cls.evaluate_wao_eaaci_criteria(p)
        brighton_level = cls.evaluate_brighton_certainty(p)
        severity_grade = cls.evaluate_wao_severity_grade(p)
        epi_rec = cls.calculate_epinephrine_dosing(p.weight_kg, p.is_adult, severity_grade)
        bb_protocol = cls.evaluate_beta_blocker_refractoriness(p)
        crystalloids = cls.calculate_crystalloid_resuscitation(p.weight_kg, p.is_adult, severity_grade)

        vasopressors = None
        if severity_grade in [WAOSeverityGrade.GRADE_4_LIFE_THREATENING, WAOSeverityGrade.GRADE_5_FATAL]:
            vasopressors = cls.calculate_refractory_vasopressors(p.weight_kg, p.is_adult)

        secondary_tx = [
            {
                "drug": "Albuterol (Salbutamol) Inhalation",
                "dose": "2.5 to 5.0 mg nebulized in 3 mL Normal Saline every 20 min as needed",
                "role": "Adjunctive bronchodilator for wheezing/bronchospasm. DOES NOT treat mucosal edema or hypotension.",
            },
            {
                "drug": "Cetirizine / Diphenhydramine (H1 Antihistamine)",
                "dose": "Cetirizine 10 mg IV/oral OR Diphenhydramine 25-50 mg IV/IM (Pediatric: 1 mg/kg, max 50 mg)",
                "role": "Symptomatic relief of pruritus, urticaria, and angioedema. Second-line; never replaces epinephrine.",
            },
            {
                "drug": "Famotidine (H2 Antihistamine)",
                "dose": "Famotidine 20 mg IV over 2 min (Pediatric: 0.5 mg/kg, max 20 mg)",
                "role": "Synergistic H1+H2 blockade for refractory cutaneous flushing and vasodilation.",
            },
            {
                "drug": "Methylprednisolone / Dexamethasone (Corticosteroids)",
                "dose": "Methylprednisolone 1-2 mg/kg IV (max 125 mg) OR Dexamethasone 10 mg IV",
                "role": "Theoretical reduction in biphasic reaction severity. Delayed onset (4-6 hours); zero acute shock reversal.",
            },
        ]

        tryptase_report = cls.evaluate_tryptase_kinetics(
            p.acute_serum_tryptase_ug_l, p.baseline_serum_tryptase_ug_l
        )

        biphasic_report = cls.stratify_biphasic_risk(p, severity_grade)

        return AnaphylaxisClinicalDecisionReport(
            meets_wao_criteria=meets_wao,
            wao_diagnostic_rationale=wao_rationale,
            brighton_level=brighton_level,
            wao_severity_grade=severity_grade,
            epinephrine_recommendation=epi_rec,
            beta_blocker_resistant_protocol=bb_protocol,
            crystalloid_resuscitation_guidelines=crystalloids,
            refractory_vasopressor_guidelines=vasopressors,
            secondary_pharmacotherapy=secondary_tx,
            tryptase_kinetics_interpretation=tryptase_report,
            biphasic_risk_stratification=biphasic_report,
        )


# =====================================================================
# SELF-CONTAINED VERIFICATION & CLINICAL VALIDATION SUITE
# =====================================================================

def verify_clinical_scenarios():
    print("=" * 80)
    print("OpenPHR Cookbook 378: Acute Anaphylaxis WAO/EAACI & Resuscitation Suite")
    print("=" * 80)

    # Test Case 1: Pediatric Peanut Anaphylaxis (22 kg, Grade 3, Wheezing + Hives)
    pt_peds = AnaphylaxisPatientPresentation(
        age_years=6.0,
        weight_kg=22.0,
        is_adult=False,
        heart_rate_bpm=135,
        systolic_bp_mmhg=88,  # Normal for 6yo is > 70 + (2*6) = 82
        diastolic_bp_mmhg=55,
        spo2_percent=91.0,
        respiratory_rate_bpm=32,
        known_allergen_exposure=True,
        probable_allergen_exposure=True,
        trigger_type="Food",
        minutes_since_exposure=15,
        generalized_urticaria=True,
        generalized_erythema_flushing=True,
        angioedema_lips_tongue_uvula_face=True,
        generalized_pruritus=True,
        audible_stridor_laryngeal_edema=False,
        wheezing_bronchospasm=True,
        severe_dyspnea_hypoxemia=True,
        rhinorrhea_sneezing_cough=True,
        pef_percent_baseline=60.0,
        history_of_asthma=True,
        acute_serum_tryptase_ug_l=18.5,
        baseline_serum_tryptase_ug_l=4.2,
    )

    report_peds = AcuteAnaphylaxisDecisionEngine.run_clinical_evaluation(pt_peds)

    assert report_peds.meets_wao_criteria is True, "Peds must meet WAO criteria"
    assert report_peds.brighton_level == BrightonCertaintyLevel.LEVEL_1, "Must be Brighton Level 1"
    assert report_peds.wao_severity_grade == WAOSeverityGrade.GRADE_3_SEVERE, "Must be Grade 3 Severe"
    assert report_peds.epinephrine_recommendation.recommended_dose_mg == 0.15, "22 kg child receives 0.15 mg autoinjector"
    assert report_peds.tryptase_kinetics_interpretation["confirms_mast_cell_activation"] is True

    print("[*] Test Case 1 (Pediatric Food Anaphylaxis - 22 kg) PASSED")
    print(f"    - WAO Criteria: {report_peds.meets_wao_criteria} | Severity: {report_peds.wao_severity_grade.value}")
    print(f"    - Recommended Epinephrine: {report_peds.epinephrine_recommendation.recommended_dose_mg} mg IM ({report_peds.epinephrine_recommendation.delivery_device.value})")
    print(f"    - Tryptase Result: {report_peds.tryptase_kinetics_interpretation['interpretation']}")

    # Test Case 2: Adult Beta-Blocker Hymenoptera Venom Anaphylactic Shock (75 kg, Grade 4)
    pt_adult_bb = AnaphylaxisPatientPresentation(
        age_years=58.0,
        weight_kg=75.0,
        is_adult=True,
        heart_rate_bpm=52,  # Relative bradycardia from beta-blocker
        systolic_bp_mmhg=72,  # Profound hypotension
        diastolic_bp_mmhg=40,
        spo2_percent=87.0,
        respiratory_rate_bpm=28,
        known_allergen_exposure=True,
        probable_allergen_exposure=True,
        trigger_type="Venom",
        minutes_since_exposure=20,
        generalized_urticaria=False,  # Anaphylactic shock without hives
        generalized_erythema_flushing=False,
        angioedema_lips_tongue_uvula_face=False,
        generalized_pruritus=False,
        audible_stridor_laryngeal_edema=True,
        wheezing_bronchospasm=True,
        severe_dyspnea_hypoxemia=True,
        rhinorrhea_sneezing_cough=False,
        measured_hypotension=True,
        shock_capillary_refill_delayed=True,
        syncope_loss_of_consciousness=True,
        on_chronic_beta_blocker=True,
        history_of_prior_anaphylaxis=True,
    )

    report_adult = AcuteAnaphylaxisDecisionEngine.run_clinical_evaluation(pt_adult_bb)

    assert report_adult.meets_wao_criteria is True, "Adult without skin signs meets WAO Criterion 2"
    assert report_adult.wao_severity_grade == WAOSeverityGrade.GRADE_4_LIFE_THREATENING, "Must be Grade 4 Life-Threatening"
    assert report_adult.epinephrine_recommendation.recommended_dose_mg == 0.50, "Life-threatening adult collapse gets 0.50 mg"
    assert report_adult.beta_blocker_resistant_protocol is not None, "Must trigger Glucagon rescue protocol"
    assert report_adult.refractory_vasopressor_guidelines is not None, "Must trigger vasopressor protocol"

    print("[*] Test Case 2 (Adult Venom Shock on Beta-Blocker - 75 kg) PASSED")
    print(f"    - WAO Criteria: {report_adult.meets_wao_criteria} (Without Cutaneous Signs - Criterion 2)")
    print(f"    - Recommended Epinephrine: {report_adult.epinephrine_recommendation.recommended_dose_mg} mg IM ({report_adult.epinephrine_recommendation.anatomical_site})")
    print(f"    - Glucagon Rescue: {report_adult.beta_blocker_resistant_protocol['iv_bolus_dose']}")
    print(f"    - Vasopressor Rescue: {report_adult.refractory_vasopressor_guidelines['first_line_infusion']}")
    print(f"    - Positioning Sentinel: {report_adult.crystalloid_resuscitation_guidelines['positioning_sentinel'][:75]}...")

    print("\n>>> ALL CLINICAL VERIFICATION TESTS PASSED (100% CONCORDANCE) <<<")


if __name__ == "__main__":
    verify_clinical_scenarios()

Clinical Safety Sentinels & Practical Prescribing Rules

  1. Intramuscular Vastus Lateralis Only: Subcutaneous delivery yields erratic, delayed systemic absorption because alpha-1 adrenergic cutaneous vasoconstriction traps the drug locally. Intravenous push boluses of undiluted $1:1000$ epinephrine are lethal and strictly contraindicated outside of full cardiac arrest due to malignant ventricular tachyarrhythmias, hypertensive crisis, and myocardial infarction.
  2. The “Empty Ventricle” Fatal Posture Error: Sudden upright elevation or walking by a patient experiencing anaphylaxis can cause instantaneous cardiac arrest. Venous pooling in dilated splanchnic and lower extremity vascular beds abruptly cuts off cardiac preload to a tachycardic, hypercontractile heart, resulting in pulseless electrical activity (PEA). Keep patients strictly supine with legs elevated throughout resuscitation.
  3. Glucagon Sentinel for Beta-Blocker Patients: Patients on metoprolol, carvedilol, propranolol, or atenolol who do not promptly respond to their first or second IM epinephrine dose require immediate IV Glucagon ($1 - 5\text{ mg}$ over $5\text{ minutes}$, followed by $2 - 10\text{ mg/hr}$ infusion). Because glucagon triggers forceful emesis, airway suctioning and lateral positioning must be prepared prior to injection.
  4. Biphasic Recurrence Window: Secondary anaphylactic collapse without allergen re-exposure occurs in up to $20\%$ of severe cases. Patients presenting with hypotension, requiring multiple doses of epinephrine, or having delayed initial therapy must be monitored for a minimum of $8 - 24\text{ hours}$ in a telemetry or intensive care setting before safe discharge.

Quality Assurance & Verification