Cookbook 380: Offline Clinical Endocrinology & Critical Care Acute Adrenal Crisis Diagnostic Staging, Cosyntropin (ACTH) Stimulation Test Interpreter, Stress-Dose Hydrocortisone Titrator & Fludrocortisone Transition Protocol

Executive Clinical Overview

Acute Adrenal Crisis is a life-threatening, hyper-acute endocrine emergency resulting from acute absolute or relative insufficiency of glucocorticoid (and frequently mineralocorticoid) hormones in patients with primary, secondary, or tertiary adrenal insufficiency. Left untreated, acute adrenal crisis progresses rapidly to refractory vasodilatory shock, hypovolemic vascular collapse, lethal dysrhythmias from hyperkalemia, profound hypoglycemia, and death.

Adrenal crisis occurs in approximately $6 - 8\%$ of patients with diagnosed adrenal insufficiency per year, with a mortality rate between $0.5\%$ and $2.0\%$ per episode. The event is most commonly precipitated by acute physiological stress: sepsis, gastrointestinal illnesses with vomiting/diarrhea preventing oral medication absorption, major surgery, trauma, or abrupt cessation of long-term exogenous corticosteroid therapy.

Despite authoritative clinical practice guidelines published by the Endocrine Society, the European Society of Endocrinology (ESE), and the American Association of Clinical Endocrinology (AACE), severe morbidity and avoidable mortality persist due to three catastrophic clinical pitfalls:

  1. Delaying Glucocorticoids for Laboratory Confirmation: Waiting for baseline serum cortisol or cosyntropin stimulation results before administering intravenous hydrocortisone is the leading cause of preventable death. If adrenal crisis is clinically suspected, emergency treatment must be initiated immediately. When diagnostic sampling is strictly desired before treatment, Dexamethasone ($4\text{ mg}$ IV) must be selected because it does not cross-react with standard laboratory cortisol radioimmunoassays (unlike hydrocortisone).
  2. Failure to Recognize Relative Adrenal Insufficiency in Septic Shock: Critical Illness-Related Corticosteroid Insufficiency (CIRCI) causes profound vascular hyporesponsiveness to catecholamines (down-regulation of vascular $\alpha_1$-adrenergic receptors), requiring prompt stress-dose corticosteroid rescue.
  3. Fludrocortisone Redundancy during Acute Hydrocortisone Therapy: Prescribing mineralocorticoid (fludrocortisone) during acute resuscitation with high-dose hydrocortisone ($\ge 50\text{ mg/day}$) is redundant and unnecessary because hydrocortisone possesses intrinsic mineralocorticoid activity ($20\text{ mg}$ hydrocortisone $\approx 0.1\text{ mg}$ fludrocortisone equivalency). Oral fludrocortisone is only indicated when hydrocortisone is tapered below $50\text{ mg/day}$.
