Cookbook 382: Offline Clinical Critical Care & Neuro-ICU Delirium CAM-ICU & ICDSC Assessment Engine, Richmond Agitation-Sedation Scale (RASS) Targeter, Subtype Sieve & Society of Critical Care Medicine (SCCM) PADIS ABCDEF Bundle Protocol

Executive Clinical Overview

ICU Delirium is an acute, fluctuating disturbance of attention, awareness, and baseline cognition reflecting acute organ dysfunction of the central nervous system (acute brain dysfunction / encephalopathy). It affects $60\% - 80\%$ of mechanically ventilated patients and $20\% - 50\%$ of non-ventilated intensive care unit (ICU) admissions. Each additional day spent in delirium independently increases the hazard of 1-year mortality by $10\%$, triples the likelihood of long-term cognitive impairment (resembling moderate-to-severe Alzheimer’s-type dementia at 12 months), and substantially lengthens ICU stay and healthcare expenditures.

Despite authoritative clinical practice guidelines from the Society of Critical Care Medicine (SCCM PADIS), the American College of Critical Care Medicine (ACCM), and the European Society of Intensive Care Medicine (ESICM), severe morbidities persist due to five widespread clinical misconceptions:

  1. The Overlooked Hypoactive Phenotype: Clinicians readily recognize hyperactive delirium (agitation, combative thrashing, extubation attempts), yet hypoactive delirium represents over $60\% - 70\%$ of all ICU cases. Hypoactive patients—quiet, lethargic, passively staring—carry a worse 6-month mortality than hyperactive patients because their profound metabolic and neuroinflammatory distress is misdiagnosed as “appropriate calm” or “oversedation.”
  2. Failure to Gate Assessment by RASS: Attempting to score CAM-ICU in a comatose or deeply sedated patient ($\text{RASS} -4$ or $-5$) is clinically invalid. Delirium screening requires responsiveness to verbal stimuli ($\text{RASS} \ge -3$).
  3. Benzodiazepine-Induced Deliriogenesis: Continuous infusion of benzodiazepines (midazolam, lorazepam) is an established independent, dose-dependent risk factor for transition into persistent delirium. Modern guidelines mandate light sedation targets ($\text{RASS } 0 \text{ to } -1$) using non-benzodiazepine agents (Dexmedetomidine or Propofol).
  4. Antipsychotic Misuse as “Delirium Prophylaxis”: Routine prophylactic administration of haloperidol or second-generation atypical antipsychotics (quetiapine, olanzapine) does not shorten delirium duration or reduce mortality. Antipsychotics are indicated strictly for distressing perceptual disturbances or intractable severe agitation threatening immediate patient safety.
  5. Neglecting Non-Pharmacological Bundles: Multi-component non-pharmacological care—the SCCM ABCDEF Bundle (Pain assessment, Both spontaneous awakening/breathing trials, Choice of sedation, Delirium monitoring, Early mobility, and Family engagement)—reduces delirium days by over $40\% - 50\%$ and ICU mortality by $30\%$.
+---------------------------------------------------------------------------------------------------------+
|                         ICU DELIRIUM ASSESSMENT & ABCDEF RESUSCITATION CASCADE                          |
+---------------------------------------------------------------------------------------------------------+
| 1. LEVEL OF CONSCIOUSNESS & AROUSABILITY GATING (RASS: -5 to +4)                                        |
|    - RASS -5 (Unarousable / No response to physical stimuli) -> STOP: COMA (Cannot assess delirium).    |
|    - RASS -4 (Deep Sedation / Movement but no eye contact to physical stimuli) -> STOP: COMA.           |
|    - RASS -3 to +4 -> ELIGIBLE FOR DELIRIUM ASSESSMENT (Proceed to Step 2).                             |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 2. CAM-ICU TWO-STEP DIAGNOSTIC DECISION ENGINE                                                          |
|    - FEATURE 1: Acute Onset or Fluctuating Course (Baseline mental status change in last 24 hours).     |
|      * If Absent -> CAM-ICU NEGATIVE.                                                                   |
|      * If Present -> Proceed to Feature 2.                                                              |
|    - FEATURE 2: Inattention (SAVEAHAART auditory letters or picture recognition; <= 7/10 correct = POS).|
|      * If < 3 errors (> 7 correct) -> CAM-ICU NEGATIVE.                                                 |
|      * If >= 3 errors (<= 7 correct) -> ATTENTION IMPAIRED (Proceed to Features 3 & 4).                |
|    - FEATURE 3: Altered Level of Consciousness (Current RASS is anything other than 0 Alert/Calm).     |
|      * If RASS != 0 -> DELIRIUM POSITIVE! (Meets Features 1 + 2 + 3).                                   |
|      * If RASS == 0 -> Proceed to Feature 4.                                                            |
|    - FEATURE 4: Disorganized Thinking (4 logic questions + 1 command; > 1 error = POSITIVE).            |
|      * If > 1 error -> DELIRIUM POSITIVE! (Meets Features 1 + 2 + 4).                                   |
|      * If <= 1 error -> CAM-ICU NEGATIVE.                                                               |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 3. PHENOTYPE SIEVE: CLINICAL SUBTYPE DIFFERENTIATION                                                    |
|    - HYPERACTIVE (RASS +1 to +4): Agitated, restless, pulling at lines, combative.                      |
|    - HYPOACTIVE (RASS -3 to -1): Lethargic, flat affect, delayed response, motionless. (HIGH MORTALITY)|
|    - MIXED (Fluctuates between positive and negative RASS scores across 24h shifts).                    |
+---------------------------------------------------------------------------------------------------------+
                                                     |
                                                     v
