You are an elite physician-educator system operating at the level of: - senior pathology professor - consultant physician - academic surgeon - ICU intensivist - radiologist - pharmacologist - medical illustrator - visual memory scientist - USMLE examiner - clinical reasoning expert Your task is to transform the uploaded medical material into CINEMATIC, ULTRA-HIGH-YIELD, VISUALLY MEMORABLE, CLINICALLY INTELLIGENT notes. The output must NOT feel like ordinary textbook notes. It must feel like: - a premium medical atlas - consultant ward teaching - pathology storytelling - modern visual learning system - memory-engineered medical education ======================================== CORE LEARNING PHILOSOPHY ======================================== Teach for: - deep conceptual understanding - long-term retention - visual imagination - clinical reasoning - ward applicability - exam excellence Avoid: - giant paragraphs - robotic textbook summaries - vague explanations - information dumping Explain EVERYTHING with reasoning. Always answer: - What is happening? - Why is it happening? - What does it cause? - How does it present clinically? - Why do investigations change? - Why does treatment work? ======================================== WRITING STYLE ======================================== Use: - elegant hierarchy - visually clean formatting - strong headings/subheadings - flowcharts - arrows - tables - layered bullets - high-yield memory hooks - concise but deep explanations The notes should feel cinematic and visually structured. ======================================== FOR EVERY TOPIC INCLUDE: ======================================== # 1. BIG PICTURE OVERVIEW Start with: - what this disease/topic is - why it matters clinically - the central concept in simple language - why students commonly misunderstand it Then explain: - the fundamental pathology - how the disease evolves ======================================== # 2. CINEMATIC VISUALIZATION Turn pathology into vivid mental imagery. Examples: - “Imagine alveoli slowly drowning in inflammatory fluid…” - “The pancreas begins digesting itself…” - “Protein leaks through the kidney like a damaged sieve…” Make the learner SEE the disease. ======================================== # 3. PATHOPHYSIOLOGY FLOWCHAIN Always create: CAUSE ↓ MECHANISM ↓ STRUCTURAL CHANGE ↓ PHYSIOLOGICAL EFFECT ↓ CLINICAL FEATURES ↓ COMPLICATIONS Use arrows extensively. ======================================== # 4. CLINICAL REASONING Teach like a consultant during ward rounds. Explain: - why symptoms occur - why signs appear - why labs change - why imaging findings occur - why complications happen - why treatment works Focus heavily on reasoning. ======================================== # 5. HIGH-YIELD TABLES Generate: - comparison tables - differentiating features - hallmark findings - investigation patterns - emergency clues - drug summaries - clinical pearls ======================================== # 6. MEMORY ENGINEERING For every major topic include: - mnemonics - visual anchors - rapid recall tricks - pattern-recognition clues - “must never miss” - “exam trap” - “commonly confused with” ======================================== # 7. INVESTIGATIONS Explain: - why investigations are ordered - why values change - interpretation logic - diagnostic patterns - imaging reasoning - ABG interpretation where relevant Do NOT simply list tests. ======================================== # 8. TREATMENT LOGIC Explain: - why each treatment is used - mechanism of action - when NOT to use it - emergency management - escalation approach - ward practicality ======================================== # 9. PHARMACOLOGY INTEGRATION For important drugs include: - mechanism - indications - contraindications - side effects - interactions - important clinical pearls - practical ward usage ======================================== # 10. SURGERY + RADIOLOGY INTEGRATION Where relevant include: - operative indications - surgical complications - perioperative reasoning - hallmark imaging findings - interpretation tips - radiological clues ======================================== # 11. EXAMINATION FOCUS At the end include: - top viva questions - top MCQ traps - most important concepts - rapid revision bullets - “if you remember only 5 things” ======================================== # 12. OUTPUT FORMAT Generate in this order: 1. Big Picture Summary 2. Core Mechanism 3. Cinematic Visualization 4. Pathophysiology Flowchart 5. Clinical Features 6. Differential Diagnosis 7. Investigations 8. Treatment Logic 9. Pharmacology Integration 10. Surgical/Radiology Correlation 11. Complications 12. Memory Anchors 13. Exam Pearls 14. Rapid Revision Sheet 15. One-Page Ultra High Yield Summary ======================================== FINAL STYLE REQUIREMENTS ======================================== The final notes must feel like: - Robbins + Harrison + Bailey & Love combined - cinematic medical storytelling - premium digital medical education - highly visual - consultant-level teaching - memory optimized - clinically intelligent - extremely high yield Optimize for: - MBBS - USMLE - ward rotations - viva exams - rapid revision - conceptual mastery Topic is "Chest X-ray"

Reading File
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Finding Sources
Finding Sources
Reading File
Loading Image
Here is your complete cinematic, ultra-high-yield CXR atlas. Here is what was built and why each section matters:

What Was Delivered

13 fully integrated sections, sourced directly from Grainger & Allison's Diagnostic Radiology, Goldman-Cecil Medicine, Rosen's Emergency Medicine, Bailey & Love's Surgery, and Roberts & Hedges' Clinical Procedures - synthesized into a single premium learning experience:
SectionWhat It Does For You
Physics of ShadowBuilds the conceptual foundation - you stop guessing and start reasoning
A-B-C-D-E-F-G-H SystemA locked-in systematic method you will use for life, never miss a finding again
5 Core PatternsConsolidation, Collapse, Effusion, Pneumothorax, Oedema - each with cinematic visualization, pathophysiology, and distinguishing features
Shift LogicThe single most tested concept - toward vs away vs no shift, with reasoning
Silhouette SignTaught with clinical application, not just definition
Trauma IntegrationBailey & Love's data on chest injuries, including the dangerous supine haemothorax/pneumothorax confusion
Tubes & LinesPatient safety section with exact normal positions
Specific ConditionsTB, Lung Cancer, COPD, Sarcoidosis - each with complete CXR staging
10 MCQ TrapsThe exact scenarios where marks are lost in exams
Visual Anchor Table12 classic cardiac silhouettes and pathological signs with memory images
One-Page SummaryComplete revision atlas in a single boxed table
The real CXR image from Grainger & Allison showing pleural effusion with CT correlation is embedded at the top of the pleural effusion section for visual reinforcement.

Generate a comparison table (Excel) of common CXR findings in ICU emergencies with decision trees

Reading File
Reading File
Running Command

ls -la /home/daytona/workspace/ && ls /home/daytona/skills/xlsx/

Running Command

mkdir -p /home/daytona/workspace/icu-cxr && ls /home/daytona/skills/xlsx/scripts/

Writing File

~/icu-cxr/build_cxr_excel.py

"""
ICU Emergency CXR Findings - Comparison Table + Decision Trees
Ultra High-Yield Excel workbook for clinical use
"""

from openpyxl import Workbook
from openpyxl.styles import (
    Font, PatternFill, Alignment, Border, Side, GradientFill
)
from openpyxl.utils import get_column_letter
from openpyxl.styles.numbers import FORMAT_TEXT

# ─── COLOUR PALETTE ────────────────────────────────────────────────────────────
C_NAVY       = "1B3A5C"   # deep navy header background
C_DARK_RED   = "8B0000"   # emergency / critical red
C_CRIMSON    = "C0392B"   # red accent
C_ORANGE     = "E67E22"   # caution orange
C_AMBER      = "F39C12"   # amber / warning
C_GREEN      = "1E8449"   # normal / safe green
C_TEAL       = "117A65"   # teal for decision steps
C_PURPLE     = "6C3483"   # purple for differentials
C_BLUE       = "1A5276"   # blue for investigations
C_LGRAY      = "F2F3F4"   # light grey row alternating
C_WHITE      = "FFFFFF"
C_YELLOW_HI  = "FFF9C4"   # soft yellow highlight
C_PINK       = "FADBD8"   # mild pink for critical rows
C_LTBLUE     = "D6EAF8"   # light blue for info rows
C_LTGREEN    = "D5F5E3"   # light green for safe rows
C_LTORANGE   = "FDEBD0"   # light orange
C_LTPURPLE   = "E8DAEF"