+---------------------------------------------------------------------------------------------------------+
|                        ACUTE ADRENAL CRISIS DIAGNOSTIC & RESUSCITATION CASCADE                          |
+---------------------------------------------------------------------------------------------------------+
| 1. IMMEDIATE CLINICAL DIAGNOSTIC GATING (ENDOCRINE SOCIETY CRITERIA)                                    |
|    - Severe Absolute/Relative Hypotension: SBP < 90 mmHg OR >= 20 mmHg drop from baseline               |
|      REFRACTORY to aggressive crystalloid boluses and catecholamine vasopressors.                       |
|    - PLUS at least TWO of:                                                                              |
|      * Severe acute abdominal symptoms (pain, vomiting, diarrhea, mimicking acute surgical abdomen)     |
|      * Profound unexplained fatigue, lethargy, or acute encephalopathy/delirium                         |
|      * Hyponatremia (Na < 135 mEq/L) AND/OR Hyperkalemia (K > 5.0 mEq/L) [Primary Adrenal Insufficiency] |
|      * Severe Hypoglycemia (Glucose < 70 mg/dL, especially infants, children, or secondary AI)          |
|      * Fever or acute hypothermia                                                                       |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 2. IMMEDIATE EMERGENCY PHARMACOTHERAPY (ZERO DELAY FOR LAB WORK)                                        |
|    - IF DIAGNOSIS ALREADY KNOWN:                                                                        |
|      * Hydrocortisone Sodium Succinate: 100 mg IV STAT bolus immediately.                               |
|      * Followed by 200 mg / 24 hours continuous IV infusion OR 50 mg IV every 6 hours.                  |
|    - IF ADRENAL INSUFFICIENCY SUSPECTED BUT UNCONFIRMED (DIAGNOSTIC WORKUP DESIRED):                    |
|      * Draw baseline Cortisol & ACTH tube immediately.                                                  |
|      * Administer Dexamethasone 4.0 mg IV STAT (Zero assay interference with cortisol immunoassays).     |
|      * Perform Cosyntropin (ACTH) Stimulation Test simultaneously without delaying corticosteroid cover.|
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 3. AGGRESSIVE RESUSCITATION & ELECTROLYTE / METABOLIC CORRECTION                                        |
|    - Volume Expansion: 1000 mL 0.9% Normal Saline (or 5% Dextrose in Normal Saline - D5NS) in hour 1,   |
|      followed by 2000 - 4000 mL over next 24 hours to restore intravascular volume.                     |
|    - Hypoglycemia Correction: D10W or D50W push if blood glucose < 70 mg/dL.                            |
|    - Hyperkalemia Sentinel: Hyperkalemia resolves rapidly with hydrocortisone & saline; avoid insulin   |
|      pushes unless ECG reveals life-threatening sine waves (insulin precipitates fatal hypoglycemia).   |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 4. STABILIZATION, TAPERING & ORAL FLUDROCORTISONE TRANSITION                                             |
|    - Tapering Schedule: Decrease hydrocortisone by 50% daily once patient is hemodynamically stable,     |
|      afebrile, and tolerating oral nutrition (Day 2: 50 mg q8h; Day 3: 25 mg q8h; Day 4: baseline).     |
|    - Oral Fludrocortisone Trigger: Initiate Fludrocortisone 0.05 - 0.2 mg PO daily ONLY when total daily|
|      hydrocortisone dose drops below 50 mg/day (in primary adrenal insufficiency only).                  |
+---------------------------------------------------------------------------------------------------------+

Cosyntropin (ACTH 1-24) Stimulation Test Kinetic Interpretation

The Cosyntropin stimulation test evaluates adrenal functional reserve by administering synthetic $\alpha^{1-24}\text{-corticotropin}$:

Modality Dose & Delivery Indication & Kinetics Cutoff for Normal Adrenal Reserve
Standard High-Dose $250\ \mu\text{g}$ IV / IM Gold standard for Primary Adrenal Insufficiency; maximal adrenocortical stimulation. Peak Cortisol $\ge 18.0\ \mu\text{g/dL}$ ($500\text{ nmol/L}$) at $30$ or $60\text{ min}$.
Low-Dose / Physiological $1.0\ \mu\text{g}$ IV Highly sensitive for Secondary/Tertiary (Central) Adrenal Insufficiency; avoids supraphysiologic stimulation. Peak Cortisol $\ge 18.0\ \mu\text{g/dL}$ at $30\text{ min}$.

Primary vs. Secondary Adrenal Insufficiency Differentiation