+---------------------------------------------------------------------------------------------------------+
| 4. SCCM PADIS ABCDEF INTERVENTION BUNDLE & PHARMACOLOGICAL SENTINELS                                     |
|    - A: Assess, Prevent, and Manage Pain (CPOT / BPS scores <= 2; multimodal non-opioid analgesia).     |
|    - B: Both SAT (Spontaneous Awakening) & SBT (Spontaneous Breathing) daily paired coordination.       |
|    - C: Choice of Sedation: TARGET LIGHT SEDATION (RASS 0 to -1); Dexmedetomidine preferred.            |
|      * BENZODIAZEPINE GUARDRAIL: Prohibit midazolam/lorazepam infusions unless treating ETOH withdrawal. |
|    - D: Delirium Monitoring, Cause Identification (THINK mnemonic: Toxic, Hypoxemia, Infection, etc.)   |
|    - E: Early Mobility & Exercise: Passive ROM -> Sitting -> Standing -> Ambulation.                   |
|    - F: Family Engagement & Reorientation: Consistent clocks, natural light, eyeglasses, hearing aids.  |
|    - Pharmacotherapy Sentinels: Haloperidol/Atypicals for safety ONLY; monitor QTc (Hold if > 500 ms). |
+---------------------------------------------------------------------------------------------------------+

Richmond Agitation-Sedation Scale (RASS) Scoring Framework

The Richmond Agitation-Sedation Scale (RASS) is the universally validated 10-point scale ($+4$ to $-5$) for quantifying level of consciousness and target sedation in adult intensive care:

Score Term Clinical Description Assessment Criteria
+4 Combative Overtly combative, violent, immediate danger to staff Observed without stimulation
+3 Very Agitated Pulls or removes tubes/catheters; aggressive behavior Observed without stimulation
+2 Agitated Frequent non-purposeful movement; fights ventilator Observed without stimulation
+1 Restless Anxious, apprehensive, but movements not vigorous Observed without stimulation
0 Alert and Calm Normal resting alertness and cooperative behavior Observed without stimulation
-1 Drowsy Not fully alert, but sustained eye opening/contact to voice Eye contact $\ge 10\text{ seconds}$
-2 Light Sedation Briefly awakens with eye contact to verbal voice Eye contact $< 10\text{ seconds}$
-3 Moderate Sedation Movement or eye opening to voice, but no eye contact Any movement without eye contact
-4 Deep Sedation No response to voice, but movement to physical stimulation Physical/painful stimulation
-5 Unarousable No response to voice or physical stimulation Physical/painful stimulation
\[\text{CAM-ICU Evaluability} = \begin{cases} \text{Coma (Ineligible for Delirium Testing)}, & \text{RASS } \le -4 \\ \text{Assessable for Delirium}, & -3 \le \text{RASS} \le +4 \end{cases}\]

Confusion Assessment Method for the ICU (CAM-ICU) Algorithm