def _font(name="Arial", size=10, bold=False, italic=False, color="000000"):
    return Font(name=name, size=size, bold=bold, italic=italic, color=color)

def _fill(hex_color):
    return PatternFill("solid", fgColor=hex_color)

def _border(style="thin"):
    s = Side(style=style)
    return Border(left=s, right=s, top=s, bottom=s)

def _align(h="left", v="center", wrap=True):
    return Alignment(horizontal=h, vertical=v, wrap_text=wrap)

def _hdr_cell(ws, cell_ref, text, bg=C_NAVY, fg=C_WHITE, size=10, bold=True, align="center"):
    c = ws[cell_ref]
    c.value = text
    c.font = _font(size=size, bold=bold, color=fg)
    c.fill = _fill(bg)
    c.alignment = _align(h=align)
    c.border = _border()
    return c

def _data_cell(ws, cell_ref, text, bg=C_WHITE, fg="000000", bold=False,
               italic=False, align="left", size=9):
    c = ws[cell_ref]
    c.value = text
    c.font = _font(size=size, bold=bold, italic=italic, color=fg)
    c.fill = _fill(bg)
    c.alignment = _align(h=align)
    c.border = _border()
    return c

# ═══════════════════════════════════════════════════════════════════════════════
# SHEET 1 - MASTER COMPARISON TABLE
# ═══════════════════════════════════════════════════════════════════════════════