\[\text{Etiology Classification} = \begin{cases} \text{Primary Adrenal Insufficiency (Addison's)}, & \text{Peak Cortisol} < 18\ \mu\text{g/dL} \text{ AND Baseline ACTH} > 2 \times \text{ULN} \ (\ge 60\ \text{pg/mL}) \\ \text{Secondary / Tertiary Adrenal Insufficiency}, & \text{Peak Cortisol} < 18\ \mu\text{g/dL} \text{ AND Baseline ACTH Normal or Low} \ (< 30\ \text{pg/mL}) \\ \text{Adrenal Reserve Intact (No Primary AI)}, & \text{Peak Cortisol} \ge 18.0\ \mu\text{g/dL} \end{cases}\]

Glucocorticoid Equivalent Potency & Mineralocorticoid Ratio

Understanding corticosteroid potency ratios is critical to prevent under-dosing or inadvertent assay interference:

\[\begin{array}{lcccc} \hline \textbf{Steroid Compound} & \textbf{Equivalent Dose (mg)} & \textbf{Anti-Inflammatory Potency} & \textbf{Mineralocorticoid Potency} & \textbf{Cortisol Assay Interference} \\ \hline \text{Hydrocortisone (Cortisol)} & 20.0 & 1.0 & 1.0 & \textbf{YES (100\% Cross-Reaction)} \\ \text{Cortisone Acetate} & 25.0 & 0.8 & 0.8 & \textbf{YES} \\ \text{Prednisone / Prednisolone} & 5.0 & 4.0 & 0.8 & \textbf{YES (Partial 10-25\%)} \\ \text{Methylprednisolone} & 4.0 & 5.0 & 0.5 & \textbf{Minimal (< 5\%)} \\ \textbf{Dexamethasone} & \mathbf{0.75} & \mathbf{25.0} & \mathbf{0.0} & \textbf{ZERO (0\% Cross-Reaction)} \\ \text{Fludrocortisone} & 2.0 & 10.0 & 125.0 & \text{None} \\ \hline \end{array}\]

Production Python Implementation

The following complete, zero-dependency Python clinical decision-support engine provides automated diagnostic criteria evaluation, cosyntropin stimulation kinetics interpretation, weight-tiered pediatric and adult stress-dose titrators, and oral fludrocortisone transition schedules.

#!/usr/bin/env python3
"""
OpenPHR Cookbook 380: Offline Clinical Endocrinology & Critical Care Engine
Acute Adrenal Crisis Staging, Cosyntropin Stimulation Test Interpreter,
Stress-Dose Hydrocortisone Titrator & Fludrocortisone Transition Protocol.

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

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


class AdrenalInsufficiencyType(Enum):
    PRIMARY_ADDISONS = "Primary Adrenal Insufficiency (Addison's Disease - Adrenocortical Destruction)"
    SECONDARY_TERTIARY_CENTRAL = "Secondary or Tertiary Adrenal Insufficiency (Hypothalamic-Pituitary Axis Failure / Exogenous Steroid Suppression)"
    CIRCI_CRITICAL_ILLNESS = "Critical Illness-Related Corticosteroid Insufficiency (CIRCI / Septic Shock Relative AI)"
    NORMAL_ADRENAL_RESERVE = "Intact Adrenocortical Reserve (Excludes Primary Adrenal Insufficiency)"
    INDETERMINATE = "Indeterminate / Requires Complete Cosyntropin Dynamic Stimulation Testing"


class ClinicalCrisisSeverity(Enum):
    REFRACTORY_SHOCK = "Life-Threatening Refractory Shock / Impending Cardiovascular Collapse"
    SEVERE_ACUTE_CRISIS = "Severe Acute Adrenal Crisis"
    INCIPIENT_IMPENDING_CRISIS = "Incipient / Impending Adrenal Crisis (Pre-Shock Phase)"
    STABLE_OUTPATIENT = "Stable Outpatient / Non-Crisis Presentation"


@dataclass
class AdrenalCrisisPatientPresentation:
    # Patient demographics
    age_years: float
    weight_kg: float
    is_adult: bool
    is_pregnant: bool = False
    # Vital signs
    heart_rate_bpm: int = 110
    systolic_bp_mmhg: int = 80
    diastolic_bp_mmhg: int = 48
    baseline_typical_sbp: int = 120
    temperature_celsius: float = 38.5
    # Clinical manifestations
    refractory_to_fluids_and_pressors: bool = True
    acute_abdominal_pain_vomiting_diarrhea: bool = True
    profound_weakness_lethargy_delirium: bool = True
    hypoglycemia_symptoms: bool = True
    hyperkalemic_ecg_changes: bool = False
    known_prior_adrenal_insufficiency: bool = False
    chronic_exogenous_steroid_use: bool = False
    precipitating_illness: str = "Severe Sepsis / Gastroenteritis"
    # Laboratory parameters
    serum_sodium_meq_l: float = 126.0
    serum_potassium_meq_l: float = 5.8
    serum_glucose_mg_dl: float = 58.0
    baseline_cortisol_ug_dl: Optional[float] = None
    baseline_acth_pg_ml: Optional[float] = None
    cosyntropin_stimulated_30min_cortisol_ug_dl: Optional[float] = None
    cosyntropin_stimulated_60min_cortisol_ug_dl: Optional[float] = None


@dataclass
class HydrocortisoneRegimen:
    initial_iv_bolus_mg: float
    maintenance_schedule: str
    daily_total_dose_mg: float
    alternative_continuous_infusion_rate_mg_hr: float
    diagnostic_steroid_substitute: str
    clinical_rationale: str


@dataclass
class CosyntropinTestResult:
    test_type: str
    peak_cortisol_ug_dl: float
    normal_cutoff_ug_dl: float
    is_insufficient: bool
    etiology: AdrenalInsufficiencyType
    interpretation: str


@dataclass
class AdrenalCrisisDecisionReport:
    meets_adrenal_crisis_criteria: bool
    diagnostic_rationale: str
    severity_classification: ClinicalCrisisSeverity
    hydrocortisone_recommendation: HydrocortisoneRegimen
    cosyntropin_analysis: Optional[CosyntropinTestResult]
    fluid_resuscitation_protocol: Dict[str, Union[str, float]]
    electrolyte_management: Dict[str, str]
    tapering_and_fludrocortisone_transition: Dict[str, Union[str, List[str]]]


class AcuteAdrenalCrisisEngine:
    """
    Clinical Decision Support Engine for Acute Adrenal Crisis Diagnostic Gating,
    Cosyntropin Kinetics Interpretation, Stress-Dose Titration, and Fluid Resuscitation.
    """

    @classmethod
    def evaluate_diagnostic_criteria(
        cls, p: AdrenalCrisisPatientPresentation
    ) -> Tuple[bool, str, ClinicalCrisisSeverity]:
        """
        Evaluates Endocrine Society Consensus Criteria for Acute Adrenal Crisis:
        1. Severe absolute hypotension (SBP < 90 mmHg) or relative hypotension (drop >= 20 mmHg)
           unresponsive or poorly responsive to fluids/vasopressors.
        2. PLUS at least TWO supporting clinical/metabolic criteria:
           - Severe acute abdominal pain, nausea, vomiting, or diarrhea
           - Profound lethargy, confusion, or delirium
           - Hyponatremia (Na < 135 mEq/L)
           - Hyperkalemia (K > 5.0 mEq/L)
           - Hypoglycemia (Glucose < 70 mg/dL)
           - Fever or hypothermia
        """
        sbp_drop = p.baseline_typical_sbp - p.systolic_bp_mmhg
        has_hypotension = p.systolic_bp_mmhg < 90 or sbp_drop >= 20

        supporting_points = []
        if p.acute_abdominal_pain_vomiting_diarrhea:
            supporting_points.append("Severe gastrointestinal symptoms (abdominal pain/vomiting/diarrhea)")
        if p.profound_weakness_lethargy_delirium:
            supporting_points.append("Profound weakness / altered mental status")
        if p.serum_sodium_meq_l < 135.0:
            supporting_points.append(f"Hyponatremia ({p.serum_sodium_meq_l} mEq/L)")
        if p.serum_potassium_meq_l > 5.0:
            supporting_points.append(f"Hyperkalemia ({p.serum_potassium_meq_l} mEq/L)")
        if p.serum_glucose_mg_dl < 70.0:
            supporting_points.append(f"Hypoglycemia ({p.serum_glucose_mg_dl} mg/dL)")
        if p.temperature_celsius >= 38.0 or p.temperature_celsius < 36.0:
            supporting_points.append(f"Temperature instability ({p.temperature_celsius} °C)")

        meets_criteria = has_hypotension and len(supporting_points) >= 2

        if p.refractory_to_fluids_and_pressors and has_hypotension:
            severity = ClinicalCrisisSeverity.REFRACTORY_SHOCK
        elif meets_criteria:
            severity = ClinicalCrisisSeverity.SEVERE_ACUTE_CRISIS
        elif has_hypotension or len(supporting_points) >= 2:
            severity = ClinicalCrisisSeverity.INCIPIENT_IMPENDING_CRISIS
        else:
            severity = ClinicalCrisisSeverity.STABLE_OUTPATIENT

        if meets_criteria:
            rationale = (
                f"Meets Endocrine Society criteria for Acute Adrenal Crisis: Hemodynamic instability "
                f"(SBP {p.systolic_bp_mmhg} mmHg, drop of {sbp_drop} mmHg) with {len(supporting_points)} "
                f"major metabolic/clinical manifestations: {', '.join(supporting_points)}."
            )
        else:
            rationale = (
                f"Does not meet strict Endocrine Society criteria (Hypotension: {has_hypotension}, "
                f"Supporting points: {len(supporting_points)}/2)."
            )

        return meets_criteria, rationale, severity

    @classmethod
    def interpret_cosyntropin_test(
        cls, p: AdrenalCrisisPatientPresentation
    ) -> Optional[CosyntropinTestResult]:
        """
        Interprets dynamic Corticotropin / ACTH stimulation testing:
        - Normal peak cortisol cutoff: >= 18.0 ug/dL (500 nmol/L) at 30 or 60 min.
        - Primary AI: Peak Cortisol < 18.0 ug/dL AND Baseline ACTH >= 60 pg/mL (>= 2x ULN).
        - Secondary AI: Peak Cortisol < 18.0 ug/dL AND Baseline ACTH < 30 pg/mL (low or inappropriately normal).
        """
        vals = []
        if p.cosyntropin_stimulated_30min_cortisol_ug_dl is not None:
            vals.append(p.cosyntropin_stimulated_30min_cortisol_ug_dl)
        if p.cosyntropin_stimulated_60min_cortisol_ug_dl is not None:
            vals.append(p.cosyntropin_stimulated_60min_cortisol_ug_dl)

        if not vals:
            if p.baseline_cortisol_ug_dl is not None:
                if p.baseline_cortisol_ug_dl < 3.0:
                    etiology = AdrenalInsufficiencyType.PRIMARY_ADDISONS if (p.baseline_acth_pg_ml and p.baseline_acth_pg_ml > 60) else AdrenalInsufficiencyType.INDETERMINATE
                    return CosyntropinTestResult(
                        test_type="Morning Basal Cortisol Screening",
                        peak_cortisol_ug_dl=p.baseline_cortisol_ug_dl,
                        normal_cutoff_ug_dl=18.0,
                        is_insufficient=True,
                        etiology=etiology,
                        interpretation=f"Morning basal serum cortisol is profoundly low ({p.baseline_cortisol_ug_dl} ug/dL < 3.0 ug/dL), virtually diagnostic of Adrenal Insufficiency.",
                    )
            return None

        peak = max(vals)
        normal_cutoff = 18.0
        is_insufficient = peak < normal_cutoff

        if not is_insufficient:
            etiology = AdrenalInsufficiencyType.NORMAL_ADRENAL_RESERVE
            interp = f"Normal adrenocortical peak response ({peak} ug/dL >= {normal_cutoff} ug/dL). Excludes primary adrenal insufficiency."
        else:
            if p.baseline_acth_pg_ml is not None:
                if p.baseline_acth_pg_ml >= 60.0:
                    etiology = AdrenalInsufficiencyType.PRIMARY_ADDISONS
                    interp = f"Subnormal peak cortisol ({peak} ug/dL < {normal_cutoff} ug/dL) with elevated ACTH ({p.baseline_acth_pg_ml} pg/mL >= 60 pg/mL). Confirms Primary Adrenal Insufficiency."
                else:
                    etiology = AdrenalInsufficiencyType.SECONDARY_TERTIARY_CENTRAL
                    interp = f"Subnormal peak cortisol ({peak} ug/dL < {normal_cutoff} ug/dL) with low/normal ACTH ({p.baseline_acth_pg_ml} pg/mL). Confirms Secondary/Tertiary Central Adrenal Insufficiency."
            else:
                etiology = AdrenalInsufficiencyType.INDETERMINATE
                interp = f"Subnormal peak cortisol ({peak} ug/dL < {normal_cutoff} ug/dL). Establishes Adrenal Insufficiency; pending baseline ACTH to classify primary vs central."

        return CosyntropinTestResult(
            test_type="Standard 250 mcg Cosyntropin (ACTH 1-24) Stimulation Test",
            peak_cortisol_ug_dl=peak,
            normal_cutoff_ug_dl=normal_cutoff,
            is_insufficient=is_insufficient,
            etiology=etiology,
            interpretation=interp,
        )

    @staticmethod
    def calculate_hydrocortisone_dosing(
        age_years: float, weight_kg: float, is_adult: bool
    ) -> HydrocortisoneRegimen:
        """
        Calculates stress-dose hydrocortisone regimen according to international guidelines:
        - Adults: 100 mg IV STAT bolus, followed by 200 mg/24h (either 200 mg continuous infusion or 50 mg IV q6h).
        - Pediatrics:
          * Age < 3 years: 25 mg IV bolus, then 25-30 mg/day divided q6h
          * Age 3 - 12 years: 50 mg IV bolus, then 50-60 mg/day divided q6h
          * Age > 12 years: 100 mg IV bolus, then 100-200 mg/day divided q6h
        - Diagnostic Bridge: Dexamethasone 4.0 mg IV (zero immunoassay interference).
        """
        if is_adult or age_years >= 12.0:
            bolus = 100.0
            maintenance = "50 mg IV every 6 hours (or continuous infusion of 200 mg/24 hours)"
            daily_total = 200.0
            infusion_rate = round(200.0 / 24.0, 1)  # ~8.3 mg/hr
            rationale = (
                "Standard adult emergency stress dosing provides maximal glucocorticoid and "
                "saturating mineralocorticoid coverage (~200 mg hydrocortisone = ~1.0 mg fludrocortisone equivalency)."
            )
        elif age_years >= 3.0:
            bolus = 50.0
            maintenance = "12.5 to 15 mg IV every 6 hours (total 50-60 mg/24h)"
            daily_total = 50.0
            infusion_rate = round(50.0 / 24.0, 1)
            rationale = "Pediatric (3-12 years) stress dosing calibrated to body surface area (~50-100 mg/m2/day)."
        else:
            bolus = 25.0
            maintenance = "6.25 to 7.5 mg IV every 6 hours (total 25-30 mg/24h)"
            daily_total = 25.0
            infusion_rate = round(25.0 / 24.0, 1)
            rationale = "Infant/Toddler (< 3 years) emergency stress bolus to prevent catastrophic hypoglycemic seizure and shock."

        return HydrocortisoneRegimen(
            initial_iv_bolus_mg=bolus,
            maintenance_schedule=maintenance,
            daily_total_dose_mg=daily_total,
            alternative_continuous_infusion_rate_mg_hr=infusion_rate,
            diagnostic_steroid_substitute="Dexamethasone 4.0 mg IV STAT (Pediatric: 0.1 - 0.2 mg/kg, max 4 mg)",
            clinical_rationale=rationale,
        )

    @staticmethod
    def calculate_fluid_resuscitation(
        weight_kg: float, is_adult: bool, glucose_mg_dl: float
    ) -> Dict[str, Union[str, float]]:
        """
        Calculates fluid resuscitation and glucose rescue parameters.
        """
        if is_adult:
            initial_vol = 1000.0
            fluid_type = "0.9% Normal Saline (or 5% Dextrose in Normal Saline - D5NS if hypoglycemic)"
            rate = "1000 mL IV in the first hour, then 500 mL/hr for 2 hours, then 2000-3000 mL over remainder of 24h."
        else:
            initial_vol = round(weight_kg * 20.0, 1)
            fluid_type = "0.9% Normal Saline bolus (20 mL/kg); add D5W/D10W immediately if hypoglycemia present"
            rate = f"{initial_vol:.0f} mL IV bolus over 30-60 minutes; repeat up to 40-60 mL/kg if perfusion impaired."

        hypo_rescue = "None indicated (Blood glucose >= 70 mg/dL)"
        if glucose_mg_dl < 70.0:
            if is_adult:
                hypo_rescue = "Administer 50 mL of 50% Dextrose (D50W) IV STAT bolus (25 g elemental dextrose); infuse D5NS maintenance."
            else:
                hypo_rescue = f"Administer 2.0 mL/kg of 10% Dextrose (D10W) IV STAT ({round(weight_kg * 2.0, 1)} mL); maintain continuous dextrose infusion."

        return {
            "initial_bolus_ml": initial_vol,
            "recommended_iv_fluid": fluid_type,
            "infusion_timeline": rate,
            "hypoglycemia_rescue_protocol": hypo_rescue,
            "potassium_guardrail": (
                "DO NOT ADD POTASSIUM TO IV FLUIDS during initial resuscitation. Hyperkalemia is common "
                "in primary AI and will normalize rapidly with volume expansion and hydrocortisone."
            ),
        }

    @staticmethod
    def generate_electrolyte_protocol(
        sodium: float, potassium: float, glucose: float
    ) -> Dict[str, str]:
        """
        Provides guardrails for electrolyte and glucose anomalies in acute adrenal crisis.
        """
        na_action = "Serum sodium within normal limits."
        if sodium < 130.0:
            na_action = (
                f"Severe Hyponatremia ({sodium} mEq/L) driven by cortisol-deficiency-induced non-osmotic ADH "
                "secretion (euvolemic/hypovolemic). Correct cautiously (< 8-10 mEq/L in 24 hours) to prevent "
                "osmotic demyelination syndrome (ODS). Hydrocortisone alone will prompt rapid aquaresis."
            )

        k_action = "Serum potassium within normal limits."
        if potassium > 5.0:
            k_action = (
                f"Hyperkalemia ({potassium} mEq/L) resulting from aldosterone deficiency (isolated to primary AI). "
                "RESOLVES RAPIDLY with Hydrocortisone and Normal Saline. AVOID standard insulin/dextrose shifts "
                "unless life-threatening ECG changes (sine wave, loss of P wave) are present, as insulin can trigger "
                "lethal intractable hypoglycemia in the absence of cortisol."
            )

        return {
            "hyponatremia_strategy": na_action,
            "hyperkalemia_strategy": k_action,
        }

    @staticmethod
    def generate_tapering_and_fludrocortisone_plan() -> Dict[str, Union[str, List[str]]]:
        """
        Outlines multi-day steroid taper and oral fludrocortisone transition.
        """
        return {
            "transition_trigger": (
                "Initiate tapering when patient is hemodynamically stable for >= 24 hours, afebrile, "
                "and able to tolerate oral medication and meals."
            ),
            "stepwise_tapering_schedule": [
                "Day 1 (Acute Crisis): Hydrocortisone 100 mg IV bolus, then 50 mg IV q6h (200 mg/day).",
                "Day 2 (Stabilization): Hydrocortisone 50 mg IV every 8 hours (150 mg/day).",
                "Day 3 (Clinical Improvement): Hydrocortisone 25 mg IV or PO every 8 hours (75 mg/day).",
                "Day 4 (Transition Phase): Hydrocortisone 20 mg PO on waking, 10 mg PO at 14:00 (30 mg/day).",
                "Day 5+ (Maintenance): Return to patient's baseline maintenance (typically 15-25 mg/day in divided doses).",
            ],
            "fludrocortisone_rules": (
                "Fludrocortisone (0.05 - 0.2 mg PO once daily in the morning) is required ONLY in Primary Adrenal "
                "Insufficiency. DO NOT initiate during acute resuscitation because stress doses of hydrocortisone "
                "(>= 50 mg/day) provide 100% saturating mineralocorticoid receptor activity. Start fludrocortisone "
                "on Day 4 or when hydrocortisone dose drops below 50 mg/day."
            ),
            "discharge_sentinels": [
                "1. Provide emergency intramuscular Hydrocortisone (100 mg vial) with syringes and teach self-injection.",
                "2. Issue medical alert bracelet / necklace stating 'Adrenal Insufficiency - Requires Emergency Hydrocortisone'.",
                "3. Patient and family education on 'Sick Day Rules' (double oral dose for fever > 38°C; triple dose for severe illness).",
                "4. Refer for endocrinology outpatient follow-up within 1-2 weeks.",
            ],
        }

    @classmethod
    def run_clinical_assessment(
        cls, p: AdrenalCrisisPatientPresentation
    ) -> AdrenalCrisisDecisionReport:
        """
        Runs the comprehensive end-to-end clinical assessment.
        """
        meets_crisis, rationale, severity = cls.evaluate_diagnostic_criteria(p)
        hydro = cls.calculate_hydrocortisone_dosing(p.age_years, p.weight_kg, p.is_adult)
        cosyntropin = cls.interpret_cosyntropin_test(p)
        fluids = cls.calculate_fluid_resuscitation(p.weight_kg, p.is_adult, p.serum_glucose_mg_dl)
        electrolytes = cls.generate_electrolyte_protocol(
            p.serum_sodium_meq_l, p.serum_potassium_meq_l, p.serum_glucose_mg_dl
        )
        taper_fludro = cls.generate_tapering_and_fludrocortisone_plan()

        return AdrenalCrisisDecisionReport(
            meets_adrenal_crisis_criteria=meets_crisis,
            diagnostic_rationale=rationale,
            severity_classification=severity,
            hydrocortisone_recommendation=hydro,
            cosyntropin_analysis=cosyntropin,
            fluid_resuscitation_protocol=fluids,
            electrolyte_management=electrolytes,
            tapering_and_fludrocortisone_transition=taper_fludro,
        )


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

def verify_clinical_scenarios():
    print("=" * 80)
    print("OpenPHR Cookbook 380: Acute Adrenal Crisis & Corticosteroid Titration Suite")
    print("=" * 80)

    # Test Case 1: Adult Addisonian Adrenal Crisis in Septic Shock (70 kg, SBP 76, K 5.9, Glucose 54)
    pt_adult_crisis = AdrenalCrisisPatientPresentation(
        age_years=44.0,
        weight_kg=70.0,
        is_adult=True,
        heart_rate_bpm=124,
        systolic_bp_mmhg=76,
        diastolic_bp_mmhg=44,
        baseline_typical_sbp=122,
        temperature_celsius=38.9,
        refractory_to_fluids_and_pressors=True,
        acute_abdominal_pain_vomiting_diarrhea=True,
        profound_weakness_lethargy_delirium=True,
        serum_sodium_meq_l=125.0,
        serum_potassium_meq_l=5.9,
        serum_glucose_mg_dl=54.0,
        baseline_cortisol_ug_dl=1.8,
        baseline_acth_pg_ml=142.0,
        cosyntropin_stimulated_30min_cortisol_ug_dl=2.4,
        cosyntropin_stimulated_60min_cortisol_ug_dl=2.6,
    )

    rep1 = AcuteAdrenalCrisisEngine.run_clinical_assessment(pt_adult_crisis)

    assert rep1.meets_adrenal_crisis_criteria is True, "Must meet adrenal crisis criteria"
    assert rep1.severity_classification == ClinicalCrisisSeverity.REFRACTORY_SHOCK
    assert rep1.hydrocortisone_recommendation.initial_iv_bolus_mg == 100.0
    assert rep1.hydrocortisone_recommendation.daily_total_dose_mg == 200.0
    assert rep1.cosyntropin_analysis is not None
    assert rep1.cosyntropin_analysis.etiology == AdrenalInsufficiencyType.PRIMARY_ADDISONS
    assert "D50W" in rep1.fluid_resuscitation_protocol["hypoglycemia_rescue_protocol"]

    print("[*] Test Case 1 (Adult Refractory Adrenal Shock - Primary Addison's) PASSED")
    print(f"    - Meets Criteria: {rep1.meets_adrenal_crisis_criteria} ({rep1.severity_classification.value})")
    print(f"    - Hydrocortisone Bolus: {rep1.hydrocortisone_recommendation.initial_iv_bolus_mg} mg IV STAT")
    print(f"    - Maintenance: {rep1.hydrocortisone_recommendation.maintenance_schedule}")
    print(f"    - Cosyntropin Interpretation: {rep1.cosyntropin_analysis.interpretation}")
    print(f"    - Hypoglycemia Rescue: {rep1.fluid_resuscitation_protocol['hypoglycemia_rescue_protocol'][:60]}...")

    # Test Case 2: Pediatric Adrenal Crisis (Age 4, 16 kg, Hypoglycemic Lethargy, SBP 68)
    pt_peds_crisis = AdrenalCrisisPatientPresentation(
        age_years=4.0,
        weight_kg=16.0,
        is_adult=False,
        heart_rate_bpm=148,
        systolic_bp_mmhg=68,
        diastolic_bp_mmhg=38,
        baseline_typical_sbp=95,
        temperature_celsius=38.2,
        acute_abdominal_pain_vomiting_diarrhea=True,
        profound_weakness_lethargy_delirium=True,
        serum_sodium_meq_l=128.0,
        serum_potassium_meq_l=5.4,
        serum_glucose_mg_dl=42.0,
        baseline_cortisol_ug_dl=2.1,
    )

    rep2 = AcuteAdrenalCrisisEngine.run_clinical_assessment(pt_peds_crisis)

    assert rep2.meets_adrenal_crisis_criteria is True, "Peds must meet adrenal crisis criteria"
    assert rep2.hydrocortisone_recommendation.initial_iv_bolus_mg == 50.0, "Child age 4 receives 50 mg bolus"
    assert "D10W" in rep2.fluid_resuscitation_protocol["hypoglycemia_rescue_protocol"]

    print("\n[*] Test Case 2 (Pediatric Adrenal Crisis - Age 4, 16 kg) PASSED")
    print(f"    - Recommended Hydrocortisone Bolus: {rep2.hydrocortisone_recommendation.initial_iv_bolus_mg} mg IV")
    print(f"    - Hypoglycemia Rescue: {rep2.fluid_resuscitation_protocol['hypoglycemia_rescue_protocol']}")

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


if __name__ == "__main__":
    verify_clinical_scenarios()

Clinical Safety Sentinels & Practical Prescribing Rules

  1. Never Delay Treatment for Laboratory Results: Mortality from acute adrenal crisis is directly correlated with time to glucocorticoid administration. If adrenal crisis is suspected, administer $100\text{ mg}$ IV hydrocortisone immediately. Diagnostic evaluation can occur after hemodynamic stabilization.
  2. Dexamethasone Zero-Assay Interference Bridge: If an initial cosyntropin stimulation test must be performed before starting high-dose therapy, do not give hydrocortisone or prednisone (both cross-react with cortisol radioimmunoassays). Instead, administer Dexamethasone $4.0\text{ mg}$ IV, which provides potent glucocorticoid receptor activation without altering serum cortisol measurements.
  3. Fludrocortisone Redundancy Sentinel: Stress doses of hydrocortisone ($\ge 50\text{ mg/day}$) fully saturate renal mineralocorticoid receptors ($100\text{ mg}$ hydrocortisone $\approx 0.5\text{ mg}$ fludrocortisone activity). Giving oral fludrocortisone during acute IV hydrocortisone therapy is completely redundant and may provoke volume overload. Delay fludrocortisone until hydrocortisone is tapered below $50\text{ mg/day}$.
  4. Hyperkalemia Treatment Precautions: Hyperkalemia in adrenal crisis is caused by aldosterone deficiency. Standard rapid-acting insulin pushes can cause fatal, refractory hypoglycemia in a patient with cortisol depletion. Volume expansion with normal saline and hydrocortisone alone will normalize potassium within hours. Reserve insulin only for life-threatening electrocardiographic instability (sine wave).

Quality Assurance & Verification