\[\text{CAM-ICU Status} = \begin{cases} \text{POSITIVE (Delirium Present)}, & \text{Feature 1 (Acute/Fluctuating)} \land \text{Feature 2 (Inattention)} \land [\text{Feature 3 (RASS} \ne 0) \lor \text{Feature 4 (Disorganized)}] \\ \text{NEGATIVE (No Delirium)}, & \text{Otherwise} \end{cases}\]

Feature 2: Inattention Testing (Letters Screening)

Feature 4: Disorganized Thinking (4 Logic Questions + 1 Command)

  1. “Will a stone float on water?” (Correct: No)
  2. “Are there fish in the sea?” (Correct: Yes)
  3. “Does one pound weigh more than two pounds?” (Correct: No)
  4. “Can you use a hammer to pound a nail?” (Correct: Yes)
  5. Command: “Hold up this many fingers” (examiner holds up 2 fingers) -> “Now do the same with the other hand” (without adding fingers).

Production Python Implementation

The following complete, zero-dependency Python clinical decision-support engine provides automated RASS validation, CAM-ICU diagnostic gating, ICDSC multi-item scoring, delirium subtyping, QTc pharmaco-sentinels, and ABCDEF bundle operationalization.

#!/usr/bin/env python3
"""
OpenPHR Cookbook 382: Offline Clinical Critical Care & Neuro-ICU Engine
ICU Delirium CAM-ICU & ICDSC Assessment, RASS Consciousness Gater,
Subtype Sieve & SCCM PADIS ABCDEF Bundle 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 RASSTerm(Enum):
    COMBATIVE = "+4: Combative (Violent, immediate danger to staff)"
    VERY_AGITATED = "+3: Very Agitated (Pulls or removes lines/tubes)"
    AGITATED = "+2: Agitated (Frequent non-purposeful movement, fights ventilator)"
    RESTLESS = "+1: Restless (Anxious, apprehensive, movements not aggressive)"
    ALERT_CALM = "0: Alert and Calm (Spontaneously attentive, cooperative)"
    DROWSY = "-1: Drowsy (Sustained eye contact >= 10 seconds to voice)"
    LIGHT_SEDATION = "-2: Light Sedation (Brief eye contact < 10 seconds to voice)"
    MODERATE_SEDATION = "-3: Moderate Sedation (Movement/eye opening, but no eye contact)"
    DEEP_SEDATION = "-4: Deep Sedation (No voice response, movement to physical stimulation only)"
    UNAROUSABLE = "-5: Unarousable (No response to voice or physical stimulation)"


class DeliriumClinicalSubtype(Enum):
    HYPERACTIVE = "Hyperactive Delirium (Agitated, combative, hyper-vigilant, pulling at catheters)"
    HYPOACTIVE = "Hypoactive Delirium (Quiet, lethargic, withdrawn, decreased responsiveness - High Mortality)"
    MIXED = "Mixed Delirium (Fluctuates between hypoactive and hyperactive phases over 24 hours)"
    NOT_DELIRIOUS = "Not Delirious (CAM-ICU / ICDSC Negative)"
    UNASSESSABLE_COMA = "Unassessable / Coma (RASS -4 or -5 prohibits cognitive evaluation)"


@dataclass
class DeliriumPatientPresentation:
    # Patient demographics
    age_years: float
    weight_kg: float
    is_adult: bool
    is_mechanically_ventilated: bool = True
    # Consciousness & RASS
    rass_score: int = 0  # -5 to +4
    rass_fluctuated_last_24h: bool = False
    rass_prior_shift_score: Optional[int] = None
    # Feature 1: Acute Onset or Mental Status Fluctuation
    acute_change_from_baseline_mental_status: bool = True
    # Feature 2: Inattention (Letter task: SAVEAHAART)
    letter_test_errors_count: int = 0  # Errors out of 10 letters (>=3 errors = positive)
    # Feature 4: Disorganized Thinking (4 questions + 1 command)
    disorganized_thinking_errors_count: int = 0  # >1 error = positive
    # ICDSC 8-item checklist inputs (for complementary validation)
    icdsc_inattention: bool = False
    icdsc_disorientation: bool = False
    icdsc_hallucinations_delusions: bool = False
    icdsc_psychomotor_agitation_retardation: bool = False
    icdsc_inappropriate_speech_mood: bool = False
    icdsc_sleep_wake_cycle_disturbance: bool = False
    icdsc_symptom_fluctuation: bool = False
    # Clinical and pharmacological context
    receiving_benzodiazepine_infusion: bool = False  # e.g., Midazolam, Lorazepam
    receiving_dexmedetomidine: bool = False
    receiving_propofol: bool = False
    receiving_antipsychotic: bool = False  # e.g., Haloperidol, Quetiapine
    baseline_qtc_ms: float = 440.0
    serum_potassium_meq_l: float = 4.0
    serum_magnesium_mg_dl: float = 2.1
    history_of_alcohol_use_disorder: bool = False


@dataclass
class CAMICUResult:
    is_evaluable: bool
    is_delirious: bool
    feature_1_acute_fluctuation: bool
    feature_2_inattention_positive: bool
    feature_3_altered_consciousness: bool
    feature_4_disorganized_thinking_positive: bool
    diagnostic_rationale: str


@dataclass
class ICDSCResult:
    total_score: int
    is_delirious: bool
    is_subsyndromal: bool
    interpretation: str


@dataclass
class DeliriumDecisionReport:
    cam_icu_evaluation: CAMICUResult
    icdsc_evaluation: ICDSCResult
    clinical_subtype: DeliriumClinicalSubtype
    rass_classification: RASSTerm
    abcdef_bundle_recommendations: Dict[str, str]
    benzodiazepine_guardrail: Dict[str, str]
    antipsychotic_and_qtc_sentinel: Dict[str, Union[str, float, bool]]
    modifiable_risk_factor_sieve: List[str]


class AcuteDeliriumEngine:
    """
    Clinical Decision Support Engine for ICU Delirium CAM-ICU Evaluation,
    RASS Consciousness Gating, Subtype Classification, and ABCDEF Bundle Protocol.
    """

    @staticmethod
    def classify_rass(score: int) -> RASSTerm:
        """Classifies numerical RASS (-5 to +4) into clinical enum."""
        mapping = {
            4: RASSTerm.COMBATIVE,
            3: RASSTerm.VERY_AGITATED,
            2: RASSTerm.AGITATED,
            1: RASSTerm.RESTLESS,
            0: RASSTerm.ALERT_CALM,
            -1: RASSTerm.DROWSY,
            -2: RASSTerm.LIGHT_SEDATION,
            -3: RASSTerm.MODERATE_SEDATION,
            -4: RASSTerm.DEEP_SEDATION,
            -5: RASSTerm.UNAROUSABLE,
        }
        return mapping.get(max(-5, min(4, score)), RASSTerm.ALERT_CALM)

    @classmethod
    def evaluate_cam_icu(cls, p: DeliriumPatientPresentation) -> CAMICUResult:
        """
        Evaluates Confusion Assessment Method for the ICU (CAM-ICU):
        Pre-requisite: RASS >= -3 (if RASS is -4 or -5, patient is comatose / unassessable).
        Positive CAM-ICU requires:
        - Feature 1 (Acute Onset or Fluctuating Course) AND
        - Feature 2 (Inattention: >= 3 errors on SAVEAHAART) AND
        - EITHER Feature 3 (Altered LOC: RASS != 0) OR Feature 4 (Disorganized Thinking: > 1 error).
        """
        if p.rass_score <= -4:
            return CAMICUResult(
                is_evaluable=False,
                is_delirious=False,
                feature_1_acute_fluctuation=False,
                feature_2_inattention_positive=False,
                feature_3_altered_consciousness=False,
                feature_4_disorganized_thinking_positive=False,
                diagnostic_rationale=(
                    f"Patient is in deep sedation / coma (RASS {p.rass_score}). "
                    "CAM-ICU cannot be evaluated. Screen again when patient awakens to RASS >= -3."
                ),
            )

        f1 = p.acute_change_from_baseline_mental_status or p.rass_fluctuated_last_24h
        f2 = p.letter_test_errors_count >= 3
        f3 = p.rass_score != 0
        f4 = p.disorganized_thinking_errors_count > 1

        is_delirious = f1 and f2 and (f3 or f4)

        if is_delirious:
            features_met = ["Feature 1 (Acute/Fluctuating)", "Feature 2 (Inattention)"]
            if f3:
                features_met.append(f"Feature 3 (Altered LOC: RASS {p.rass_score})")
            if f4:
                features_met.append(f"Feature 4 (Disorganized Thinking: {p.disorganized_thinking_errors_count} errors)")
            rationale = (
                f"CAM-ICU POSITIVE for ICU Delirium. Criteria met: {', '.join(features_met)}."
            )
        else:
            reasons = []
            if not f1:
                reasons.append("No acute onset or fluctuation (Feature 1 negative)")
            if not f2:
                reasons.append(f"Intact attention with only {p.letter_test_errors_count} errors (Feature 2 negative)")
            if not (f3 or f4):
                reasons.append("Alert/Calm (RASS 0) with organized thinking (Features 3 and 4 negative)")
            rationale = f"CAM-ICU NEGATIVE: {'; '.join(reasons)}."

        return CAMICUResult(
            is_evaluable=True,
            is_delirious=is_delirious,
            feature_1_acute_fluctuation=f1,
            feature_2_inattention_positive=f2,
            feature_3_altered_consciousness=f3,
            feature_4_disorganized_thinking_positive=f4,
            diagnostic_rationale=rationale,
        )

    @classmethod
    def evaluate_icdsc(cls, p: DeliriumPatientPresentation) -> ICDSCResult:
        """
        Evaluates the Intensive Care Delirium Screening Checklist (ICDSC, 0-8 points):
        Score 0: Normal
        Score 1-3: Subsyndromal Delirium
        Score >= 4: Clinical Delirium (High sensitivity across shifts)
        """
        if p.rass_score <= -4:
            return ICDSCResult(
                total_score=0,
                is_delirious=False,
                is_subsyndromal=False,
                interpretation="Unassessable due to deep sedation or coma (RASS -4 or -5).",
            )

        score = 0
        # Item 1: Altered level of consciousness (RASS != 0)
        if p.rass_score != 0:
            score += 1
        # Item 2: Inattention
        if p.icdsc_inattention or p.letter_test_errors_count >= 3:
            score += 1
        # Item 3: Disorientation
        if p.icdsc_disorientation or p.disorganized_thinking_errors_count > 1:
            score += 1
        # Item 4: Hallucinations / delusions
        if p.icdsc_hallucinations_delusions:
            score += 1
        # Item 5: Psychomotor agitation or retardation
        if p.icdsc_psychomotor_agitation_retardation or p.rass_score != 0:
            score += 1
        # Item 6: Inappropriate speech or mood
        if p.icdsc_inappropriate_speech_mood:
            score += 1
        # Item 7: Sleep-wake cycle disturbance
        if p.icdsc_sleep_wake_cycle_disturbance:
            score += 1
        # Item 8: Symptom fluctuation
        if p.icdsc_symptom_fluctuation or p.rass_fluctuated_last_24h:
            score += 1

        is_delirious = score >= 4
        is_subsyndromal = 1 <= score <= 3

        if is_delirious:
            interp = f"ICDSC Score: {score}/8 -> POSITIVE FOR CLINICAL DELIRIUM (Score >= 4)."
        elif is_subsyndromal:
            interp = f"ICDSC Score: {score}/8 -> SUBSYNDROMAL DELIRIUM (Score 1-3). High risk of progression."
        else:
            interp = f"ICDSC Score: {score}/8 -> Normal cognitive assessment."

        return ICDSCResult(
            total_score=score,
            is_delirious=is_delirious,
            is_subsyndromal=is_subsyndromal,
            interpretation=interp,
        )

    @staticmethod
    def identify_clinical_subtype(
        cam_result: CAMICUResult,
        rass: int,
        prior_shift_rass: Optional[int],
    ) -> DeliriumClinicalSubtype:
        """
        Differentiates delirium into Hyperactive, Hypoactive, or Mixed subtypes.
        """
        if not cam_result.is_evaluable:
            return DeliriumClinicalSubtype.UNASSESSABLE_COMA

        if not cam_result.is_delirious:
            return DeliriumClinicalSubtype.NOT_DELIRIOUS

        # Check for mixed subtype: fluctuation across positive and negative RASS scores
        if prior_shift_rass is not None:
            if (rass > 0 and prior_shift_rass < 0) or (rass < 0 and prior_shift_rass > 0):
                return DeliriumClinicalSubtype.MIXED

        if rass > 0:
            return DeliriumClinicalSubtype.HYPERACTIVE
        elif rass < 0:
            return DeliriumClinicalSubtype.HYPOACTIVE
        else:
            # RASS 0 with delirium is almost always hypoactive/inattentive
            return DeliriumClinicalSubtype.HYPOACTIVE

    @staticmethod
    def generate_abcdef_bundle_plan(
        is_ventilated: bool, rass: int, subtype: DeliriumClinicalSubtype
    ) -> Dict[str, str]:
        """
        Operationalizes the SCCM PADIS ABCDEF bundle for delirium prevention and management.
        """
        return {
            "A_Assess_Prevent_Manage_Pain": (
                "Assess pain every 2-4 hours using validated scales (CPOT for intubated, BPS, or NRS). "
                "Target CPOT <= 2. Prioritize multimodal analgesia (Acetaminophen, topical lidocaine, "
                "gabapentinoids) to minimize systemic opioid consumption."
            ),
            "B_Both_SAT_and_SBT": (
                "Conduct daily paired Spontaneous Awakening Trial (SAT - stop continuous sedatives) "
                "and Spontaneous Breathing Trial (SBT). Pairing SAT with SBT significantly reduces "
                "ventilator days and delirium duration."
                if is_ventilated
                else "Not applicable (Patient not mechanically ventilated). Maintain spontaneous interaction."
            ),
            "C_Choice_of_Sedation": (
                "TARGET LIGHT SEDATION (RASS 0 to -1). Prefer Dexmedetomidine (Precedex) over GABAergic "
                "sedatives. Dexmedetomidine preserves cognitive arousal, promotes natural sleep architecture, "
                "and shortens time to extubation."
            ),
            "D_Delirium_Assessment_and_THINK": (
                "Screen with CAM-ICU every shift. Investigate secondary etiologies using the THINK mnemonic: "
                "Toxic (medications, anticholinergics), Hypoxemia/Hypercapnia, Infection/Sepsis, "
                "Non-homeostatic (electrolytes, metabolic), Kidney/Liver organ failure."
            ),
            "E_Early_Mobility_and_Exercise": (
                "Initiate daily progressive mobility protocol: Passive range of motion -> Active resistance -> "
                "Dangling at bedside edge -> Chair transfer -> Standing and assisted ambulation. "
                "Physical rehab significantly decreases delirium incidence."
            ),
            "F_Family_Engagement_and_Empowerment": (
                "Promote structured family visits, daily reorientation protocols (clocks, calendar, whiteboards), "
                "natural circadian light exposure (open blinds at 08:00, dim lights at 21:00), and ensure "
                "patient has personal eyeglasses and functioning hearing aids."
            ),
        }

    @staticmethod
    def evaluate_benzodiazepine_guardrail(
        on_benzo: bool, alcohol_withdrawal: bool
    ) -> Dict[str, str]:
        """
        Enforces strict safety guardrails regarding benzodiazepine deliriogenesis.
        """
        if on_benzo:
            if alcohol_withdrawal:
                return {
                    "sentinel_status": "EXCEPTION PERMITTED (Alcohol Withdrawal / CIWA)",
                    "clinical_rule": (
                        "Benzodiazepines are strictly indicated for severe alcohol withdrawal syndrome or status epilepticus. "
                        "Titrate using symptom-triggered CIWA-Ar / RASS targets rather than fixed continuous infusions."
                    ),
                }
            else:
                return {
                    "sentinel_status": "CRITICAL DELIRIOGENIC GUARDRAIL TRIGGERED",
                    "clinical_rule": (
                        "STOP OR WEAN BENZODIAZEPINE CONTINUOUS INFUSION IMMEDIATELY. "
                        "SCCM PADIS guidelines designate continuous benzodiazepine infusions as a major independent "
                        "risk factor for transition to delirium. Transition to Dexmedetomidine or low-dose Propofol."
                    ),
                }

        return {
            "sentinel_status": "COMPLIANT",
            "clinical_rule": "Patient is not receiving deliriogenic benzodiazepine infusions.",
        }

    @staticmethod
    def evaluate_antipsychotic_and_qtc(
        p: DeliriumPatientPresentation,
    ) -> Dict[str, Union[str, float, bool]]:
        """
        Enforces pharmaco-safety sentinels for Haloperidol / Atypical Antipsychotic therapy.
        """
        qtc = p.baseline_qtc_ms
        qtc_prolonged = qtc > 500.0

        if qtc_prolonged:
            guidance = (
                f"STOP / CONTRAINDICATED: Baseline QTc is severely prolonged ({qtc} ms > 500 ms). "
                "Haloperidol and atypical antipsychotics (Quetiapine, Olanzapine, Ziprasidone) are strictly "
                "CONTRAINDICATED due to high risk of drug-induced Torsades de Pointes and ventricular fibrillation. "
                "Rely strictly on non-pharmacological ABCDEF interventions and Dexmedetomidine."
            )
        else:
            guidance = (
                f"Baseline QTc is acceptable ({qtc} ms <= 500 ms). If severe hyperactive agitation threatens "
                "immediate safety (extubation, line removal), low-dose Haloperidol (0.5 - 2.5 mg IV) or "
                "Quetiapine (12.5 - 25 mg PO q12h) may be used short-term. Routine prophylactic use is contraindicated."
            )

        electrolyte_note = (
            f"Electrolytes: Potassium {p.serum_potassium_meq_l} mEq/L, Magnesium {p.serum_magnesium_mg_dl} mg/dL. "
            + (
                "Replete Potassium >= 4.0 and Magnesium >= 2.0 before considering any QT-prolonging agent."
                if p.serum_potassium_meq_l < 4.0 or p.serum_magnesium_mg_dl < 2.0
                else "Electrolytes are optimized for arrhythmia safety."
            )
        )

        return {
            "baseline_qtc_ms": qtc,
            "is_qtc_prolonged": qtc_prolonged,
            "safety_recommendation": guidance,
            "electrolyte_stabilization": electrolyte_note,
        }

    @classmethod
    def run_clinical_assessment(
        cls, p: DeliriumPatientPresentation
    ) -> DeliriumDecisionReport:
        """
        Runs the comprehensive end-to-end ICU delirium assessment.
        """
        cam = cls.evaluate_cam_icu(p)
        icdsc = cls.evaluate_icdsc(p)
        rass_class = cls.classify_rass(p.rass_score)
        subtype = cls.identify_clinical_subtype(cam, p.rass_score, p.rass_prior_shift_score)
        bundle = cls.generate_abcdef_bundle_plan(p.is_mechanically_ventilated, p.rass_score, subtype)
        benzo_guard = cls.evaluate_benzodiazepine_guardrail(
            p.receiving_benzodiazepine_infusion, p.history_of_alcohol_use_disorder
        )
        qtc_sentinel = cls.evaluate_antipsychotic_and_qtc(p)

        risk_factors = []
        if p.receiving_benzodiazepine_infusion and not p.history_of_alcohol_use_disorder:
            risk_factors.append("Benzodiazepine continuous infusion")
        if p.is_mechanically_ventilated:
            risk_factors.append("Invasive mechanical ventilation")
        if p.age_years >= 65:
            risk_factors.append(f"Advanced age ({p.age_years} years)")
        if p.serum_potassium_meq_l < 3.5:
            risk_factors.append("Hypokalemia")

        return DeliriumDecisionReport(
            cam_icu_evaluation=cam,
            icdsc_evaluation=icdsc,
            clinical_subtype=subtype,
            rass_classification=rass_class,
            abcdef_bundle_recommendations=bundle,
            benzodiazepine_guardrail=benzo_guard,
            antipsychotic_and_qtc_sentinel=qtc_sentinel,
            modifiable_risk_factor_sieve=risk_factors,
        )


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

def verify_clinical_scenarios():
    print("=" * 80)
    print("OpenPHR Cookbook 382: ICU Delirium CAM-ICU, RASS & ABCDEF Bundle Suite")
    print("=" * 80)

    # Test Case 1: Quiet Hypoactive Delirium in Mechanically Ventilated Patient (RASS -2, Letter Errors 4)
    pt_hypoactive = DeliriumPatientPresentation(
        age_years=68.0,
        weight_kg=74.0,
        is_adult=True,
        is_mechanically_ventilated=True,
        rass_score=-2,  # Light sedation / drowsy
        acute_change_from_baseline_mental_status=True,
        letter_test_errors_count=4,  # Fails inattention
        disorganized_thinking_errors_count=2,
        receiving_benzodiazepine_infusion=True,  # Midazolam infusion running
        baseline_qtc_ms=440.0,
    )

    rep1 = AcuteDeliriumEngine.run_clinical_assessment(pt_hypoactive)

    assert rep1.cam_icu_evaluation.is_evaluable is True, "Must be evaluable with RASS -2"
    assert rep1.cam_icu_evaluation.is_delirious is True, "Must be CAM-ICU positive"
    assert rep1.clinical_subtype == DeliriumClinicalSubtype.HYPOACTIVE, "Negative RASS delirium is hypoactive"
    assert "CRITICAL DELIRIOGENIC GUARDRAIL" in rep1.benzodiazepine_guardrail["sentinel_status"]

    print("[*] Test Case 1 (Mechanically Ventilated Hypoactive Delirium - RASS -2) PASSED")
    print(f"    - CAM-ICU Evaluation: {rep1.cam_icu_evaluation.diagnostic_rationale}")
    print(f"    - Delirium Subtype: {rep1.clinical_subtype.value}")
    print(f"    - Benzo Guardrail: {rep1.benzodiazepine_guardrail['clinical_rule'][:65]}...")
    print(f"    - ABCDEF Choice of Sedation: {rep1.abcdef_bundle_recommendations['C_Choice_of_Sedation'][:65]}...")

    # Test Case 2: Deep Sedation / Coma Gating (RASS -4 -> Unassessable)
    pt_coma = DeliriumPatientPresentation(
        age_years=55.0,
        weight_kg=80.0,
        is_adult=True,
        rass_score=-4,  # Deep sedation
    )

    rep2 = AcuteDeliriumEngine.run_clinical_assessment(pt_coma)

    assert rep2.cam_icu_evaluation.is_evaluable is False, "RASS -4 must be unassessable"
    assert rep2.clinical_subtype == DeliriumClinicalSubtype.UNASSESSABLE_COMA

    print("\n[*] Test Case 2 (Deep Sedation RASS -4 Coma Gating) PASSED")
    print(f"    - Evaluable: {rep2.cam_icu_evaluation.is_evaluable} ({rep2.cam_icu_evaluation.diagnostic_rationale})")

    # Test Case 3: Hyperactive Agitation with Prolonged QTc (RASS +2, QTc 530 ms)
    pt_hyperactive = DeliriumPatientPresentation(
        age_years=72.0,
        weight_kg=65.0,
        is_adult=True,
        rass_score=2,  # Agitated
        acute_change_from_baseline_mental_status=True,
        letter_test_errors_count=5,
        disorganized_thinking_errors_count=3,
        baseline_qtc_ms=530.0,  # Prolonged QTc
    )

    rep3 = AcuteDeliriumEngine.run_clinical_assessment(pt_hyperactive)

    assert rep3.clinical_subtype == DeliriumClinicalSubtype.HYPERACTIVE
    assert rep3.antipsychotic_and_qtc_sentinel["is_qtc_prolonged"] is True
    assert "CONTRAINDICATED" in str(rep3.antipsychotic_and_qtc_sentinel["safety_recommendation"])

    print("\n[*] Test Case 3 (Hyperactive Delirium with QTc Prolongation 530 ms) PASSED")
    print(f"    - Subtype: {rep3.clinical_subtype.value}")
    print(f"    - QTc Safety Sentinel: {rep3.antipsychotic_and_qtc_sentinel['safety_recommendation'][:75]}...")

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


if __name__ == "__main__":
    verify_clinical_scenarios()

Clinical Safety Sentinels & Practical Prescribing Rules

  1. RASS Consciousness Gating Rule: Never attempt cognitive testing in a deeply sedated or comatose patient ($ ext{RASS } -4$ or $-5$). Delirium is defined by acute inattention, which requires a minimally arousable state ($ ext{RASS } \ge -3$).
  2. The Benzodiazepine Deliriogenic Trap: Continuous infusions of midazolam or lorazepam increase the transition probability to delirium by over $300\%$. In mechanically ventilated patients, convert sedation to Dexmedetomidine (Precedex) or low-dose Propofol, preserving benzodiazepines strictly for status epilepticus or severe alcohol withdrawal.
  3. Hypoactive Delirium Vigilance: Over $60\%$ of ICU delirium is hypoactive. Because hypoactive patients do not disrupt ward care, their cognitive failure is frequently missed, delaying search for occult sepsis, intracranial catastrophe, or metabolic decompensation. Daily structured CAM-ICU screening is mandatory.
  4. Antipsychotic QTc Guardrails: Haloperidol, Quetiapine, and other dopamine antagonists prolong the cardiac QTc interval. Obtain a baseline 12-lead ECG; if $ ext{QTc} > 500 ext{ ms}$, haloperidol is strictly contraindicated due to lethal risk of drug-induced Torsades de Pointes. Maintain serum potassium $\ge 4.0 ext{ mEq/L}$ and magnesium $\ge 2.0 ext{ mg/dL}$.

Quality Assurance & Verification