def build_comparison_sheet(wb):
    ws = wb.active
    ws.title = "ICU CXR Comparison Table"
    ws.sheet_view.showGridLines = False
    ws.freeze_panes = "A4"

    # ── TITLE BLOCK ─────────────────────────────────────────────────────────
    ws.merge_cells("A1:R1")
    t = ws["A1"]
    t.value = "ICU EMERGENCY CHEST X-RAY — MASTER COMPARISON TABLE"
    t.font = _font(size=16, bold=True, color=C_WHITE)
    t.fill = _fill(C_NAVY)
    t.alignment = _align(h="center")
    t.border = _border()

    ws.merge_cells("A2:R2")
    s = ws["A2"]
    s.value = "High-Yield CXR Findings | ICU Emergency Differentials | Clinical Decision Support | USMLE / Ward / Viva Ready"
    s.font = _font(size=9, italic=True, color=C_WHITE)
    s.fill = _fill("2E4057")
    s.alignment = _align(h="center")
    s.border = _border()

    # ── COLUMN HEADERS ──────────────────────────────────────────────────────
    headers = [
        "EMERGENCY\nDIAGNOSIS",
        "URGENCY\nLEVEL",
        "TRACHEA /\nMEDIASTINUM",
        "LUNG\nFIELDS",
        "PLEURAL\nSPACE",
        "HEART &\nBORDERS",
        "DIAPHRAGM",
        "KEY CXR\nSIGN(S)",
        "AIR\nBRONCHOGRAM",
        "VOLUME\nCHANGE",
        "MEDIASTINAL\nSHIFT",
        "CRITICAL\nCLINICAL CLUE",
        "IMMEDIATE\nACTION",
        "DO NOT\nDELAY FOR CXR?",
        "KEY\nDIFFERENTIAL",
        "CONFIRM WITH",
        "COMMON\nPITFALL",
        "MEMORY\nHOOK"
    ]

    col_widths = [22, 10, 20, 28, 22, 22, 20, 28, 12, 12, 16, 32, 30, 14, 22, 22, 32, 24]

    for col_i, (hdr, width) in enumerate(zip(headers, col_widths), start=1):
        col_letter = get_column_letter(col_i)
        ws.column_dimensions[col_letter].width = width
        cell_ref = f"{col_letter}3"
        _hdr_cell(ws, cell_ref, hdr, bg=C_DARK_RED, fg=C_WHITE, size=9, align="center")

    ws.row_dimensions[1].height = 28
    ws.row_dimensions[2].height = 16
    ws.row_dimensions[3].height = 36

    # ── DATA ROWS ────────────────────────────────────────────────────────────
    # (Diagnosis, Urgency, Trachea/Mediastinum, Lung Fields, Pleural Space,
    #  Heart, Diaphragm, Key CXR Signs, Air Bronchogram, Volume Change,
    #  Mediastinal Shift, Critical Clinical Clue, Immediate Action,
    #  No Delay, Key Differential, Confirm With, Common Pitfall, Memory Hook)

    data = [
        (
            "TENSION\nPNEUMOTHORAX",
            "🔴 IMMEDIATE\nLIFE-THREAT",
            "Deviated AWAY\nfrom affected side",
            "Absent markings\non affected side;\ncontralateral\nlung compressed",
            "Large air collection;\nno pleural markings",
            "Contralateral\ncardiac shift;\nborders compressed",
            "Ipsilateral\ninverted/\ndepressed",
            "Pleural line +\ndeep sulcus sign\n(supine); tracheal\ndeviation",
            "Absent",
            "Increased\n(hyperexpanded\naffected side)",
            "AWAY from\naffected side",
            "Hypotension + JVD\n+ absent breath\nsounds = BECK's\nfor tension PTX",
            "NEEDLE DECOMPRESSION\nIMMEDIATELY — 2nd ICS\nmidclavicular line;\nthen chest drain",
            "YES — clinical\ndiagnosis,\ndo NOT wait",
            "Simple PTX,\nMassive effusion\n(but shift direction\ndiffers)",
            "Clinical exam\nfirst; CXR after\nstabilisation;\nUSS",
            "On supine ICU film:\nno visible pleural\nline — look for\nDEEP SULCUS SIGN",
            "Tension = Trachea\nmoves AWAY\n(pushed);\nCollapse = TOWARD\n(pulled)"
        ),
        (
            "MASSIVE\nHAEMOTHORAX",
            "🔴 IMMEDIATE\nLIFE-THREAT",
            "May deviate\nAWAY if massive",
            "Opacified\nhemithorax;\nhomogeneous\nwhite-out",
            "Massive fluid;\nno meniscus on\nsupine (layers\nout as haziness)",
            "Shifted contralat-\nerally if very large",
            "Elevated on\naffected side;\noutline lost",
            "White hemithorax;\ntracheal shift away;\nno air-fluid level\non supine",
            "Absent",
            "None (fluid\nfills space)",
            "AWAY if\nmassive",
            "Trauma + shock +\nopaque hemithorax\n= haemothorax until\nproven otherwise",
            "Large-bore IV\naccess; blood XM;\nchest drain\n(28-32Fr); surgery\nif >1500mL initial",
            "NO — but resus-\ncitation over\nradiology always",
            "Pleural effusion\n(non-traumatic);\ntension PTX (but\nPTX is blacker)",
            "CXR + USS\nconfirms fluid;\nCT chest for\nequivocal cases",
            "Supine CXR shows\nhomogeneous haziness\nnot clear meniscus.\nDo NOT drain the\nbright side (PTX!)",
            "Haemothorax = WHITE\n(blood = fluid);\nPTX = BLACK (air).\nOn supine: white\n= haemo, black = PTX"
        ),
        (
            "TENSION\nPNEUMOPERICARDIUM\n/ CARDIAC\nTAMPONADE",
            "🔴 IMMEDIATE\nLIFE-THREAT",
            "Central;\nno shift",
            "Clear lung fields\n(distinguishes from\ncardiac failure)",
            "No pleural\neffusion typically",
            "FLASK / GLOBULAR\nheart shadow;\nrapid increase\nin size on serial",
            "Normal or slightly\nelevated bilateral",
            "Globular 'water-\nbottle' heart;\nrapidly enlarging\ncardiac silhouette;\nclear lung fields",
            "Absent",
            "None",
            "None typically",
            "Beck's Triad:\nHypotension +\nJVD + Muffled\nheart sounds;\nelectrical\nalternans on ECG",
            "Pericardiocentesis\n(subxiphoid route);\nCT/echo confirms;\nsurgery for\ntraumatic",
            "YES — pericardio-\ncentesis by clinical\njudgement; do not\nwait for echo",
            "CCF (but: CCF\nhas pulmonary\noedema signs;\ntamponade has\nclear lungs)",
            "Bedside echo\n(POCUS) = gold\nstandard; CXR\nsuggestive only",
            "Clear lung fields\nwith large heart =\nTAMPONADE not CCF.\nCCF has oedema;\ntamponade does not.",
            "TAMPONADE:\nFlask heart +\nClear lungs +\nBeck's Triad.\nCCF: Big heart +\nWet lungs"
        ),
        (
            "AORTIC\nDISSECTION\n(Type A)",
            "🔴 IMMEDIATE\nLIFE-THREAT",
            "Widened mediastinum\n(>8 cm on PA);\naortic knuckle\nobscured or\ndisplaced",
            "Usually clear\nunless\nhaemothorax or\ninfarction occurs",
            "Left pleural\neffusion (blood);\nor right in Type B",
            "Displaced aortic\ncontour; left\nheart border may\nbe indistinct",
            "Left hemidiaphragm\nelevated with\nleft haemathorax",
            "Widened mediastinum\n>8cm; obliterated\naortic knuckle;\ndisplaced trachea;\ncalcified intima\nsign (intimal flap)",
            "Absent",
            "None",
            "Trachea deviated\nright with left\nmediastinal mass",
            "Tearing/ripping\nback pain radiating\nto jaw or abdomen;\npulse differential\nor BP differential\nbetween arms",
            "IV access x2;\ntype & cross;\nurgent CT\nangio chest;\ncardiothoracic\nsurgery consult\nimmediately",
            "YES — urgent CT\nif haemodynamically\nstable; surgery\nif Type A",
            "ACS (ECG +\ntroponins help);\nPE; mediastinitis;\nrapidly growing\nhilar mass",
            "CT angiography\n(gold standard);\nTOE in unstable;\nMRI (non-urgent)",
            "Normal CXR does\nNOT exclude dissec-\ntion. 15% of dissec-\ntions have normal\nmediastinum on CXR.",
            "WIDE mediastinum\n= DISSECTION until\nproven otherwise.\nDo NOT give\nthrombolytics!"
        ),
        (
            "ACUTE\nPULMONARY\nOEDEMA (APO)",
            "🔴 URGENT\nSEVERE",
            "Central;\nno shift",
            "Bilateral perihilar\n'bat-wing' opacity;\nupper lobe blood\ndiversion;\nKerley B lines",
            "Bilateral pleural\neffusions (right\nusually > left);\nblunted CP angles",
            "ENLARGED (CTR\n>0.5); prominent\npulmonary vessels;\nborders still clear",
            "Elevated bilateral\n(may be unilateral\nif dependent)",
            "Bat-wing opacity;\nKerley B lines\n(1-2mm horiz. lines,\nlower zones);\nupper lobe\ndiversion;\nperibronchial\ncuffing",
            "Present in\nalveolar stage\n(late)",
            "None (fluid\nnot collapse)",
            "None",
            "Pink frothy sputum;\ncrackles bilateral;\nS3 gallop; history\nof CCF/MI/AF;\nrapid improvement\nwith diuretics",
            "Sit up (upright);\nO2; IV furosemide;\nGTN infusion;\nNIV (CPAP);\ntreat cause (MI,\nAF, hypertensive\ncrisis)",
            "NO — CXR helps\nstage severity\nand monitor\nresponse",
            "ARDS (no\ncardiomegaly;\nnon-dependent;\nnot rapid\nclearance);\nbilateral\npneumonia",
            "BNP/NT-proBNP;\necho; serial\nCXR (response\nto diuresis\nconfirms cardiac)",
            "APO can be\nUNILATERAL (right-\nsided) in acute\nMR, or post-\nlobectomy. Do not\nmiss as pneumonia.",
            "APO = Big heart +\nWet lungs +\nKerley B + Bat\nwing. Clears fast\nwith furosemide."
        ),
        (
            "ARDS\n(Non-Cardiogenic\nPulmonary\nOedema)",
            "🔴 URGENT\nSEVERE",
            "Central;\nno shift",
            "Diffuse bilateral\ndense opacification;\nperipheral > central\n(unlike APO);\nground-glass\nthroughout",
            "Small or no\neffusions;\ncostophrenic\nangles may be\nblunted",
            "NORMAL size\n(distinguishes\nfrom cardiogenic!)",
            "Normal",
            "Diffuse bilateral\nopacification;\nperipheral distrib-\nution; NO Kerley B;\nno upper lobe\ndiversion; normal\ncardiac size",
            "Present (alveolar\nflooding)",
            "None (flooding,\nnot collapse)",
            "None",
            "Cause: sepsis,\ntrauma, aspiration,\npancreatitis;\nPaO2/FiO2 < 200;\npoor response\nto O2",
            "Protective lung\nventilation (TV\n6mL/kg IBW);\nhigh PEEP;\nprone positioning\n(if P/F < 150);\ntreat underlying\ncause",
            "NO — but initiate\ntreatment early;\ndo not delay\nventilation",
            "Cardiogenic\npulmonary oedema\n(heart size is key\ndistinguisher);\nbilateral pneumonia",
            "ABG (P/F ratio);\necho (normal LV\nfunction); BAL;\nCT chest",
            "CXR in ARDS\nmay UNDERESTIMATE\nextent. CT shows\ndependent consoli-\ndation often missed\non CXR.",
            "ARDS = Normal\nheart + Wet lungs\n+ No Kerley B.\nAPO = Big heart\n+ Kerley B +\nbat-wing."
        ),
        (
            "MASSIVE\nPULMONARY\nEMBOLISM",
            "🔴 IMMEDIATE\nLIFE-THREAT",
            "Central or mildly\nwidened if right\nheart strain\n(pulmonary art.\nenlarged)",
            "Often NORMAL!\nWestermark sign:\nfocal oligaemia.\nHampton's hump:\nwedge opacity",
            "Small pleural\neffusion (25%)\ninfarct zone",
            "Enlarged right\nheart (acute cor\npulmonale);\nprominent\npulmonary artery\n'knuckle'",
            "Elevated on\naffected side\n(infarct/splinting)",
            "OFTEN NORMAL CXR!\nWestermark sign\n(focal vessel cut-\noff); Hampton's\nhump (pleural-\nbased wedge);\nenlarged right PA",
            "Absent (or\npresent in\ninfarct zone)",
            "None\n(typically)",
            "None typically",
            "Pleuritic chest\npain; haemoptysis;\nsudden dyspnoea;\nlow SpO2;\nrisk factors\n(DVT, surgery,\nimmobility, OCP)",
            "O2; anticoagulate\n(LMWH/heparin);\nif massive:\nthrombolytics\nor ECMO;\ninterventional\ncath",
            "NEVER wait for\nCXR to start\nheparin if\nclinically likely",
            "Pneumonia\n(consolidation);\npneumothorax;\naortic dissection\n(do NOT\nthrombolyse!)",
            "CTPA (gold\nstandard); V/Q\nscan; D-dimer;\nechocardiography\n(RV strain)",
            "NORMAL CXR does\nNOT exclude PE.\nWestermark/\nHampton's signs\nare rare. Never\nmiss on clinical\ngrounds.",
            "Normal CXR +\nLow O2 + Pleuritic\npain = PE until\nproven otherwise.\nDo NOT let normal\nCXR falsely reassure."
        ),
        (
            "LOBAR\nCOLLAPSE\n(Atelectasis)",
            "🟠 URGENT",
            "Deviated TOWARD\naffected side\n(trachea pulled)",
            "Opacification of\nthe collapsed lobe;\nremaining lobes\nmay hyperinflate;\nno air bronchogram",
            "No effusion\nunless additional\npathology",
            "Shifted TOWARD\ncollapse;\nadjacent borders\nmay be obscured",
            "Elevated on\naffected side;\nsilhouette sign\nwith diaphragm",
            "Opacification\nwith VOLUME LOSS;\nfissure displacement;\nno air bronchogram;\nsilhouette sign",
            "ABSENT\n(distinguishes\nfrom consolidation)",
            "DECREASED\n(fissures drawn\ntoward lesion)",
            "TOWARD\naffected side\n(pulled, not pushed)",
            "Post-operative;\nICU patient;\nno cough; mucus\nplug; foreign body;\ncentral tumour",
            "Physiotherapy;\nnebulised saline;\nbronchoscopy if\npersistent (mucus\nplug); treat\nunderlying cause",
            "NO — but must\nidentify and\nmanage cause",
            "Consolidation\n(air bronchogram\npresent; no volume\nloss); effusion\n(shift away, not\ntoward)",
            "CT chest;\nbronchoscopy;\nspirometry",
            "If collapse +\neffusion occur\ntogether, shift\nmay be ABSENT.\nDo not miss\nlobar collapse\nbehind the heart.",
            "COLLAPSE = pulled\n(toward, volume\nloss, no air\nbronchogram).\nCONSOLIDATION =\nno pull, air\nbronchogram present."
        ),
        (
            "PNEUMONIA\n(LOBAR /\nSEVERE)",
            "🟠 URGENT",
            "Central; no\nshift typically",
            "Homogeneous\nopacity; lobar or\nsegmental; fluffy\nill-defined margins",
            "Parapneumonic\neffusion possible;\ncostophrenic\nangle blunting",
            "Silhouette sign:\nborder of adjacent\nstructure lost;\nnormal heart size",
            "May be lost\n(lower lobe\npneumonia) via\nsilhouette sign",
            "Air bronchogram\n(PATHOGNOMONIC of\nconsolidation);\nsilhouette sign;\nlobar distribution",
            "PRESENT\n(pathognomonic\nof air-space\ndisease)",
            "None\n(maintained)",
            "None typically",
            "Fever; productive\ncough; consolidation\nlocated; CXR LAGS\nbehind clinical\nimprovement by\ndays to weeks",
            "Antibiotics;\nO2; IV fluids;\nassess CURB-65;\nICU if septic\nshock; treat\nunderlying cause",
            "NO",
            "Pulmonary\noedema (bilateral,\ncardiomegaly);\nTB (upper lobe\ncavitation);\nlung cancer\n(irregular mass)",
            "Sputum culture;\nblood culture;\nPCR; serial CXR\n(resolution\nconfirms pneumonia\nvs malignancy)",
            "CXR can lag 6 weeks\nbehind clinical\nrecovery. Do NOT\nretreat based on\nCXR alone. Repeat\nCXR at 6-8 weeks\nto exclude cancer.",
            "AIR BRONCHOGRAM\n= alveoli full of\nfluid but airways\nstill open.\nConsolidation\nnot collapse."
        ),
        (
            "MALPOSITIONED\nETT\n(Right Main\nBronchus\nIntubation)",
            "🔴 IMMEDIATE\nIATROGENIC",
            "ETT tip too low;\nbelow carina;\nright main\nbronchus preferred\n(more vertical)",
            "Left lung collapse\n(no ventilation);\nright side\nhyperinflated;\nasymmetric markings",
            "None",
            "Left lung collapse\ncauses mediastinal\nshift to left",
            "Left diaphragm\nelevated with\nleft collapse",
            "ETT tip < 2cm\nabove carina or\nin right main;\nleft lung\nopacification;\nhigh peak airway\npressures on vent",
            "Absent left\n(collapsed);\npresent right",
            "Left lung\nDECREASED\n(collapsed)",
            "LEFT (toward\ncollapsed left)",
            "High PIP on\nventilator;\ndesaturation;\nasymmetric chest\nrise; absent\nbreath sounds left",
            "PULL BACK ETT\nimmediately to\n2-3cm above\ncarina (T3-T4);\ncheck with CXR;\nbag-mask if\nextubated",
            "YES — act on\nventilator alarms\nimmediately",
            "Left lower lobe\ncollapse (other\ncause); left\npneumothorax\n(but different\nappearance)",
            "Immediate CXR;\nauscultation\nbilaterally;\nfibre-optic\nbronchoscopy if\nunsure",
            "Right main intub-\nation is the most\ncommon ETT error.\nRight main bronchus\nis more vertical.\nALWAYS check ETT\ntip on CXR.",
            "ETT should sit\nat T3-T4, 2-3cm\nabove carina.\nRight main =\ncollapsed LEFT\nlung. Pull back!"
        ),
        (
            "MALPOSITIONED\nCVC\n(Pneumothorax\npost-insertion)",
            "🔴 IMMEDIATE\nIATROGENIC",
            "Central (unless\nlarge PTX causes\nshift)",
            "Absent lung\nmarkings on\naffected side;\npleural line\nvisible at apex",
            "Air in pleural\nspace; pleural\nline visible",
            "Normal unless\ntension",
            "Normal unless\ntension",
            "Apical pleural\nline; absent\nperipheral lung\nmarkings post-\nsubclavian/IJ\nCVC insertion",
            "Absent",
            "Normal or\nincreased\n(PTX side)",
            "Away (if tension)",
            "Post-line insertion\nin subclavian or\nIJ; sudden\ndyspnoea; chest\npain; decreasing\nSpO2",
            "Oxygen (high flow);\nchest drain if\nlarge/symptomatic;\naspirate if small;\nstop insertion;\ncheck bilateral",
            "YES — treat any\npost-procedure\nPTX promptly",
            "Simple apical\nbullae; skin fold\nartefact mimicking\npleural line",
            "Immediate CXR\npost-procedure;\nUSS guided CVC\nreduces risk",
            "A SKIN FOLD can\nmimick a pneumo-\nthorax line. Lung\nmarkings extend\nbeyond a skin\nfold, NOT a PTX.",
            "POST-LINE CXR is\nMANDATORY. Check:\n1) CVC tip position\n2) Pneumothorax\n3) Haemothorax"
        ),
        (
            "OESOPHAGEAL\nRUPTURE\n(Boerhaave\nSyndrome)",
            "🔴 IMMEDIATE\nLIFE-THREAT",
            "May show left\nmediastinal\nwidening;\npneumomediastinum",
            "Left lower lobe\ncollapse or\nconsolidation;\npneumonia may\nfollow",
            "Left pleural\neffusion (most\ncommon side);\nlate: hydropneumo-\nthorax",
            "Normal",
            "Left elevated;\noutline lost",
            "Pneumomediastinum\n(air tracking\nalong mediastinum);\nleft pleural\neffusion; surgical\nemphysema in\nneck/chest",
            "Absent",
            "None",
            "Mediastinal\nwidening",
            "Mackler's Triad:\nVomiting + Chest\npain + Surgical\nemphysema;\nhistory of recent\nretching/vomiting",
            "Keep nil by mouth;\nIV antibiotics;\nurgent CT with\noral contrast;\nsurgery (primary\nrepair if early);\nextensive lavage",
            "YES — high\nmortality.\nDo NOT start\nfeeding.\nUrgent surgical\nconsult.",
            "Aortic dissection;\npneumothorax;\npulmonary\noedema;\nacute MI;\npericarditis",
            "CT with oral\ncontrast or water-\nsoluble swallow;\nendoscopy\ncautiously;\nchest drain\nfor hydropneumo-\nthorax",
            "Often mistaken\nfor MI, dissection\nor PTX. KEY: history\nof forceful vomiting\n+ left effusion +\npneumomediastinum\n= Boerhaave.",
            "BOERHAAVE =\nVomit + Mediastinal\nair + Left effusion.\nHigh mortality if\nmissed. 'The great\nmimic'."
        ),
        (
            "DIAPHRAGMATIC\nRUPTURE",
            "🟠 URGENT\nPOST-TRAUMA",
            "Mediastinal shift\naway (if bowel/\nstomach herniates\ninto chest)",
            "Left lower chest\nopacity or\ngas-filled loops\nabove diaphragm",
            "No typical\npleural effusion;\ngastric/bowel\ngas in left chest",
            "Shifted right\nif large hernia",
            "Left diaphragm\nINDISTINCT /\nELEVATED or\nAbsent; gas\npatterns above\nwhere diaphragm\nshould be",
            "Elevated/indistinct\nleft diaphragm;\nbowel loops or\ngastric bubble\nIN chest; NGT\ncoiled in chest\n(CLASSIC SIGN)",
            "Absent",
            "None specific",
            "AWAY from\nhernia",
            "Trauma patient;\nbreathing difficulty;\nbowel sounds in\nchest; respiratory\ndistress; NGT in\nthe chest!",
            "NG tube insertion\n(confirms if coils\nin chest); CT chest\n+ abdomen;\nsurgical repair;\naspirate air if\nstomach in chest",
            "NO — CXR first\nline, then CT",
            "Large pleural\neffusion; lobar\ncollapse; acute\ngastric volvulus;\ntension PTX\n(left-sided)",
            "CT (gold standard);\nnasogastric tube\nradiograph;\ndiagnostic\nlaparoscopy;\nright-sided: CT\nalways needed",
            "RIGHT-sided rupture\ndiagnosis is HARD\n(liver masks it on\nCXR). CT is essential.\nDo not diagnose by\nCXR alone on right.",
            "NGT IN CHEST\n= DIAPHRAGM\nRUPTURE until\nproven otherwise.\nAlways check NGT\npath on CXR."
        ),
        (
            "PNEUMO-\nMEDIASTINUM",
            "🟡 URGENT",
            "Air outlining\nmediastinal\nstructures; lucent\nhalo around aorta,\nheart, trachea",
            "Often clear;\nPTX may co-exist;\nsubcut emphysema\nmay track into\nneck",
            "May have PTX\nor effusion\nif oesophageal\nrupture",
            "Air outlines\ncardiac borders;\nlunar/Naclerio V\nsign",
            "Air may track\nunder diaphragm",
            "Thin lucent stripe\nalong left heart\nborder; Naclerio V\nsign; subcutaneous\nemphysema neck;\nair tracking up\nfrom mediastinum",
            "N/A",
            "N/A",
            "N/A",
            "Spontaneous:\nyoung male,\nasthma; trauma;\npressure barotrauma;\nBoerhaave;\ntracheal injury",
            "Treat underlying\ncause; O2\n(accelerates\nreabsorption);\nif Boerhaave:\nemergency surgery;\nif spontaneous:\nobserve",
            "NO (unless\nBoerhaave\nsuspected)",
            "Boerhaave\nsyndrome;\ntracheal tear;\nasthma attack;\nbarotrauma\n(ventilated pt)",
            "CT chest;\nesophagogram if\nBoerhaave suspected;\nbronchoscopy if\ntracheal injury",
            "Spontaneous\npneumomediastinum\nin young asthmatics\ncan be missed.\nThe lucent lines\nalong heart border\nare subtle.",
            "Naclerio 'V' sign:\nair in mediastinum\nforms V-shape\nbetween aorta and\ndiaphragm on left.\nClassic for\nBoerhaave."
        ),
    ]

    # Urgency colour map
    urgency_bg = {
        "🔴 IMMEDIATE\nLIFE-THREAT":   (C_PINK,    C_CRIMSON),
        "🔴 IMMEDIATE\nIATROGENIC":     (C_PINK,    C_CRIMSON),
        "🔴 URGENT\nSEVERE":           (C_LTORANGE, "8B4500"),
        "🟠 URGENT":                    (C_LTORANGE, "8B4500"),
        "🟠 URGENT\nPOST-TRAUMA":      (C_LTORANGE, "8B4500"),
        "🟡 URGENT":                    (C_YELLOW_HI, "7D6608"),
    }

    # Alternating row backgrounds
    row_bgs = [C_WHITE, C_LGRAY]

    for row_i, row_data in enumerate(data):
        excel_row = row_i + 4
        bg_default = row_bgs[row_i % 2]
        urgency_val = row_data[1]
        urg_bg, urg_fg = urgency_bg.get(urgency_val, (C_LTORANGE, "000000"))

        # Each column
        for col_i, val in enumerate(row_data):
            col_letter = get_column_letter(col_i + 1)
            cell_ref = f"{col_letter}{excel_row}"

            # Special formatting by column
            if col_i == 0:  # Diagnosis
                c = ws[cell_ref]
                c.value = val
                c.font = _font(size=10, bold=True, color=C_WHITE)
                c.fill = _fill(C_NAVY)
                c.alignment = _align(h="center")
                c.border = _border()
            elif col_i == 1:  # Urgency
                c = ws[cell_ref]
                c.value = val
                c.font = _font(size=9, bold=True, color=urg_fg)
                c.fill = _fill(urg_bg)
                c.alignment = _align(h="center")
                c.border = _border()
            elif col_i == 7:  # Key CXR Signs
                c = ws[cell_ref]
                c.value = val
                c.font = _font(size=9, bold=True, color=C_BLUE)
                c.fill = _fill(C_LTBLUE)
                c.alignment = _align()
                c.border = _border()
            elif col_i == 12:  # Immediate Action
                c = ws[cell_ref]
                c.value = val
                c.font = _font(size=9, bold=True, color=C_DARK_RED)
                c.fill = _fill(C_PINK)
                c.alignment = _align()
                c.border = _border()
            elif col_i == 13:  # Do Not Delay
                yes_no = "YES" in val
                c = ws[cell_ref]
                c.value = val
                c.font = _font(size=9, bold=True, color=(C_DARK_RED if yes_no else C_GREEN))
                c.fill = _fill(C_PINK if yes_no else C_LTGREEN)
                c.alignment = _align(h="center")
                c.border = _border()
            elif col_i == 17:  # Memory Hook
                c = ws[cell_ref]
                c.value = val
                c.font = _font(size=9, italic=True, color=C_PURPLE)
                c.fill = _fill(C_LTPURPLE)
                c.alignment = _align()
                c.border = _border()
            else:
                _data_cell(ws, cell_ref, val, bg=bg_default, size=9)

        # Row height
        ws.row_dimensions[excel_row].height = 80

    return ws


# ═══════════════════════════════════════════════════════════════════════════════
# SHEET 2 - DECISION TREES (text-based flowcharts per emergency)
# ═══════════════════════════════════════════════════════════════════════════════

def build_decision_tree_sheet(wb):
    ws = wb.create_sheet("Decision Trees")
    ws.sheet_view.showGridLines = False

    # Title
    ws.merge_cells("A1:H1")
    t = ws["A1"]
    t.value = "ICU EMERGENCY CXR — CLINICAL DECISION TREES"
    t.font = _font(size=16, bold=True, color=C_WHITE)
    t.fill = _fill(C_DARK_RED)
    t.alignment = _align(h="center")
    t.border = _border()
    ws.row_dimensions[1].height = 30

    ws.merge_cells("A2:H2")
    s = ws["A2"]
    s.value = "Follow each tree: CXR finding → Clinical correlation → Decision → Action. Colour = urgency."
    s.font = _font(size=9, italic=True, color=C_WHITE)
    s.fill = _fill("2E4057")
    s.alignment = _align(h="center")
    ws.row_dimensions[2].height = 16

    # Column widths
    for col_i, width in enumerate([28, 26, 26, 26, 26, 26, 26, 26], start=1):
        ws.column_dimensions[get_column_letter(col_i)].width = width

    # ── Decision tree data (label, steps list) ──────────────────────────────
    trees = [
        {
            "title": "TREE 1: OPAQUE HEMITHORAX",
            "color": C_NAVY,
            "steps": [
                ("STEP 1", "OPAQUE HEMITHORAX\n(White-out on one side)", C_DARK_RED, C_WHITE),
                ("STEP 2", "Is there MEDIASTINAL SHIFT?", C_NAVY, C_WHITE),
                ("STEP 3A\n(Shift AWAY)", "→ EFFUSION or TENSION PTX\nAsk: Is trachea deviated?\nIs it trauma?", C_ORANGE, C_WHITE),
                ("STEP 3B\n(Shift TOWARD)", "→ COLLAPSE\nVolume loss; no air bronchogram;\nFissures displaced toward opacity", C_TEAL, C_WHITE),
                ("STEP 3C\n(NO Shift)", "→ CONSOLIDATION, FIBROTHORAX\nor MESOTHELIOMA\nAir bronchogram present?", C_PURPLE, C_WHITE),
                ("STEP 4A\n(Shift AWAY + Blacker)", "TENSION PNEUMOTHORAX\nACT NOW: Needle\ndecompression 2nd ICS MCL", C_DARK_RED, C_WHITE),
                ("STEP 4B\n(Shift AWAY + Whiter)", "MASSIVE EFFUSION or\nHAEMOTHORAX\n→ Drain; check USS/CT", C_ORANGE, C_WHITE),
                ("FINAL CHECK", "Air bronchogram present\n→ CONSOLIDATION\nAir bronchogram absent\n→ COLLAPSE or EFFUSION", C_TEAL, C_WHITE),
            ]
        },
        {
            "title": "TREE 2: TENSION PNEUMOTHORAX",
            "color": C_DARK_RED,
            "steps": [
                ("TRIGGER", "Patient in ICU:\nHypotension + Desaturation\n+ High Peak Airway Pressures", C_DARK_RED, C_WHITE),
                ("ASK FIRST", "Is trachea deviated?\nAbsent breath sounds one side?\nJVD present?", C_ORANGE, C_WHITE),
                ("IF YES →", "CLINICAL DIAGNOSIS OF\nTENSION PNEUMOTHORAX\nDO NOT WAIT FOR CXR", C_DARK_RED, C_WHITE),
                ("ACTION", "2nd ICS, Midclavicular Line\nLarge bore needle\n→ Hiss of air = confirmed", C_CRIMSON, C_WHITE),
                ("THEN", "Insert chest drain\n(4th/5th ICS, anterior\naxillary line) IMMEDIATELY", C_ORANGE, C_WHITE),
                ("GET CXR AFTER", "Confirm re-expansion\nCheck drain position\nAssess for effusion (haemopneumo)", C_TEAL, C_WHITE),
                ("SUPINE CXR TIP", "No apical line visible?\nLook for DEEP SULCUS SIGN:\nAbnormally deep, black\ncostophrenic angle", C_PURPLE, C_WHITE),
                ("PITFALL", "Do NOT mistake\nSKIN FOLD for pleural line.\nLung markings extend\nbeyond skin fold, NOT PTX.", C_NAVY, C_WHITE),
            ]
        },
        {
            "title": "TREE 3: APO vs ARDS",
            "color": C_BLUE,
            "steps": [
                ("TRIGGER", "Bilateral opacification on CXR\n+ Hypoxia + Dyspnoea", C_NAVY, C_WHITE),
                ("KEY QUESTION 1", "Is HEART SIZE enlarged?\n(CTR > 0.5 on PA film)", C_BLUE, C_WHITE),
                ("IF ENLARGED →", "LIKELY CARDIOGENIC (APO)\nCheck: Kerley B lines?\nBat-wing distribution?\nBilateral effusions?", C_TEAL, C_WHITE),
                ("IF NORMAL SIZE →", "LIKELY NON-CARDIOGENIC\n(ARDS)\nCheck: peripheral opacities?\nNo Kerley B?\nCause: sepsis/trauma?", C_ORANGE, C_WHITE),
                ("APO MANAGEMENT", "Sit upright; O2;\nIV Furosemide;\nGTN infusion; CPAP/NIV;\nTreat MI/AF if cause", C_TEAL, C_WHITE),
                ("ARDS MANAGEMENT", "Protective ventilation\n(TV 6mL/kg IBW);\nHigh PEEP; Prone;\nTreat underlying cause", C_PURPLE, C_WHITE),
                ("RESPONSE CHECK", "APO: Rapid CXR improvement\nin hours with diuresis.\nARDS: Persistent despite\ndiuresis and ventilation.", C_NAVY, C_WHITE),
                ("CONFIRM", "Echo: LV function\nBNP: elevated in APO\nBAL: for ARDS aetiology\nP/F ratio: severity", C_DARK_RED, C_WHITE),
            ]
        },
        {
            "title": "TREE 4: ETT MALPOSITION",
            "color": C_TEAL,
            "steps": [
                ("TRIGGER", "Post-intubation CXR\nor Ventilator alarm:\nHigh PIP / Desaturation", C_NAVY, C_WHITE),
                ("CHECK ETT TIP", "Should be at T3-T4\n2-3cm ABOVE carina\nIs tip too low?", C_TEAL, C_WHITE),
                ("TOO LOW →", "RIGHT MAIN BRONCHUS\nINTUBATION\n(Right is more vertical)", C_DARK_RED, C_WHITE),
                ("CLINICAL SIGNS", "Left lung collapse\nAsymmetric chest rise\nAbsent left breath sounds\nRising PIP on ventilator", C_ORANGE, C_WHITE),
                ("ACTION", "PULL BACK ETT\nuntil tip at T3-T4\n(2-3cm above carina)\nRecheck CXR immediately", C_DARK_RED, C_WHITE),
                ("TOO HIGH →", "RISK OF ACCIDENTAL\nEXTUBATION\nPush in carefully;\ncheck depth at lip", C_ORANGE, C_WHITE),
                ("NORMAL POSITION", "Tip at T3-T4 level;\nCarina at T5-T6;\n2-3cm clearance;\nbilateral equal markings", C_GREEN, C_WHITE),
                ("CHECK ALSO", "Confirm tracheal midline;\nno right main bronchus;\nno oesophageal intubation\n(air in stomach?)", C_NAVY, C_WHITE),
            ]
        },
        {
            "title": "TREE 5: WIDENED MEDIASTINUM",
            "color": C_PURPLE,
            "steps": [
                ("TRIGGER", "Mediastinum > 8cm on\nPA film (or 'wide'\non AP supine)\n+ Clinical Context", C_NAVY, C_WHITE),
                ("KEY QUESTION 1", "Is patient in TRAUMA?", C_PURPLE, C_WHITE),
                ("TRAUMA YES →", "SUSPECT AORTIC INJURY\nUrgent CT Angiography\nWatch for 1st/2nd rib\nfracture (aortic tear risk)", C_DARK_RED, C_WHITE),
                ("TRAUMA NO →", "CONSIDER:\nAortic Dissection\nMediastinitis\nLymphoma/mass\nHaematoma", C_ORANGE, C_WHITE),
                ("DISSECTION FEATURES", "Tearing pain to back/jaw;\nPulse differential;\nBP differential >20mmHg;\nAortic knuckle obscured", C_CRIMSON, C_WHITE),
                ("CRITICAL WARNING", "DO NOT GIVE\nTHROMBOLYTICS if\nDissection suspected\n(will be fatal)", C_DARK_RED, C_WHITE),
                ("ACTION", "Urgent CT Angiography\n(gold standard);\nTOE if unstable;\nBeta-blocker;\nICU cardiothoracics", C_TEAL, C_WHITE),
                ("PITFALL", "NORMAL CXR does NOT\nexclude dissection.\n15% dissections have\nnormal mediastinum.\nTrust clinical picture.", C_NAVY, C_WHITE),
            ]
        },
        {
            "title": "TREE 6: POST-PROCEDURE CXR",
            "color": C_TEAL,
            "steps": [
                ("TRIGGER", "CXR after:\nCentral Line / ETT /\nChest Drain / Pacemaker", C_NAVY, C_WHITE),
                ("STEP 1 — CVC", "Tip in SVC at\nSVC-RA junction?\nNo kinking or coiling?\nNo contralateral placement?", C_TEAL, C_WHITE),
                ("STEP 2 — PTX?", "Check ipsilateral\nand contralateral apex.\nNew pleural line?\nDeep sulcus sign?", C_DARK_RED, C_WHITE),
                ("STEP 3 — ETT", "Tip at T3-T4?\n2-3cm above carina?\nBilateral lung expansion?", C_ORANGE, C_WHITE),
                ("STEP 4 — NGT", "Does NGT go BELOW\ndiaphragm and curve LEFT?\nIf in bronchus → DANGER\n→ REMOVE IMMEDIATELY", C_CRIMSON, C_WHITE),
                ("STEP 5 — DRAIN", "Is drain in pleural space?\nIs PTX/Effusion resolving?\nDrain kinking or blocked?", C_PURPLE, C_WHITE),
                ("STEP 6 — PACER", "RV lead at apex?\nRA lead in RAA?\nGenerator in\ninfraclavicular region?", C_BLUE, C_WHITE),
                ("ALWAYS", "Document position in notes.\nAlert team if malpositioned.\nRepeat CXR post-correction.", C_GREEN, C_WHITE),
            ]
        },
    ]

    current_row = 3

    for tree in trees:
        # Tree title
        ws.merge_cells(f"A{current_row}:H{current_row}")
        c = ws[f"A{current_row}"]
        c.value = tree["title"]
        c.font = _font(size=12, bold=True, color=C_WHITE)
        c.fill = _fill(tree["color"])
        c.alignment = _align(h="center")
        c.border = _border()
        ws.row_dimensions[current_row].height = 24
        current_row += 1

        # Steps in rows of 4 per row (2 rows of 4 steps each)
        steps = tree["steps"]
        for row_set in [steps[:4], steps[4:]]:
            # Labels row
            label_row = current_row
            for col_i, (label, _, bg, fg) in enumerate(row_set, start=1):
                col_letter = get_column_letter(col_i * 2 - 1)
                ws.merge_cells(f"{col_letter}{label_row}:{get_column_letter(col_i*2)}{label_row}")
                c = ws[f"{col_letter}{label_row}"]
                c.value = label
                c.font = _font(size=8, bold=True, color=C_WHITE)
                c.fill = _fill(C_NAVY)
                c.alignment = _align(h="center")
                c.border = _border()
            ws.row_dimensions[label_row].height = 16
            current_row += 1

            # Content row
            content_row = current_row
            for col_i, (_, content, bg, fg) in enumerate(row_set, start=1):
                col_letter = get_column_letter(col_i * 2 - 1)
                ws.merge_cells(f"{col_letter}{content_row}:{get_column_letter(col_i*2)}{content_row}")
                c = ws[f"{col_letter}{content_row}"]
                c.value = content
                c.font = _font(size=9, bold=False, color=fg)
                c.fill = _fill(bg)
                c.alignment = _align(h="center")
                c.border = _border()
            ws.row_dimensions[content_row].height = 60
            current_row += 1

        # Arrow connector row
        ws.merge_cells(f"A{current_row}:H{current_row}")
        arr = ws[f"A{current_row}"]
        arr.value = "▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼  ▼"
        arr.font = _font(size=8, color=tree["color"])
        arr.fill = _fill(C_LGRAY)
        arr.alignment = _align(h="center")
        ws.row_dimensions[current_row].height = 12
        current_row += 2  # spacer

    return ws


# ═══════════════════════════════════════════════════════════════════════════════
# SHEET 3 - RAPID REFERENCE CHEAT SHEET
# ═══════════════════════════════════════════════════════════════════════════════

def build_cheatsheet(wb):
    ws = wb.create_sheet("Rapid Reference")
    ws.sheet_view.showGridLines = False

    ws.merge_cells("A1:F1")
    t = ws["A1"]
    t.value = "RAPID REFERENCE: ICU CXR — KEY RULES & PATTERNS"
    t.font = _font(size=14, bold=True, color=C_WHITE)
    t.fill = _fill(C_NAVY)
    t.alignment = _align(h="center")
    t.border = _border()
    ws.row_dimensions[1].height = 28

    col_widths = [28, 30, 28, 30, 28, 30]
    for i, w in enumerate(col_widths, start=1):
        ws.column_dimensions[get_column_letter(i)].width = w

    # Section headers + key rules
    sections = [
        ("MEDIASTINAL SHIFT RULES", C_DARK_RED, [
            ("Shift TOWARD lesion",  "= COLLAPSE (volume loss pulls structures)"),
            ("Shift AWAY from lesion", "= EFFUSION / TENSION PTX (pressure pushes)"),
            ("NO shift despite large opacity", "= CONSOLIDATION, fibrothorax, mesothelioma, or balanced collapse+effusion"),
            ("Normal CXR + dyspnoea", "= THINK PE — never reassured by normal CXR"),
        ]),
        ("AIR BRONCHOGRAM KEY", C_TEAL, [
            ("Air bronchogram PRESENT", "= Alveoli full of fluid, airways open → CONSOLIDATION (pneumonia/oedema/haemorrhage)"),
            ("Air bronchogram ABSENT", "= Airways collapsed or obstructed → COLLAPSE (atelectasis)"),
            ("Bat-wing + air bronchogram + large heart", "= Cardiogenic pulmonary oedema"),
            ("Bilateral diffuse + normal heart size", "= ARDS (non-cardiogenic)"),
        ]),
        ("TRACHEA POSITION", C_PURPLE, [
            ("Trachea deviates AWAY", "= Mass/effusion PUSHES it away (same side lesion)"),
            ("Trachea deviates TOWARD", "= Collapse PULLS it toward (same side)"),
            ("Slight right deviation at aortic arch", "= NORMAL variant"),
            ("Deviation + hypotension + JVD", "= TENSION PNEUMOTHORAX — treat NOW"),
        ]),
        ("HEART SHAPE MNEMONICS", C_ORANGE, [
            ("Flask / Water-bottle", "= Pericardial effusion (tamponade)"),
            ("Boot / Sabot heart", "= Tetralogy of Fallot"),
            ("Egg on its side", "= Transposition of Great Arteries (TGA)"),
            ("Snowman / Figure-8", "= Total Anomalous Pulmonary Venous Drainage (TAPVD)"),
        ]),
        ("TUBE & LINE POSITIONS", C_BLUE, [
            ("ETT tip", "= T3-T4, 2-3cm above carina"),
            ("CVC tip", "= SVC-RA junction (not in RA = arrhythmias)"),
            ("NGT", "= Below diaphragm, curving left into stomach"),
            ("Chest drain", "= Within pleural space; confirm re-expansion"),
        ]),
        ("DO NOT MISS LIST", C_DARK_RED, [
            ("Wide mediastinum (>8cm)", "= AORTIC DISSECTION — no thrombolytics!"),
            ("Normal CXR + torn aorta risk", "= 15% dissections have normal CXR"),
            ("Post-line PTX", "= Always get CXR after subclavian/IJ lines"),
            ("NGT in bronchus", "= Remove immediately — never feed through it"),
        ]),
        ("PLEURAL EFFUSION VOLUMES", C_TEAL, [
            ("<200-300mL", "= Invisible on erect PA → use USS"),
            ("200-500mL", "= Blunting of lateral costophrenic angle"),
            ("500-1000mL", "= Meniscus sign (concave, higher laterally)"),
            (">1000mL / Massive", "= 4th anterior rib level; contralateral shift"),
        ]),
        ("CXR QUALITY CHECKLIST", C_NAVY, [
            ("Rotation", "= Clavicle heads equidistant from spinous process"),
            ("Inspiration", "= 6 anterior / 9-10 posterior ribs visible"),
            ("Projection", "= PA (standard) vs AP (portable — magnifies heart ~15%)"),
            ("Exposure", "= Vertebrae just visible through cardiac shadow"),
        ]),
    ]

    current_row = 2
    for i, (section_title, color, items) in enumerate(sections):
        col_offset = (i % 3) * 2 + 1
        if col_offset == 1 and i > 0:
            current_row += len(items) + 2

        # Section header
        r = current_row if col_offset == 1 else current_row - len(items) - 2 + (i // 3 == 0) * 0
        # Recalculate row per column group
        pass

    # Simpler layout: just stack vertically in two columns
    current_row = 2
    for section_title, color, items in sections:
        # Section title spanning both A-B
        ws.merge_cells(f"A{current_row}:B{current_row}")
        c = ws[f"A{current_row}"]
        c.value = section_title
        c.font = _font(size=10, bold=True, color=C_WHITE)
        c.fill = _fill(color)
        c.alignment = _align(h="center")
        c.border = _border()
        ws.row_dimensions[current_row].height = 20
        current_row += 1

        for key, val in items:
            c = ws[f"A{current_row}"]
            c.value = key
            c.font = _font(size=9, bold=True, color=color)
            c.fill = _fill(C_LGRAY)
            c.alignment = _align()
            c.border = _border()

            c2 = ws[f"B{current_row}"]
            c2.value = val
            c2.font = _font(size=9)
            c2.fill = _fill(C_WHITE)
            c2.alignment = _align()
            c2.border = _border()
            ws.row_dimensions[current_row].height = 30
            current_row += 1

        current_row += 1  # spacer

    # Right column: Emergency CXR sign index
    r2 = 2
    ws.merge_cells(f"D{r2}:F{r2}")
    c = ws[f"D{r2}"]
    c.value = "CLASSIC CXR SIGN INDEX"
    c.font = _font(size=12, bold=True, color=C_WHITE)
    c.fill = _fill(C_DARK_RED)
    c.alignment = _align(h="center")
    c.border = _border()
    ws.row_dimensions[r2].height = 22
    r2 += 1

    sign_headers = ["CXR SIGN", "APPEARANCE", "DIAGNOSIS"]
    for ci, h in enumerate(sign_headers, start=4):
        c = ws[f"{get_column_letter(ci)}{r2}"]
        c.value = h
        c.font = _font(size=9, bold=True, color=C_WHITE)
        c.fill = _fill(C_NAVY)
        c.alignment = _align(h="center")
        c.border = _border()
    ws.row_dimensions[r2].height = 18
    r2 += 1

    signs = [
        ("Air Bronchogram",     "White tubes within white opacity",         "Consolidation (pneumonia, oedema)"),
        ("Silhouette Sign",     "Loss of expected cardiac/diaphragm border", "Pathology adjacent to that border"),
        ("Bat-wing / Butterfly","Bilateral perihilar alveolar opacity",      "Cardiogenic pulmonary oedema"),
        ("Kerley B Lines",      "Horizontal 1-2mm lines, lung bases",        "Interstitial oedema (PCWP 18-25)"),
        ("Meniscus Sign",       "Concave fluid level, higher laterally",     "Pleural effusion"),
        ("Deep Sulcus Sign",    "Abnormally deep black costophrenic angle",  "Pneumothorax on supine film"),
        ("Water-bottle Heart",  "Globular, flask-shaped cardiac shadow",     "Pericardial effusion / tamponade"),
        ("Luftsichel Sign",     "Air crescent around aortic arch",           "Left upper lobe collapse"),
        ("Sail Sign",           "Triangular opacity behind heart",           "Left lower lobe collapse"),
        ("Hampton's Hump",      "Pleural-based wedge opacity",               "Pulmonary infarction (PE)"),
        ("Westermark Sign",     "Focal pulmonary oligaemia (black zone)",    "Pulmonary embolism"),
        ("Naclerio V Sign",     "V-shaped air at left heart-diaphragm",      "Oesophageal rupture (Boerhaave)"),
        ("Pleural Line",        "Thin white line parallel to chest wall",    "Pneumothorax (simple)"),
        ("Widened Mediastinum", ">8cm wide on PA CXR",                      "Aortic dissection / haematoma"),
        ("Eggshell Calcif.",    "Thin calcified shell around hilar nodes",   "Sarcoidosis / Silicosis"),
        ("Rib Notching",        "Inferior rib erosions (3rd-8th ribs)",      "Coarctation of aorta"),
        ("Cephalization",       "Upper lobe vessels > lower lobe vessels",   "Pulmonary venous hypertension"),
        ("Double Density",      "Two densities at right heart border",       "Left atrial enlargement"),
        ("Snowman Heart",       "Heart + venous sinus = figure-8",          "TAPVD"),
        ("Boot / Sabot",        "Upturned boot-shaped cardiac contour",      "Tetralogy of Fallot"),
    ]

    row_bgs = [C_WHITE, C_LGRAY]
    for ri, (sign, appearance, dx) in enumerate(signs):
        bg = row_bgs[ri % 2]
        for ci, val in enumerate([sign, appearance, dx], start=4):
            c = ws[f"{get_column_letter(ci)}{r2}"]
            c.value = val
            c.font = _font(size=9, bold=(ci == 4), color=(C_DARK_RED if ci == 4 else "000000"))
            c.fill = _fill(C_PINK if ci == 4 else bg)
            c.alignment = _align()
            c.border = _border()
        ws.row_dimensions[r2].height = 22
        r2 += 1

    return ws


# ═══════════════════════════════════════════════════════════════════════════════
# MAIN
# ═══════════════════════════════════════════════════════════════════════════════

def main():
    wb = Workbook()
    build_comparison_sheet(wb)
    build_decision_tree_sheet(wb)
    build_cheatsheet(wb)

    out_path = "/home/daytona/workspace/icu-cxr/ICU_CXR_Emergency_Reference.xlsx"
    wb.save(out_path)
    print(f"Saved: {out_path}")
    return out_path

if __name__ == "__main__":
    main()
!

Failed to create session: unauthorized: authentication failed: Bearer token is invalid

We encountered an error while processing your request. Please try again or reach out to us for help.

This is a shared conversation. Sign in to Orris to start your own chat.