20 most abnormal ecg in daily practice and mark the abnormal

Reading File
Finding Sources
Searching Images

abnormal ECG patterns clinical practice

Reading File
Finding Sources
Searching Images

STEMI ST elevation myocardial infarction ECG 12 lead

Searching Images

atrial fibrillation ECG irregular rhythm no P waves

Searching Images

ventricular tachycardia ventricular fibrillation ECG wide complex tachycardia

Searching Images

complete heart block third degree AV block ECG bradycardia

Searching Images

left bundle branch block LBBB right bundle branch block RBBB ECG QRS morphology

Searching Images

Wolff-Parkinson-White WPW syndrome delta wave pre-excitation ECG

Searching Images

hyperkalemia peaked T waves ECG electrolyte abnormality

Searching Images

Brugada syndrome ECG coved ST elevation V1 V2 right precordial

Searching Images

prolonged QT interval torsades de pointes ECG long QT syndrome

I now have rich image material and clinical data to compile a comprehensive guide. Let me put together the full response with annotated ECG images.

20 Most Abnormal ECGs in Daily Practice

Each entry below includes the key abnormality, what to look for, clinical significance, and real ECG images from the medical image library.

1. πŸ”΄ Anterior STEMI (LAD Occlusion)

Key Abnormalities:
  • ST elevation β‰₯1 mm (convex/tombstone) in V1–V6
  • Hyperacute peaked T-waves in V2–V4
  • Reciprocal ST depression in II, III, aVF (inferior leads)
  • Evolving Q waves in V2–V3
Clinical significance: Proximal LAD occlusion β†’ massive anterior wall infarction. Emergency PCI within 90 minutes.
Anterior STEMI
⬆️ MARKED: Red zone = ST elevation V1–V6 (tombstone morphology), with reciprocal depression in inferior leads.

2. πŸ”΄ Inferior STEMI (RCA Occlusion)

Key Abnormalities:
  • ST elevation in II, III, aVF (inferior leads)
  • Reciprocal ST depression in I, aVL (lateral leads)
  • T-wave inversion or elevation matching ischemic territory
Clinical significance: RCA or dominant LCx occlusion. Always obtain right-sided leads (V3R–V4R) to rule out concurrent right ventricular MI.
Inferior STEMI with lateral reciprocal changes
⬆️ MARKED: ST elevation in III and aVF (red arrows), ST depression and T-wave inversion in I and aVL (white arrows).

3. πŸ”΄ Atrial Fibrillation (AF)

Key Abnormalities:
  • No P waves β€” replaced by chaotic fibrillatory (f) waves (best seen in V1, II)
  • Irregularly irregular R-R intervals
  • Narrow QRS (unless aberrant conduction)
Clinical significance: Most common sustained arrhythmia. Risk of stroke, heart failure. Rate control or rhythm control required.
Atrial Fibrillation ECG
⬆️ MARKED: Absent P waves β†’ chaotic baseline, completely irregular R-R intervals throughout all leads.

4. πŸ”΄ Complete (Third-Degree) AV Block

Key Abnormalities:
  • Complete AV dissociation: P waves and QRS complexes are independent
  • Slow ventricular escape rhythm (30–50 bpm)
  • Wide QRS (ventricular escape, infra-nodal block) or narrow (junctional escape, nodal block)
  • No constant PR interval
Clinical significance: Requires urgent temporary pacing β†’ permanent pacemaker.
Complete Heart Block ECG
⬆️ MARKED: P waves (black arrows) march through at their own rate; wide QRS escape complexes appear slowly and are completely unrelated to P waves. Ventricular rate β‰ˆ30 bpm.

5. πŸ”΄ Ventricular Fibrillation (VF)

Key Abnormalities:
  • Completely chaotic, irregular waveforms β€” no identifiable P, QRS, or T waves
  • Varying amplitude and morphology
  • No organized electrical activity
Clinical significance: Fatal without immediate defibrillation. Pulseless cardiac arrest.
Ventricular Fibrillation ECG
⬆️ MARKED: After the initial normal beat, completely chaotic, polymorphic oscillations with no discernible P/QRS/T β€” this is VF.

6. πŸ”΄ Torsades de Pointes (TdP)

Key Abnormalities:
  • Polymorphic VT with "twisting" QRS complexes around the isoelectric line
  • Triggered by long QT β†’ R-on-T phenomenon
  • Short-long-short RR initiating sequence
Clinical significance: May degenerate into VF. Treat underlying long QT (stop offending drugs, Mg²⁺ IV, pacing to overdrive suppress).
Torsades de Pointes ECG
⬆️ MARKED: Wide-complex tachycardia with classic rotating/twisting QRS morphology around the baseline β€” the hallmark "twisting of the points."

7. πŸ”΄ Prolonged QT Interval / Long QT Syndrome (LQTS)

Key Abnormalities:
  • QTc >450 ms (men), >470 ms (women) β€” corrected for heart rate
  • Abnormal T-wave morphology (biphasic, notched, flat)
  • May show T-wave alternans in severe cases
Clinical significance: Risk of TdP and sudden cardiac death. Causes: congenital (channelopathy), drugs (sotalol, amiodarone, antipsychotics, azithromycin), hypokalemia, hypomagnesemia.
Long QT Syndrome ECG with Torsades
⬆️ MARKED: Panel A β€” markedly prolonged QTc (478 ms); Panel B β€” transition from prolonged QT into Torsades de Pointes.

8. πŸ”΄ Hyperkalemia

Key Abnormalities (sequential progression):
  • Early: Tall, narrow, peaked ("tented") T waves β€” narrow base, symmetric
  • Moderate: Flat or absent P waves, widened QRS
  • Severe: Sine-wave pattern β†’ VF/asystole
Clinical significance: K⁺ > 6.5 mEq/L is life-threatening. Immediate treatment: IV calcium, bicarbonate, insulin/dextrose, kayexalate, dialysis.
Hyperkalemia ECG peaked T waves
⬆️ MARKED: Tall, narrow, symmetrical tented T waves in V2–V5 (K⁺ = 8.0 mEq/L), widened QRS, absent P waves β€” classic progressive hyperkalemic changes.

9. 🟠 Wolff-Parkinson-White (WPW) Syndrome

Key Abnormalities:
  • Short PR interval (<120 ms)
  • Delta wave: slurred upstroke at start of QRS
  • Wide QRS (β‰₯120 ms)
  • Secondary ST-T changes (discordant repolarization)
Clinical significance: Accessory pathway bypassing the AV node. Risk of pre-excited AF (rapid conduction β†’ VF). Ablation is curative.
WPW ECG with delta waves
⬆️ MARKED: Red arrows in leads II and III point to delta waves (slurred upstroke); short PR, widened QRS throughout.

10. πŸ”΄ Brugada Syndrome

Key Abnormalities (Type 1 β€” diagnostic):
  • Coved ST elevation β‰₯2 mm in V1–V2 (high right precordial)
  • Convex/downward-sloping ST β†’ inverted T wave
  • Mimics RBBB in V1
Clinical significance: Sodium channelopathy (SCN5A). Risk of polymorphic VT/VF and sudden death, especially at night/fever. ICD is treatment of choice.
Brugada Syndrome Type 1 ECG
⬆️ MARKED: Coved ST elevation in V1 and V2 β€” J-point β‰₯2 mm with convex downward slope into inverted T wave. Diagnostic Type 1 pattern.

11. 🟠 Left Bundle Branch Block (LBBB)

Key Abnormalities:
  • QRS β‰₯120 ms (broad complex)
  • Broad, notched R wave in I, aVL, V5, V6 (lateral leads)
  • Deep S or QS in V1
  • No septal Q waves in lateral leads
  • Discordant ST-T changes (ST opposite to QRS)
Clinical significance: New LBBB in chest pain = STEMI equivalent (Sgarbossa criteria). May indicate structural heart disease, CRT indication in HF.
LBBB and RBBB alternating ECG
⬆️ MARKED: Beat-to-beat alternation β€” one beat shows RBBB (rsR' in V1), the next shows LBBB (notched R in lateral leads). This is alternating bundle branch block β€” a high-risk pattern requiring pacemaker.

12. 🟑 Right Bundle Branch Block (RBBB)

Key Abnormalities:
  • QRS β‰₯120 ms
  • rSR' ("rabbit ears") pattern in V1–V2
  • Broad, slurred S wave in I, V5, V6
  • Secondary T-wave inversion in V1–V3
Clinical significance: Often incidental. New RBBB with anterior MI: indicates proximal LAD disease. Isolated RBBB associated with 50% increased 20-year mortality risk.

13. 🟑 Second-Degree AV Block β€” Mobitz Type I (Wenckebach)

Key Abnormalities:
  • Progressive PR prolongation until a QRS is dropped (non-conducted P wave)
  • After the dropped beat, PR resets to shortest
  • Grouped beating pattern
  • Usually narrow QRS
Clinical significance: Often benign (AV nodal disease), seen in athletes, inferior MI. Rarely needs pacing unless symptomatic.

14. πŸ”΄ Second-Degree AV Block β€” Mobitz Type II

Key Abnormalities:
  • Fixed PR interval before sudden dropped QRS (no warning)
  • Often wide QRS (infra-nodal block)
  • 2:1 or 3:1 conduction ratio possible
Clinical significance: High risk of progressing to complete heart block. Pacemaker indicated.

15. 🟠 Left Ventricular Hypertrophy (LVH)

Key Abnormalities (Sokolow-Lyon criteria):
  • S in V1 + R in V5 or V6 > 35 mm
  • Tall R in aVL > 11 mm
  • Strain pattern: ST depression + T-wave inversion in lateral leads (I, aVL, V5, V6)
  • Left axis deviation
Clinical significance: Associated with hypertension, aortic stenosis, HCM. LVH with strain = increased cardiovascular risk.

16. 🟠 Pericarditis

Key Abnormalities:
  • Diffuse saddle-shaped ST elevation in multiple leads (not territory-specific)
  • PR depression (most specific finding β€” opposite to P-wave polarity)
  • Reciprocal changes only in aVR and V1
  • No reciprocal ST depression in other leads
Clinical significance: Distinguish from STEMI (diffuse vs. territorial, PR depression, no reciprocal changes). Treat with NSAIDs + colchicine.

17. 🟑 AF with Rapid Ventricular Response (AF-RVR)

Key Abnormalities:
  • All features of AF (irregularly irregular, no P waves)
  • Heart rate > 100–150 bpm
Clinical significance: Hemodynamically destabilizing. Rate control with beta-blockers, diltiazem, or digoxin.
AF with fast ventricular response
⬆️ MARKED: Rapid irregular rhythm (~126 bpm), absent P waves replaced by fine fibrillatory baseline β€” AF with rapid ventricular response.

18. 🟠 Right Heart Strain (Massive Pulmonary Embolism)

Key Abnormalities (S1Q3T3 pattern):
  • S wave in lead I
  • Q wave in lead III
  • T-wave inversion in lead III
  • Right axis deviation, incomplete RBBB
  • Sinus tachycardia (most common finding)
  • T-wave inversion V1–V4 (right ventricular strain)
Clinical significance: Massive PE with right heart strain. Requires urgent anticoagulation Β± thrombolysis/thrombectomy.

19. 🟑 Atrial Flutter

Key Abnormalities:
  • Regular "sawtooth" flutter waves at 250–350/min (best in II, III, aVF)
  • No isoelectric baseline between flutter waves
  • Typically 2:1 or 4:1 block (ventricular rate ~150 bpm for 2:1)
Clinical significance: Often presents as regular tachycardia at exactly 150 bpm. Rate control, cardioversion, or catheter ablation.

20. 🟑 Digoxin Toxicity / Digoxin Effect

Key Abnormalities:
  • "Scooped" or "reverse tick" ST depression in lateral leads
  • Shortened QT interval (therapeutic effect)
  • At toxicity: Any arrhythmia possible β€” PAT with block, PVCs, bidirectional VT, junctional rhythms, bradycardia
  • AV block
Clinical significance: Narrow therapeutic window. Toxic levels cause life-threatening arrhythmias. Treat with digoxin-specific antibody fragments (DigiFab).

Summary Table

#AbnormalityKey ECG FindingUrgency
1Anterior STEMIST elevation V1–V6, tombstoneπŸ”΄ STAT
2Inferior STEMIST elevation II, III, aVF + reciprocalπŸ”΄ STAT
3Atrial FibrillationNo P waves, irregularly irregularπŸ”΄/🟠 Urgent
4Complete AV BlockAV dissociation, escape rhythmπŸ”΄ STAT
5Ventricular FibrillationChaotic, no QRSπŸ”΄ SHOCK NOW
6Torsades de PointesTwisting polymorphic VTπŸ”΄ STAT
7Long QT SyndromeQTc >450/470 ms, T-wave changesπŸ”΄ Urgent
8HyperkalemiaPeaked T waves β†’ sine waveπŸ”΄ STAT
9WPWDelta wave, short PR, wide QRS🟠 Urgent
10Brugada SyndromeCoved ST elevation V1–V2πŸ”΄ Urgent
11LBBBBroad notched R lateral, QS V1🟠 Important
12RBBBrSR' V1, broad S in lateral🟑 Note
13Mobitz Type IProgressive PR β†’ dropped beat🟑 Monitor
14Mobitz Type IIFixed PR β†’ dropped beat, wide QRSπŸ”΄ Urgent
15LVH + StrainVoltage criteria + lateral ST depression🟠 Important
16PericarditisDiffuse saddle ST + PR depression🟠 Urgent
17AF-RVRAF at >100–150 bpm🟠 Urgent
18Massive PE (S1Q3T3)S1Q3T3, RV strain, tachycardiaπŸ”΄ Urgent
19Atrial FlutterSawtooth flutter waves, 150 bpm🟠 Urgent
20Digoxin ToxicityScooped ST, any arrhythmiaπŸ”΄ Urgent

Color coding: πŸ”΄ Life-threatening emergency | 🟠 Urgent management needed | 🟑 Requires monitoring/workup
Each ECG pattern above requires systematic assessment: rate β†’ rhythm β†’ axis β†’ intervals (PR, QRS, QT) β†’ ST-T morphology β†’ specific pattern recognition. Correlation with clinical context is always mandatory before acting on any single ECG finding.

Md theory final exam all systems questions and answers mind map

Asking for Preferences
Asking for Preferences
Reading File
Running Command

mkdir -p /home/daytona/workspace/md-exam-mindmap && ls /home/daytona/workspace/m…

Writing File

~/md-exam-mindmap/generate_mindmap.py

#!/usr/bin/env python3
"""
MD Theory Final Exam - All Systems Q&A Mind Map PDF Generator
Comprehensive, beautifully formatted multi-page PDF
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    PageBreak, HRFlowable, KeepTogether
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus.flowables import Flowable
from reportlab.graphics.shapes import Drawing, Rect, String, Line, Circle
from reportlab.graphics import renderPDF
import os

OUTPUT_PATH = "/home/daytona/workspace/md-exam-mindmap/MD_Final_Exam_MindMap.pdf"

# ─────────────────────────── COLOUR PALETTE ──────────────────────────────────
DARK_BG      = colors.HexColor("#0D1B2A")
ACCENT_BLUE  = colors.HexColor("#1E88E5")
ACCENT_TEAL  = colors.HexColor("#00ACC1")
ACCENT_GREEN = colors.HexColor("#43A047")
ACCENT_RED   = colors.HexColor("#E53935")
ACCENT_AMBER = colors.HexColor("#FB8C00")
ACCENT_PURPLE= colors.HexColor("#8E24AA")
ACCENT_PINK  = colors.HexColor("#D81B60")
LIGHT_GREY   = colors.HexColor("#F5F5F5")
MID_GREY     = colors.HexColor("#E0E0E0")
TEXT_DARK    = colors.HexColor("#1A1A2E")
TEXT_MUTED   = colors.HexColor("#546E7A")
WHITE        = colors.white

SYSTEM_COLORS = {
    "Cardiovascular":    colors.HexColor("#E53935"),
    "Respiratory":       colors.HexColor("#1E88E5"),
    "Gastrointestinal":  colors.HexColor("#43A047"),
    "Renal & Urology":   colors.HexColor("#00ACC1"),
    "Neurology":         colors.HexColor("#8E24AA"),
    "Endocrine":         colors.HexColor("#FB8C00"),
    "Hematology":        colors.HexColor("#D81B60"),
    "Musculoskeletal":   colors.HexColor("#5D4037"),
    "Reproductive":      colors.HexColor("#F06292"),
    "Immunology":        colors.HexColor("#00897B"),
    "Psychiatry":        colors.HexColor("#3949AB"),
    "Pharmacology":      colors.HexColor("#7CB342"),
}

# ────────────────────────── STYLES ───────────────────────────────────────────
def make_styles():
    s = getSampleStyleSheet()

    cover_title = ParagraphStyle(
        "CoverTitle", fontName="Helvetica-Bold", fontSize=32,
        textColor=WHITE, alignment=TA_CENTER, leading=40, spaceAfter=8)

    cover_sub = ParagraphStyle(
        "CoverSub", fontName="Helvetica", fontSize=16,
        textColor=colors.HexColor("#B0BEC5"), alignment=TA_CENTER, leading=22, spaceAfter=6)

    cover_detail = ParagraphStyle(
        "CoverDetail", fontName="Helvetica", fontSize=12,
        textColor=colors.HexColor("#78909C"), alignment=TA_CENTER, leading=18)

    sys_title = ParagraphStyle(
        "SysTitle", fontName="Helvetica-Bold", fontSize=22,
        textColor=WHITE, alignment=TA_CENTER, leading=28, spaceAfter=4)

    section_hdr = ParagraphStyle(
        "SectionHdr", fontName="Helvetica-Bold", fontSize=13,
        textColor=WHITE, alignment=TA_LEFT, leading=18,
        leftIndent=6, spaceAfter=4, spaceBefore=6)

    q_style = ParagraphStyle(
        "Question", fontName="Helvetica-Bold", fontSize=10.5,
        textColor=TEXT_DARK, leading=15, spaceAfter=2, spaceBefore=4,
        leftIndent=8)

    a_style = ParagraphStyle(
        "Answer", fontName="Helvetica", fontSize=10,
        textColor=colors.HexColor("#1B5E20"), leading=14, spaceAfter=3,
        leftIndent=18)

    key_style = ParagraphStyle(
        "Key", fontName="Helvetica-BoldOblique", fontSize=9.5,
        textColor=colors.HexColor("#BF360C"), leading=13, spaceAfter=2,
        leftIndent=18)

    toc_entry = ParagraphStyle(
        "TOCEntry", fontName="Helvetica", fontSize=12,
        textColor=TEXT_DARK, leading=20, leftIndent=20)

    toc_title = ParagraphStyle(
        "TOCTitle", fontName="Helvetica-Bold", fontSize=18,
        textColor=ACCENT_BLUE, alignment=TA_CENTER, leading=26, spaceAfter=12)

    tip_style = ParagraphStyle(
        "Tip", fontName="Helvetica-Oblique", fontSize=9,
        textColor=colors.HexColor("#455A64"), leading=13, spaceAfter=2,
        leftIndent=18)

    return dict(
        cover_title=cover_title, cover_sub=cover_sub, cover_detail=cover_detail,
        sys_title=sys_title, section_hdr=section_hdr,
        q=q_style, a=a_style, key=key_style, toc=toc_entry, toc_title=toc_title, tip=tip_style
    )

# ────────────────────────── COVER PAGE ───────────────────────────────────────
class ColorBackground(Flowable):
    def __init__(self, width, height, color):
        super().__init__()
        self.width = width
        self.height = height
        self.bg = color

    def draw(self):
        self.canv.setFillColor(self.bg)
        self.canv.rect(0, 0, self.width, self.height, fill=1, stroke=0)

def cover_page(styles, W, H):
    elems = []
    # Dark background
    elems.append(ColorBackground(W, H, DARK_BG))
    elems.append(Spacer(1, 3.5*cm))

    # Decorative coloured bar
    bar_data = [["" for _ in range(12)]]
    bar_style = TableStyle([
        ('BACKGROUND', (i, 0), (i, 0), list(SYSTEM_COLORS.values())[i]) for i in range(12)
    ] + [('ROWBACKGROUNDS', (0,0), (-1,-1), [c for c in SYSTEM_COLORS.values()]),
         ('LINEABOVE', (0,0), (-1,-1), 0, colors.transparent),
         ('LINEBELOW', (0,0), (-1,-1), 0, colors.transparent)])
    bar_tbl = Table(bar_data, colWidths=[W/12]*12, rowHeights=[10])
    bar_tbl.setStyle(bar_style)
    elems.append(bar_tbl)
    elems.append(Spacer(1, 1.2*cm))

    elems.append(Paragraph("MD Theory Final Exam", styles["cover_title"]))
    elems.append(Spacer(1, 0.3*cm))
    elems.append(Paragraph("All Systems β€” Questions & Answers Mind Map", styles["cover_sub"]))
    elems.append(Spacer(1, 0.5*cm))

    # System pills row
    pill_data = [[Paragraph(f'<font color="white">β–  {s}</font>', ParagraphStyle(
        "pill", fontName="Helvetica", fontSize=7.5, textColor=WHITE, alignment=TA_CENTER))
        for s in ["Cardiovascular", "Respiratory", "GI", "Renal", "Neurology", "Endocrine"]]]
    pill_tbl = Table(pill_data, colWidths=[W/6]*6, rowHeights=[18])
    pill_tbl.setStyle(TableStyle([
        ('BACKGROUND', (i,0),(i,0), list(SYSTEM_COLORS.values())[i]) for i in range(6)
    ] + [('TOPPADDING',(0,0),(-1,-1),3),('BOTTOMPADDING',(0,0),(-1,-1),3),
         ('ROUNDEDCORNERS',[3])]))
    elems.append(pill_tbl)
    elems.append(Spacer(1, 0.3*cm))

    pill_data2 = [[Paragraph(f'<font color="white">β–  {s}</font>', ParagraphStyle(
        "pill2", fontName="Helvetica", fontSize=7.5, textColor=WHITE, alignment=TA_CENTER))
        for s in ["Hematology", "MSK", "Reproductive", "Immunology", "Psychiatry", "Pharmacology"]]]
    pill_tbl2 = Table(pill_data2, colWidths=[W/6]*6, rowHeights=[18])
    pill_tbl2.setStyle(TableStyle([
        ('BACKGROUND', (i,0),(i,0), list(SYSTEM_COLORS.values())[i+6]) for i in range(6)
    ] + [('TOPPADDING',(0,0),(-1,-1),3),('BOTTOMPADDING',(0,0),(-1,-1),3)]))
    elems.append(pill_tbl2)
    elems.append(Spacer(1, 1.5*cm))

    elems.append(HRFlowable(width="70%", thickness=1, color=colors.HexColor("#37474F"),
                            hAlign='CENTER'))
    elems.append(Spacer(1, 0.8*cm))
    elems.append(Paragraph("Comprehensive High-Yield Study Reference", styles["cover_detail"]))
    elems.append(Paragraph("Theory Exam Preparation Β· All Years Combined", styles["cover_detail"]))
    elems.append(Spacer(1, 0.5*cm))
    elems.append(Paragraph("12 Systems Β· 200+ Q&A Β· Clinical Pearls", styles["cover_detail"]))
    elems.append(PageBreak())
    return elems

# ────────────────────────── Q&A DATABASE ─────────────────────────────────────
QA_DATA = {
    "Cardiovascular": {
        "color": SYSTEM_COLORS["Cardiovascular"],
        "topics": {
            "Heart Failure": [
                ("What are the classic signs of left-sided heart failure?",
                 "Dyspnea, orthopnea, PND, pulmonary oedema, S3 gallop, pink frothy sputum.",
                 "Backward failure β†’ pulmonary venous congestion"),
                ("What are the signs of right-sided heart failure?",
                 "JVD, peripheral oedema, hepatomegaly, ascites, tricuspid regurgitation.",
                 "Backward failure β†’ systemic venous congestion"),
                ("What is the Starling curve and how does it apply to HF?",
                 "SV increases with preload up to an optimum; in HF, the curve is depressed and flat β€” increased preload gives diminishing returns.",
                 "HFrEF: EF <40%; HFpEF: EF β‰₯50%"),
                ("Name 4 drug classes proven to reduce mortality in HFrEF.",
                 "ACE inhibitors/ARBs/ARNi, Beta-blockers (carvedilol, metoprolol), MRA (spironolactone), SGLT2 inhibitors (dapagliflozin).",
                 "RAAS + neurohumoral blockade is the cornerstone"),
                ("What is the New York Heart Association (NYHA) classification?",
                 "Class I: No symptoms on ordinary activity. II: Mild on ordinary activity. III: Marked on less than ordinary. IV: Symptoms at rest.",
                 "Used to guide therapy escalation"),
            ],
            "Ischemic Heart Disease": [
                ("What ECG changes occur in STEMI vs NSTEMI?",
                 "STEMI: ST elevation β‰₯1mm (β‰₯2mm in V1-V3), new LBBB. NSTEMI: ST depression, T-wave inversion, or normal ECG β€” diagnosed by troponin rise.",
                 "Troponin I/T peaks at 12-24h; hs-cTn detectable in 3h"),
                ("What is the treatment algorithm for STEMI?",
                 "Aspirin + P2Y12 inhibitor (ticagrelor/clopidogrel) + anticoagulant. Primary PCI within 90 min (door-to-balloon). Thrombolysis if PCI not available within 120 min.",
                 "MONA: Morphine, Oxygen, Nitrates, Aspirin β€” now evidence-questioned; O2 only if SpO2 <90%"),
                ("What is Dressler's syndrome?",
                 "Post-MI pericarditis (2-10 weeks after MI): fever, pleuritic chest pain, pericardial friction rub. Autoimmune mechanism. Treat with NSAIDs + colchicine.",
                 "Distinct from early post-MI pericarditis (day 1-3)"),
                ("Describe the pathophysiology of acute coronary syndrome.",
                 "Atherosclerotic plaque rupture β†’ platelet aggregation β†’ thrombus formation β†’ partial (NSTEMI/UA) or complete (STEMI) coronary occlusion.",
                 "Vulnerable plaque: thin fibrous cap, lipid-rich core"),
                ("What are the Killip classes in MI?",
                 "I: No HF. II: Mild HF (rales <50% lung, S3). III: Acute pulmonary oedema. IV: Cardiogenic shock (BP <90, oliguria).",
                 "Killip IV mortality >80% without aggressive therapy"),
            ],
            "Arrhythmias": [
                ("What is the mechanism of AF and how is it managed?",
                 "Disorganised atrial electrical activity (multiple re-entrant wavelets). Rate control (beta-blocker/diltiazem) or rhythm control (cardioversion/amiodarone). Anticoagulate if CHAβ‚‚DSβ‚‚-VASc β‰₯2.",
                 "CHAβ‚‚DSβ‚‚-VASc: CHF, HTN, Ageβ‰₯75(Γ—2), DM, Stroke(Γ—2), Vascular, Age65-74, Sex(female)"),
                ("What is the difference between Mobitz I and II?",
                 "Mobitz I (Wenckebach): Progressive PR prolongation β†’ dropped QRS. Nodal, usually benign. Mobitz II: Fixed PR β†’ sudden dropped QRS. Infra-nodal, requires pacemaker.",
                 "Mobitz II β†’ high risk complete heart block"),
                ("How do you manage SVT acutely?",
                 "Vagal manoeuvres first. If failed: IV adenosine (6mg rapid bolus, then 12mg). Unstable: synchronised DC cardioversion.",
                 "Adenosine TΒ½ = 10 sec; warn patient of brief chest pain"),
                ("What is WPW and why is it dangerous?",
                 "Accessory pathway (Bundle of Kent) bypasses AV node causing pre-excitation. Dangerous in AF: rapid anterograde conduction can cause VF. Avoid AV blockers (adenosine, digoxin, verapamil) in WPW+AF.",
                 "ECG: short PR, delta wave, wide QRS"),
            ],
            "Valvular Disease": [
                ("What are the features of mitral stenosis?",
                 "Opening snap after S2, mid-diastolic rumbling murmur at apex. Causes AF, pulmonary HTN, haemoptysis. Cause: rheumatic fever.",
                 "Mnemonic: MS β†’ 'Opens' β†’ opening snap"),
                ("Compare aortic stenosis and regurgitation.",
                 "AS: Ejection systolic murmur radiating to neck, slow-rising pulse, syncope/angina/dyspnea triad. AR: Early diastolic murmur, collapsing pulse (water hammer), wide pulse pressure, Austin Flint murmur.",
                 "AS: calculate valve area (normal >2 cmΒ²; severe <1 cmΒ²)"),
                ("What is Infective Endocarditis (IE) diagnostic criteria?",
                 "Duke criteria: 2 major, or 1 major + 3 minor, or 5 minor. Major: positive blood cultures (typical organisms Γ—2), echo evidence. Minor: predisposing condition, fever, vascular/embolic phenomena, immunologic phenomena.",
                 "Most common organism: S. viridans (native); S. aureus (IV drug user/prosthetic)"),
            ],
            "Hypertension": [
                ("Define hypertension and its stages.",
                 "Normal <120/80. Elevated 120-129/<80. Stage 1: 130-139/80-89. Stage 2: β‰₯140/β‰₯90. Hypertensive crisis: >180/120.",
                 "JNC8/ACC-AHA 2017 guidelines"),
                ("What are secondary causes of hypertension?",
                 "Renal: Renovascular HTN (renal artery stenosis), chronic kidney disease. Endocrine: Phaeochromocytoma, primary hyperaldosteronism (Conn's), Cushing's, hyperthyroidism. Other: coarctation of aorta, OSA.",
                 "Suspect secondary HTN if young, refractory, or abrupt onset"),
            ],
        }
    },

    "Respiratory": {
        "color": SYSTEM_COLORS["Respiratory"],
        "topics": {
            "Obstructive Lung Disease": [
                ("What is the spirometric definition of COPD?",
                 "Post-bronchodilator FEV₁/FVC <0.70 (fixed ratio). GOLD classification by FEV₁% predicted: GOLD 1 β‰₯80%, 2 50-79%, 3 30-49%, 4 <30%.",
                 "Key: irreversible (fixed) obstruction vs. reversible in asthma"),
                ("How does asthma differ from COPD pathophysiologically?",
                 "Asthma: eosinophilic/Th2 inflammation, reversible bronchospasm, atopy. COPD: neutrophilic/macrophage inflammation, irreversible obstruction, emphysema + chronic bronchitis, smoking-related.",
                 "Overlap (ACOS): features of both β€” treat as asthma first"),
                ("What is the stepwise management of asthma?",
                 "Step 1: SABA PRN. Step 2: + low-dose ICS. Step 3: + LABA or increase ICS. Step 4: Medium/high ICS + LABA. Step 5: Biologics (omalizumab, mepolizumab) + oral steroids.",
                 "SMART therapy: ICS/formoterol for maintenance AND relief"),
                ("Define status asthmaticus and its management.",
                 "Severe asthma unresponsive to initial bronchodilators. Manage: high-flow O2, nebulised salbutamol (continuous), IV magnesium sulfate, systemic steroids, IV aminophylline, ICU/intubation if refractory.",
                 "Silent chest + confusion = near-fatal β€” immediate ICU"),
            ],
            "Pneumonia": [
                ("What is the CURB-65 score?",
                 "Confusion, Urea >7, RR β‰₯30, BP <90/60, Age β‰₯65. Score 0-1: outpatient. Score 2: hospital. Score 3-5: ICU consider.",
                 "Alternatively use PSI/PORT score for more precise risk"),
                ("What organisms cause atypical pneumonia?",
                 "Mycoplasma pneumoniae, Legionella pneumophila, Chlamydophila pneumoniae. Features: gradual onset, dry cough, extrapulmonary features, patchy infiltrates, low WBC.",
                 "Legionella: hyponatraemia, liver dysfunction, high LDH β€” treat with fluoroquinolone/azithromycin"),
                ("How does aspiration pneumonia differ from aspiration pneumonitis?",
                 "Pneumonitis: chemical injury from acid aspiration, self-limiting, no antibiotics needed. Pneumonia: bacterial infection after aspiration, requires antibiotics covering anaerobes.",
                 "Risk factors: LOC, dysphagia, alcoholism, GERD"),
            ],
            "Pleural Disease": [
                ("How do you classify pleural effusions?",
                 "Light's criteria: exudate if ANY of β€” pleural:serum protein >0.5, pleural:serum LDH >0.6, pleural LDH >2/3 upper limit of serum. Transudate: HF, cirrhosis, nephrotic syndrome. Exudate: pneumonia, malignancy, PE, TB.",
                 "Most common cause transudate = HF; exudate = malignancy"),
                ("What is a tension pneumothorax and how is it managed?",
                 "Air in pleural space with one-way valve β†’ increasing tension β†’ mediastinal shift, tracheal deviation AWAY from lesion, absent breath sounds, JVD, haemodynamic collapse. Immediate needle decompression (2nd ICS mid-clavicular), then chest drain.",
                 "NEVER delay for X-ray if tension suspected"),
            ],
            "Pulmonary Embolism": [
                ("What is the Wells score for PE?",
                 "Clinical signs DVT (+3), PE #1 diagnosis (+3), HR>100 (+1.5), immobility/surgery (+1.5), prior DVT/PE (+1.5), haemoptysis (+1), malignancy (+1). >4 = likely; ≀4 = unlikely.",
                 "Wells ≀4 + negative D-dimer = PE excluded; Wells >4 = CTPA"),
                ("What is the management algorithm for massive PE?",
                 "Haemodynamic instability (BP <90, RV failure) β†’ systemic thrombolysis (alteplase 100mg over 2h) or surgical embolectomy. Anticoagulate with UFH first.",
                 "Submassive PE (RV strain, elevated troponin): consider catheter-directed thrombolysis"),
            ],
            "Lung Cancer": [
                ("Classify lung cancer and its clinical associations.",
                 "SCLC: central, smoking, ACTH/ADH paraneoplastic, very chemo-sensitive. NSCLC: Adenocarcinoma (peripheral, non-smokers, EGFR/ALK mutations), Squamous (central, hypercalcaemia via PTHrP, cavitation), Large cell.",
                 "SCLC: Lambert-Eaton (anti-VGCC), SIADH, Cushing's"),
                ("What are paraneoplastic syndromes in lung cancer?",
                 "Squamous: hypercalcaemia (PTHrP). SCLC: SIADH (ADH), Cushing's (ACTH), Lambert-Eaton (VGCC ab). Adenocarcinoma: hypertrophic osteoarthropathy, DVT (Trousseau).",
                 "Finger clubbing is most common paraneoplastic sign"),
            ],
        }
    },

    "Gastrointestinal": {
        "color": SYSTEM_COLORS["Gastrointestinal"],
        "topics": {
            "Upper GI": [
                ("What is the difference between peptic ulcer and GERD?",
                 "PUD: mucosal break >5mm in stomach (GU) or duodenum (DU) due to H. pylori or NSAIDs. GERD: reflux of acid causing heartburn, regurgitation, without ulceration (though erosive oesophagitis may occur).",
                 "H. pylori: urease test, breath test, stool antigen β€” treat with triple therapy"),
                ("What are the complications of peptic ulcer disease?",
                 "Haemorrhage (most common β€” melaena/haematemesis), perforation (acute abdomen, free air under diaphragm), gastric outlet obstruction (pyloric stenosis), malignant transformation (gastric ulcers only).",
                 "Rockford score for upper GI bleed risk stratification"),
                ("Describe the pathophysiology of H. pylori infection.",
                 "Gram-negative spiral bacterium. Produces urease β†’ NH3 β†’ neutralises acid locally, allows survival. Causes gastritis β†’ increased gastrin β†’ increased acid β†’ DU. Damages mucosa directly β†’ GU.",
                 "H. pylori is a WHO Group 1 carcinogen for gastric adenocarcinoma"),
            ],
            "Lower GI": [
                ("Compare Crohn's disease and ulcerative colitis.",
                 "CD: transmural inflammation, skip lesions, anywhere mouth to anus, cobblestone, fistulae, strictures, non-caseating granulomas. UC: mucosal inflammation, continuous from rectum upward, pseudopolyps, crypt abscesses.",
                 "Extraintestinal: eyes (uveitis), skin (EN, PG), joints (arthritis), liver (PSC β€” mostly UC)"),
                ("What are the complications of cirrhosis?",
                 "Portal HTN β†’ oesophageal varices (haemorrhage), ascites, splenomegaly. Hepatic encephalopathy (ammonia), spontaneous bacterial peritonitis (SBP), hepatorenal syndrome, hepatocellular carcinoma, coagulopathy.",
                 "Child-Pugh and MELD scores for severity and transplant listing"),
                ("What is the Child-Pugh scoring system?",
                 "Score: Bilirubin, Albumin, PT/INR, Ascites, Encephalopathy. Class A (5-6): well-compensated. Class B (7-9): significant impairment. Class C (10-15): decompensated cirrhosis.",
                 "MELD score = 3.78Γ—ln(bilirubin)+11.2Γ—ln(INR)+9.57Γ—ln(creatinine)+6.43"),
            ],
            "Hepatology": [
                ("What are the causes of acute liver failure (ALF)?",
                 "Paracetamol overdose (most common in UK/US), viral hepatitis (HAV, HBV, HEV), Wilson's disease, Budd-Chiari, autoimmune hepatitis, Amanita phalloides poisoning, drug reactions.",
                 "NAC (N-acetylcysteine) is treatment of paracetamol toxicity"),
                ("Describe hepatic encephalopathy grading and management.",
                 "Grade 0: No symptoms. I: Mild confusion. II: Drowsy, asterixis. III: Stupor, incoherent. IV: Coma. Manage: identify precipitant, lactulose (acidifies colon, traps NH4+), rifaximin.",
                 "Precipitants: GI bleed, infection, constipation, electrolyte imbalance, sedatives"),
                ("What is the approach to jaundice?",
                 "Pre-hepatic: haemolysis (unconjugated ↑). Hepatic: hepatocellular damage β€” both fractions rise, LFTs abnormal. Post-hepatic: obstruction β€” conjugated ↑, ALP/GGT markedly elevated, pale stools, dark urine.",
                 "Always check USS abdomen first for biliary dilatation"),
            ],
            "Pancreas": [
                ("What is the Revised Atlanta classification of acute pancreatitis?",
                 "Mild: no organ failure, no local complications. Moderately severe: transient organ failure (<48h) or local complications. Severe: persistent organ failure (>48h).",
                 "Glasgow/Ranson/APACHE II scores assess severity"),
                ("What are the causes and management of acute pancreatitis?",
                 "Causes: GET SMASHED β€” Gallstones (most common), Ethanol (2nd), Trauma, Steroids, Mumps, Autoimmune, Scorpion/snake venom, Hyperlipidaemia/Hypercalcaemia/Hypothermia, ERCP/Emboli, Drugs.",
                 "Treatment: aggressive IV fluids, analgesia (IV opioids), NBM, monitor for complications"),
            ],
        }
    },

    "Renal & Urology": {
        "color": SYSTEM_COLORS["Renal & Urology"],
        "topics": {
            "Acute Kidney Injury": [
                ("What are the KDIGO stages of AKI?",
                 "Stage 1: Creatinine Γ—1.5-1.9 baseline or rise β‰₯0.3 mg/dL within 48h, or UO <0.5 ml/kg/h for 6-12h. Stage 2: Γ—2-2.9 or UO <0.5 ml/kg/h for β‰₯12h. Stage 3: Γ—3 or creatinine β‰₯4 mg/dL, or UO <0.3 ml/kg/h for β‰₯24h, or RRT needed.",
                 "Pre-renal (most common) β†’ Intra-renal β†’ Post-renal"),
                ("How do you differentiate pre-renal from intrinsic AKI?",
                 "Pre-renal: FeNa <1%, urine Na <20, urine osmolality >500, urine:plasma creatinine >40, responds to fluid. Intrinsic (ATN): FeNa >2%, urine Na >40, isosthenuria, muddy casts.",
                 "FeNa = (urine Na Γ— plasma Cr)/(plasma Na Γ— urine Cr) Γ— 100"),
                ("What are indications for emergency dialysis?",
                 "AEIOU: Acidosis (pH <7.1), Electrolytes (K+ >6.5), Intoxication (methanol, ethylene glycol, salicylates, lithium), Overload (pulmonary oedema refractory), Uraemia (pericarditis, encephalopathy).",
                 "Remember: dialysis removes drugs with low protein binding and low volume of distribution"),
            ],
            "Chronic Kidney Disease": [
                ("What are the GFR stages of CKD?",
                 "G1: β‰₯90 (normal/high). G2: 60-89 (mildly decreased). G3a: 45-59. G3b: 30-44. G4: 15-29 (severely decreased). G5: <15 (kidney failure). Always add albuminuria staging (A1/A2/A3).",
                 "CKD defined by abnormalities β‰₯3 months in duration"),
                ("What are the complications of CKD?",
                 "Anaemia (↓EPO), renal osteodystrophy (↑PTH, ↓calcitriol, hyperphosphataemia), HTN, metabolic acidosis, hyperkalaemia, uraemic syndrome (encephalopathy, pericarditis), accelerated CVD.",
                 "Treat with EPO, phosphate binders, calcitriol, ACE inhibitor/ARB"),
            ],
            "Glomerulonephritis": [
                ("What is nephrotic vs nephritic syndrome?",
                 "Nephrotic: proteinuria >3.5g/day, hypoalbuminaemia, oedema, hyperlipidaemia, lipiduria. Causes: MCNS, FSGS, membranous, diabetic nephropathy. Nephritic: haematuria (RBC casts), HTN, oliguria, mild proteinuria. Causes: IgA nephropathy, PSGN, lupus nephritis, anti-GBM.",
                 "Mnemonic β€” Nephrotic = No blood (proteinuria dominant); Nephritic = bloody (haematuria dominant)"),
                ("What is IgA nephropathy (Berger's disease)?",
                 "Most common GN worldwide. IgA deposits in mesangium. Presents with episodic macroscopic haematuria following mucosal infection (synpharyngitic). Slowly progressive β€” 25% reach ESRD at 20 years.",
                 "Treatment: RAAS blockade + immunosuppression for proteinuric/progressive cases"),
            ],
            "Acid-Base": [
                ("Summarise the approach to ABG interpretation.",
                 "1. pH: acidosis <7.35, alkalosis >7.45. 2. PaCO2: respiratory cause. 3. HCO3-: metabolic cause. 4. Assess compensation. 5. If metabolic acidosis: calculate anion gap (Na-Cl-HCO3, normal 8-12).",
                 "High AG acidosis: MUDPILES β€” Methanol, Uraemia, DKA, Propylene glycol, Isoniazid/Iron, Lactic acidosis, Ethylene glycol, Salicylates"),
                ("What is the Henderson-Hasselbalch equation and its clinical application?",
                 "pH = 6.1 + log([HCO3-] / 0.03 Γ— PaCO2). Clinical use: determines primary disturbance and adequacy of compensation. Expected PaCO2 in metabolic acidosis = (1.5 Γ— HCO3-) + 8 Β± 2 (Winter's formula).",
                 "Compensation is NEVER complete (overshooting would change primary diagnosis)"),
            ],
        }
    },

    "Neurology": {
        "color": SYSTEM_COLORS["Neurology"],
        "topics": {
            "Stroke": [
                ("What is the time-critical management of ischaemic stroke?",
                 "Thrombolysis (IV alteplase 0.9 mg/kg) within 4.5h of symptom onset. Mechanical thrombectomy (large vessel occlusion) within 24h. Aspirin 300mg after haemorrhage excluded. Admit to stroke unit.",
                 "FAST: Face, Arms, Speech, Time. BP target: <185/110 before thrombolysis"),
                ("How do you distinguish haemorrhagic from ischaemic stroke?",
                 "CT head (non-contrast) IMMEDIATELY: haemorrhage = hyperdense lesion. Ischaemic = normal initially (infarct visible 24-48h). Clinical: haemorrhagic β€” sudden severe headache, vomiting, rapid loss of consciousness.",
                 "Never give thrombolytics before excluding haemorrhage"),
                ("What are the lacunar infarct syndromes?",
                 "Pure motor hemiplegia (posterior limb internal capsule/pons), pure sensory stroke (thalamus), sensorimotor stroke, ataxic hemiparesis, dysarthria-clumsy hand syndrome.",
                 "Lacunar infarcts: small vessel disease, HTN β€” no cortical features"),
            ],
            "Seizures & Epilepsy": [
                ("How is status epilepticus managed?",
                 "0-5 min: IV/IM lorazepam (0.1 mg/kg). 5-20 min: IV levetiracetam, valproate, or phenytoin. 20-40 min: anaesthetic doses (propofol, thiopental, midazolam infusion). Simultaneously treat causes (glucose, thiamine).",
                 "Refractory SE: EEG monitoring, ICU, burst suppression"),
                ("What is SUDEP?",
                 "Sudden Unexpected Death in Epilepsy. Most common cause of premature death in epilepsy. Risk increased by nocturnal seizures, generalised tonic-clonic seizures, poor seizure control, young males.",
                 "Reduce risk with optimal seizure control, avoid sleep deprivation"),
            ],
            "Headache": [
                ("Describe the features of subarachnoid haemorrhage (SAH).",
                 "Sudden onset 'thunderclap' headache (worst of life), neck stiffness, photophobia. Caused by berry aneurysm rupture (most common). CT head (non-contrast) is 98% sensitive within 12h. LP if CT negative β†’ xanthochromia.",
                 "Nimodipine (calcium channel blocker) prevents vasospasm in SAH"),
                ("Compare migraine and tension-type headache.",
                 "Migraine: unilateral, pulsating, moderate-severe, nausea/vomiting, photophobia/phonophobia, lasts 4-72h, may have aura. Tension: bilateral, pressing/tightening, mild-moderate, no nausea, no aggravation with activity.",
                 "SUNCT/SUNA: autonomic features + conjunctival injection β€” rule out secondary causes"),
            ],
            "Movement Disorders": [
                ("Describe the pathophysiology of Parkinson's disease.",
                 "Loss of dopaminergic neurons in substantia nigra (pars compacta) β†’ depletion of dopamine in striatum β†’ excess inhibition of motor cortex via basal ganglia. Lewy bodies (alpha-synuclein) are hallmark.",
                 "TRAP: Tremor (resting pill-rolling), Rigidity (cogwheel), Akinesia, Postural instability"),
                ("What are the treatments for Parkinson's disease?",
                 "Levodopa + carbidopa (most effective β€” gold standard). Dopamine agonists (pramipexole, ropinirole). MAO-B inhibitors (rasagiline, selegiline). COMT inhibitors (entacapone). Amantadine (for dyskinesia). DBS for refractory.",
                 "Levodopa complications: wearing off, on-off phenomenon, dyskinesias"),
            ],
            "Dementia": [
                ("Compare the main types of dementia.",
                 "Alzheimer's: gradual onset, memory first, hippocampal atrophy, amyloid plaques + tau tangles, AChE inhibitors. Vascular: stepwise, focal signs, CVD risk factors. DLB: fluctuating cognition, visual hallucinations, Parkinsonism, REM sleep disorder. FTD: personality/behaviour change first.",
                 "DLB: AVOID antipsychotics (severe neuroleptic sensitivity reaction)"),
            ],
        }
    },

    "Endocrine": {
        "color": SYSTEM_COLORS["Endocrine"],
        "topics": {
            "Diabetes Mellitus": [
                ("What is the diagnostic criteria for diabetes mellitus?",
                 "FPG β‰₯126 mg/dL (7.0 mmol/L). 2h PG β‰₯200 mg/dL (11.1 mmol/L) on OGTT. Random PG β‰₯200 mg/dL with symptoms. HbA1c β‰₯6.5% (48 mmol/mol). All except random + symptoms must be confirmed on repeat.",
                 "IFG: FPG 100-125. IGT: 2h PG 140-199. Both are prediabetes states."),
                ("Compare DKA and HHS.",
                 "DKA: T1DM, glucose 250-600, pH <7.3, HCO3 <18, high AG, ketonaemia. Treat: IV fluids (0.9% NaCl), insulin infusion, K+ replacement. HHS: T2DM, glucose >600, hyperosmolar (>320), no/mild acidosis, no significant ketonaemia. Higher mortality.",
                 "HHS: replace fluids slowly (risk brain oedema), use 0.45% saline, cautious insulin"),
                ("What are the microvascular complications of diabetes?",
                 "Retinopathy (leading cause of blindness working-age), Nephropathy (leading cause of ESRD), Neuropathy (peripheral symmetrical sensorimotor, autonomic: gastroparesis, postural hypotension).",
                 "Annual screening: HbA1c, renal function, urine ACR, retinal photo, foot examination"),
                ("What is the mechanism of SGLT2 inhibitors?",
                 "Block SGLT2 in proximal tubule β†’ prevent glucose reabsorption β†’ glycosuria β†’ lower blood glucose. Additional benefits: weight loss, BP reduction, cardioprotection (HF), nephroprotection.",
                 "Side effects: UTI/genital candidiasis, DKA (euglycaemic), Fournier's gangrene"),
            ],
            "Thyroid": [
                ("Compare hypothyroidism and hyperthyroidism.",
                 "Hypothyroid (Hashimoto's most common): weight gain, cold intolerance, bradycardia, dry skin, constipation, delayed reflexes, myxoedema. Treat with levothyroxine. Hyperthyroid (Graves' most common): weight loss, heat intolerance, tachycardia/AF, sweating, diarrhoea, exophthalmos, goitre. Treat: carbimazole/PTU, propranolol, radioiodine, surgery.",
                 "Thyroid storm: hyperpyrexia, tachycardia, delirium β€” treat with propranolol, PTU, Lugol's iodine, steroids"),
                ("What is myxoedema coma?",
                 "Severe hypothyroidism precipitated by cold, infection, drugs. Features: hypothermia, bradycardia, hypotension, hyponatraemia, hypoglycaemia, coma. Treat: IV T3/T4, steroids (co-existing adrenal insufficiency), warm slowly, treat precipitant.",
                 "TSH is the best screening test for thyroid disorders"),
            ],
            "Adrenal": [
                ("Compare Addison's disease and Cushing's syndrome.",
                 "Addison's (hypocortisolaemia): weakness, fatigue, weight loss, hyperpigmentation (ACTH↑), hypotension, hyponatraemia, hyperkalaemia, hypoglycaemia. Cushing's (hypercortisolaemia): central obesity, buffalo hump, moon face, purple striae, HTN, diabetes, osteoporosis, hirsutism.",
                 "Addisonian crisis: Addison's + stress β†’ adrenal crisis β†’ give IV hydrocortisone 100mg STAT"),
                ("How do you diagnose and locate phaeochromocytoma?",
                 "Biochemistry: 24h urine catecholamines/metanephrines, or plasma free metanephrines (most sensitive). Locate: MRI/CT adrenals, then MIBG scan or PET if extra-adrenal. Rule of 10s: 10% malignant, bilateral, extra-adrenal, paediatric, familial.",
                 "Prep for surgery: alpha-blockade (phenoxybenzamine) FIRST, then beta-blockade"),
            ],
            "Pituitary": [
                ("What is acromegaly and how is it diagnosed?",
                 "Excess GH in adults (after epiphyseal fusion) from GH-secreting pituitary adenoma. Features: coarsening facial features, large hands/feet, macroglossia, organomegaly, DM, HTN, carpal tunnel. Diagnose: IGF-1 raised + GH not suppressed on OGTT. MRI pituitary.",
                 "Acromegaly: increased CV mortality β€” annual echo, colonoscopy"),
                ("What is diabetes insipidus and how is it treated?",
                 "Central DI: ↓ADH from posterior pituitary damage β†’ inability to concentrate urine. Nephrogenic DI: renal resistance to ADH. Diagnose: water deprivation test β†’ if urine concentrates after DDAVP = central DI. Treat central DI: DDAVP (desmopressin).",
                 "Differentiate from primary polydipsia: plasma osmolality helps"),
            ],
        }
    },

    "Hematology": {
        "color": SYSTEM_COLORS["Hematology"],
        "topics": {
            "Anaemia": [
                ("Classify anaemia by MCV and give causes.",
                 "Microcytic (MCV <80): IDA, thalassaemia, sideroblastic, anaemia of chronic disease (can be normocytic too). Normocytic (80-100): acute blood loss, haemolysis, CKD, hypothyroidism, marrow infiltration. Macrocytic (>100): megaloblastic (B12/folate deficiency), non-megaloblastic (alcohol, liver disease, hypothyroidism, drugs).",
                 "Iron deficiency: serum ferritin ↓ (most sensitive early marker), transferrin saturation ↓, TIBC ↑"),
                ("How does B12 deficiency cause megaloblastic anaemia?",
                 "B12 is cofactor for methionine synthase (THF regeneration) and methylmalonyl-CoA mutase. Deficiency β†’ impaired DNA synthesis β†’ megaloblastic changes. Also causes subacute combined degeneration of spinal cord (dorsal + lateral columns).",
                 "B12 deficiency causes: pernicious anaemia (autoimmune β€” anti-IF antibodies), veganism, ileal disease/resection, Crohn's"),
            ],
            "Haematological Malignancy": [
                ("Compare AML and ALL.",
                 "AML: adults, myeloid blasts >20%, Auer rods, FAB classification. ALL: children (peak 2-5y), lymphoblasts, TdT positive, t(12;21) most common (good prognosis), Ph chromosome t(9;22) in adult ALL (poor prognosis).",
                 "AML: treat with 7+3 (cytarabine + daunorubicin). ALL: vincristine, steroids, asparaginase, MTX"),
                ("What is the Philadelphia chromosome and its significance?",
                 "t(9;22) translocation β†’ BCR-ABL fusion gene β†’ constitutively active tyrosine kinase β†’ uncontrolled proliferation. Found in 95% CML and 20-25% adult ALL. Imatinib (TKI) is targeted therapy for CML.",
                 "Imatinib revolutionised CML: 5-year survival >90%"),
                ("What are the features of multiple myeloma?",
                 "CRAB: hypercalcaemia (↑osteoclasts), Renal failure (light chain deposition), Anaemia, Bone lesions/pain (punched-out lytic lesions). Plus: M-protein on SPEP, Bence Jones protein in urine, rouleaux on smear, ↑ESR.",
                 "Diagnose: bone marrow biopsy showing β‰₯10% clonal plasma cells"),
            ],
            "Coagulation": [
                ("What is DIC and how is it managed?",
                 "Disseminated Intravascular Coagulation: widespread activation of coagulation β†’ thrombosis consuming clotting factors + platelets β†’ paradoxical bleeding. Labs: ↑PT, ↑aPTT, ↓fibrinogen, ↓platelets, ↑D-dimer, schistocytes. Treat underlying cause; FFP, cryoprecipitate, platelets.",
                 "Causes: sepsis (most common), trauma, malignancy, obstetric complications (abruption, AFE)"),
                ("Explain the intrinsic vs extrinsic coagulation pathways.",
                 "Extrinsic (tissue factor): TF + VIIa β†’ activates X (monitored by PT/INR). Intrinsic (contact): XII, XI, IX, VIII β†’ activates X (monitored by aPTT). Common pathway: Xa + Va β†’ thrombin β†’ fibrin. Warfarin inhibits II, VII, IX, X, Protein C, S. Heparin potentiates antithrombin.",
                 "DOACs: rivaroxaban/apixaban block Xa; dabigatran blocks IIa (thrombin)"),
            ],
        }
    },

    "Musculoskeletal": {
        "color": SYSTEM_COLORS["Musculoskeletal"],
        "topics": {
            "Arthritis": [
                ("Compare rheumatoid arthritis and osteoarthritis.",
                 "RA: inflammatory, symmetrical, small joints (MCP, PIP), morning stiffness >1h, RF/anti-CCP positive, pannus formation, extra-articular features (nodules, vasculitis, ILD). OA: degenerative, asymmetric, weight-bearing joints (hip, knee), DIP, Heberden's nodes, stiffness after rest.",
                 "RA treatment: methotrexate (anchor), hydroxychloroquine, sulfasalazine, biologics (TNF-inhibitors, IL-6 inhibitors)"),
                ("What is gout and how is it managed?",
                 "Hyperuricaemia β†’ monosodium urate crystal deposition β†’ acute inflammatory arthritis (1st MTP most common = podagra). Aspirate joint: needle-shaped negatively birefringent crystals. Acute: NSAIDs/colchicine/steroids. Prophylaxis: allopurinol (xanthine oxidase inhibitor) or febuxostat.",
                 "Pseudogout: calcium pyrophosphate crystals β€” positively birefringent, rhomboid shape, affects wrist/knee"),
            ],
            "Connective Tissue Disease": [
                ("What are the diagnostic criteria for SLE?",
                 "ACR/EULAR 2019 criteria: Entry criterion: ANA β‰₯1:80. Domains: constitutional, haematological, neuropsychiatric, mucocutaneous, serosal, musculoskeletal, renal, immunological (anti-dsDNA, anti-Sm, complement). Score β‰₯10 = SLE.",
                 "Anti-dsDNA: specific for SLE, correlates with disease activity. Anti-Sm: specific but not sensitive. Anti-Ro/La: Sjogren's + NLE"),
                ("What is antiphospholipid syndrome (APS)?",
                 "Acquired thrombophilia: recurrent arterial/venous thrombosis, pregnancy morbidity. Antibodies: lupus anticoagulant, anticardiolipin, anti-Ξ²2GPI. Treat: anticoagulation (warfarin). Catastrophic APS: multiorgan failure from microvascular thrombosis.",
                 "Paradox: lupus anticoagulant prolongs aPTT in vitro but causes thrombosis in vivo"),
            ],
            "Bone Disease": [
                ("Compare osteoporosis and osteomalacia biochemically.",
                 "Osteoporosis: normal Ca, PO4, ALP; reduced bone density (T-score ≀-2.5). Osteomalacia (adult rickets): low Ca, low PO4, raised ALP, raised PTH; bone pain, pseudofractures (Looser's zones). Cause: vitamin D deficiency.",
                 "Bisphosphonates (alendronate) first-line for osteoporosis; denosumab, romosozumab for refractory"),
            ],
        }
    },

    "Reproductive": {
        "color": SYSTEM_COLORS["Reproductive"],
        "topics": {
            "Obstetrics": [
                ("What is pre-eclampsia and how is it managed?",
                 "New HTN (β‰₯140/90) + proteinuria or end-organ damage after 20 weeks. Severe if BP β‰₯160/110, thrombocytopaenia, renal failure, liver dysfunction, pulmonary oedema, visual symptoms. Deliver at β‰₯37 weeks. Severe: magnesium sulfate (seizure prophylaxis), antihypertensives (labetalol, hydralazine, nifedipine).",
                 "Only cure is delivery. HELLP = Haemolysis, Elevated LFTs, Low Platelets"),
                ("What is the Bishop score?",
                 "Cervical assessment for induction of labour: Position, Consistency, Effacement, Dilatation, Station of presenting part. Score β‰₯8 = favourable cervix (induction likely successful). Score <6 = cervical ripening needed.",
                 "Prostaglandins (dinoprostone) used for cervical ripening"),
                ("What is placenta praevia vs placental abruption?",
                 "Praevia: placenta covers internal os β†’ painless antepartum haemorrhage, diagnosed on USS. Abruption: premature separation of normally sited placenta β†’ painful dark haemorrhage, woody hard uterus, fetal distress, DIC risk.",
                 "Praevia: avoid VE, deliver by C-section"),
            ],
            "Gynaecology": [
                ("What is PCOS and its diagnostic criteria?",
                 "Rotterdam criteria (2 of 3): oligo/anovulation, clinical/biochemical hyperandrogenism, polycystic ovaries on USS. Features: infertility, acne, hirsutism, metabolic syndrome. Treat: OCP (cycle regulation), metformin (insulin resistance), clomifene/letrozole (ovulation induction).",
                 "PCOS is the most common cause of anovulatory infertility"),
                ("What are the stages of endometriosis and its treatment?",
                 "Endometrial tissue outside uterus β†’ cyclical pain, dysmenorrhoea, dyspareunia, infertility. Stages I-IV (minimal to severe). Medical: OCP, progestogens, GnRH agonists. Surgical: laparoscopic excision, hysterectomy with bilateral salpingo-oophorectomy.",
                 "Gold standard diagnosis: laparoscopy with biopsy"),
            ],
        }
    },

    "Immunology": {
        "color": SYSTEM_COLORS["Immunology"],
        "topics": {
            "Hypersensitivity": [
                ("Describe the 4 types of hypersensitivity reactions.",
                 "Type I: IgE-mediated (anaphylaxis, atopy) β€” immediate. Type II: IgG/IgM against cell surface (AIHA, Goodpasture's, haemolytic transfusion reaction). Type III: immune complex deposition (SLE, serum sickness, PSGN). Type IV: T-cell mediated (contact dermatitis, TB, transplant rejection, coeliac).",
                 "Mnemonic: ACID β€” Anaphylactic, Cytotoxic, Immune complex, Delayed"),
                ("How is anaphylaxis managed?",
                 "Remove trigger. IM adrenaline 0.5mg (1:1000) into outer thigh β€” FIRST and most important. High-flow O2. IV fluids. Chlorphenamine (antihistamine) + hydrocortisone (adjuncts only). Monitor for biphasic reaction for 4-6h.",
                 "Anaphylaxis: urticaria + wheeze + hypotension β€” adrenaline must NOT be delayed"),
            ],
            "HIV/AIDS": [
                ("What defines AIDS and how is HIV managed?",
                 "AIDS: CD4 <200 cells/ΞΌL or AIDS-defining illness (PCP, CMV retinitis, CNS toxoplasmosis, cryptococcal meningitis, MAC, Kaposi's sarcoma). Treat with ART (antiretroviral therapy) β€” HAART: 2 NRTIs + 1 NNRTI or integrase inhibitor.",
                 "PCP prophylaxis: TMP-SMX when CD4 <200. MAC prophylaxis: azithromycin when CD4 <50"),
                ("What are the opportunistic infections in HIV by CD4 count?",
                 "<500: Candida (oral thrush), HSV, HZV, TB. <200: PCP (Pneumocystis jirovecii), toxoplasmosis, cryptococcal meningitis, cryptosporidiosis. <50: CMV (retinitis, colitis), MAC (Mycobacterium avium complex).",
                 "CD4 <200 = AIDS-defining. Monitor viral load for treatment response"),
            ],
        }
    },

    "Psychiatry": {
        "color": SYSTEM_COLORS["Psychiatry"],
        "topics": {
            "Mood Disorders": [
                ("What is the diagnostic criteria for major depressive disorder (MDD)?",
                 "β‰₯5 of SIGECAPS for β‰₯2 weeks, must include depressed mood or anhedonia: Sleep (insomnia/hypersomnia), Interest (anhedonia), Guilt, Energy ↓, Concentration ↓, Appetite/weight change, Psychomotor changes, Suicidal ideation.",
                 "PHQ-9 score β‰₯10 = moderate depression. Mild: therapy. Moderate: SSRI + therapy. Severe: SSRI + immediate therapy Β± inpatient"),
                ("What is bipolar disorder and how is it treated?",
                 "Type I: β‰₯1 manic episode (7+ days, elevated/irritable, DIGFAST: Distractibility, Impulsivity, Grandiosity, Flight of ideas, Activity increase, Sleep ↓, Talkativeness). Type II: hypomanic + depressive. Treat mania: lithium/valproate/antipsychotics. Prevent: lithium (most evidence).",
                 "Lithium toxicity: tremor, ataxia, confusion, convulsions β€” narrow TI, monitor levels"),
            ],
            "Psychosis": [
                ("Describe the positive and negative symptoms of schizophrenia.",
                 "Positive: hallucinations (auditory most common), delusions (persecutory, grandiose), disorganised thought, inappropriate affect. Negative: alogia, avolition, anhedonia, affective flattening, asociality. Treat: antipsychotics (D2 blockers). Clozapine for treatment-resistant.",
                 "Clozapine: risk of agranulocytosis β€” mandatory WBC monitoring. Most effective antipsychotic."),
                ("What are the side effects of antipsychotics?",
                 "Extrapyramidal: acute dystonia, akathisia, Parkinsonism, tardive dyskinesia (irreversible). Metabolic: weight gain, dyslipidaemia, DM (atypicals > typicals). Anticholinergic: dry mouth, urinary retention, constipation. Prolactin elevation. Neuroleptic malignant syndrome (NMS): hyperthermia, rigidity, autonomic instability.",
                 "NMS: STOP antipsychotic, dantrolene, bromocriptine, ICU"),
            ],
            "Anxiety": [
                ("What are the anxiety disorders and their pharmacological treatments?",
                 "GAD: SSRIs/SNRIs (first-line), buspirone, pregabalin. Panic disorder: SSRIs/SNRIs, cognitive therapy. PTSD: SSRIs (paroxetine, sertraline), trauma-focused CBT. OCD: SSRIs (high dose), clomipramine. Social anxiety: SSRIs, beta-blockers (performance anxiety).",
                 "Benzodiazepines: short-term only due to dependence risk β€” NOT first-line for anxiety"),
            ],
        }
    },

    "Pharmacology": {
        "color": SYSTEM_COLORS["Pharmacology"],
        "topics": {
            "Pharmacokinetics": [
                ("Define and clinically apply volume of distribution (Vd).",
                 "Vd = Dose/Plasma concentration. Low Vd (0.04-0.2 L/kg): confined to plasma (heparin, warfarin). Medium (0.2-0.6 L/kg): ECF. High (>0.6 L/kg): distributed into tissues (chloroquine, amiodarone, digoxin). High Vd drugs NOT removed by dialysis.",
                 "Amiodarone Vd = 60 L/kg β€” explains long half-life and tissue toxicity"),
                ("What is zero-order vs first-order kinetics?",
                 "First-order: rate of elimination proportional to concentration β€” constant fraction eliminated per unit time, constant TΒ½. Zero-order: constant amount eliminated per unit time regardless of concentration (enzyme saturation). Clinical examples: phenytoin, ethanol, aspirin (high dose) β€” zero-order at therapeutic levels.",
                 "Zero-order: small dose change β†’ disproportionate large plasma level increase"),
                ("Explain the clinical significance of cytochrome P450 (CYP450) interactions.",
                 "CYP450 inducers (increase metabolism β†’ lower drug levels): rifampicin, carbamazepine, phenytoin, St John's Wort, alcohol (chronic). Inhibitors (decrease metabolism β†’ higher drug levels β†’ toxicity): azole antifungals, SSRIs, erythromycin, amiodarone, grapefruit juice.",
                 "Warfarin + rifampicin = ↑warfarin metabolism β†’ ↓INR β†’ thrombosis. Warfarin + fluconazole = ↓metabolism β†’ ↑INR β†’ bleeding"),
            ],
            "Pharmacodynamics": [
                ("What is the difference between competitive and non-competitive antagonism?",
                 "Competitive (reversible): shifts dose-response curve to the right (increased EC50), same Emax. Can be overcome by increasing agonist dose. Non-competitive (irreversible/allosteric): decreases Emax, no rightward shift possible. Example: phenoxybenzamine (non-competitive alpha-blocker).",
                 "Therapeutic window = range between EC50 (efficacy) and TC50 (toxicity)"),
                ("What is the therapeutic index and how does it relate to drug safety?",
                 "TI = LD50/ED50 (animal models) or TD50/ED50 (clinical). Narrow TI drugs require monitoring: lithium (0.6-1.2 mmol/L), digoxin (0.8-2 ng/mL), warfarin (INR 2-3), phenytoin (10-20 ΞΌg/mL), theophylline (10-20 ΞΌg/mL), cyclosporin.",
                 "Always check TDM levels and drug interactions for narrow TI drugs"),
            ],
            "Key Drug Classes": [
                ("What are the major drug interactions with warfarin?",
                 "Potentiate (↑INR): amiodarone, fluconazole/metronidazole (CYP inhibitors), aspirin, NSAIDs. Antagonise (↓INR): rifampicin, carbamazepine, phenytoin (CYP inducers), St John's Wort, vitamin K. Reverse: vitamin K (slow), FFP/PCC (immediate reversal in bleeding).",
                 "Reversal: minor bleeding β†’ hold warfarin + vitamin K 1-5mg PO. Major bleeding β†’ IV vitamin K + PCC"),
                ("Compare the mechanisms of common antibiotics.",
                 "Cell wall: beta-lactams (penicillins, cephalosporins, carbapenems), vancomycin. Protein synthesis: 30S β€” aminoglycosides, tetracyclines; 50S β€” macrolides, chloramphenicol, clindamycin. DNA/RNA: fluoroquinolones (topoisomerase II/IV), rifampicin (RNA pol), metronidazole (DNA damage). Cell membrane: polymyxins, daptomycin.",
                 "MATLAB: Macrolides/Aminoglycosides/Tetracyclines (protein); Linezolid And Beta-lactams"),
            ],
        }
    },
}

# ─────────────────────────── PDF BUILDER ─────────────────────────────────────
def build_system_section(system_name, data, styles, W):
    elems = []
    sys_color = data["color"]

    # System header banner
    header_bg = Table([[Paragraph(f"β—†  {system_name.upper()}  β—†", styles["sys_title"])]],
                      colWidths=[W], rowHeights=[48])
    header_bg.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), sys_color),
        ('TOPPADDING', (0,0), (-1,-1), 10),
        ('BOTTOMPADDING', (0,0), (-1,-1), 10),
        ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ]))
    elems.append(header_bg)
    elems.append(Spacer(1, 8))

    topics = data["topics"]
    for topic_name, qa_list in topics.items():
        # Topic sub-header
        topic_hdr = Table([[Paragraph(f"  {topic_name}", styles["section_hdr"])]],
                          colWidths=[W], rowHeights=[28])
        topic_hdr.setStyle(TableStyle([
            ('BACKGROUND', (0,0), (-1,-1), colors.HexColor("#263238")),
            ('TOPPADDING', (0,0), (-1,-1), 6),
            ('BOTTOMPADDING', (0,0), (-1,-1), 6),
            ('LEFTPADDING', (0,0), (-1,-1), 8),
        ]))
        elems.append(KeepTogether([topic_hdr, Spacer(1, 4)]))

        qa_rows = []
        for i, (q, a, key) in enumerate(qa_list):
            row_color = colors.white if i % 2 == 0 else colors.HexColor("#F8FFFE")
            # Build Q&A cell
            q_para = Paragraph(f"<b>Q{i+1}.</b> {q}", styles["q"])
            a_para = Paragraph(f"<b>β–Ά</b> {a}", styles["a"])
            key_para = Paragraph(f"<b>πŸ”‘ Key:</b> {key}", styles["key"])

            cell = [q_para, a_para, key_para]
            num_cell = [Paragraph(f"<b>{i+1}</b>", ParagraphStyle(
                "num", fontName="Helvetica-Bold", fontSize=13,
                textColor=sys_color, alignment=TA_CENTER, leading=16))]

            qa_rows.append([num_cell, cell])

        qa_tbl = Table(qa_rows, colWidths=[22, W-22])
        qa_tbl.setStyle(TableStyle([
            ('VALIGN', (0,0), (-1,-1), 'TOP'),
            ('TOPPADDING', (0,0), (-1,-1), 6),
            ('BOTTOMPADDING', (0,0), (-1,-1), 6),
            ('LEFTPADDING', (0,0), (-1,-1), 4),
            ('RIGHTPADDING', (0,0), (-1,-1), 4),
            ('ROWBACKGROUNDS', (0,0), (-1,-1), [colors.white, colors.HexColor("#F8FFFE")]),
            ('LINEBELOW', (0,0), (-1,-1), 0.5, colors.HexColor("#ECEFF1")),
            ('LINEAFTER', (0,0), (0,-1), 2, sys_color),
        ]))
        elems.append(qa_tbl)
        elems.append(Spacer(1, 10))

    elems.append(PageBreak())
    return elems


def build_toc(styles, W):
    elems = []
    elems.append(Spacer(1, 1*cm))
    elems.append(Paragraph("TABLE OF CONTENTS", styles["toc_title"]))
    elems.append(HRFlowable(width="80%", thickness=2, color=ACCENT_BLUE, hAlign='CENTER'))
    elems.append(Spacer(1, 0.5*cm))

    toc_data = []
    for i, (system, data) in enumerate(QA_DATA.items(), 1):
        color = data["color"]
        dot = Paragraph(f'<font color="{color.hexval()}">●</font>', ParagraphStyle(
            "dot", fontName="Helvetica", fontSize=14, alignment=TA_CENTER))
        sys_para = Paragraph(
            f'<b><font color="{color.hexval()}">{i:02d}. {system}</font></b>',
            ParagraphStyle("tocitem", fontName="Helvetica-Bold", fontSize=12, leading=20))
        topics_para = Paragraph(
            "  |  ".join(data["topics"].keys()),
            ParagraphStyle("subtopics", fontName="Helvetica", fontSize=8.5,
                           textColor=TEXT_MUTED, leading=13))
        toc_data.append([dot, [sys_para, topics_para]])

    toc_tbl = Table(toc_data, colWidths=[16, W-16])
    toc_tbl.setStyle(TableStyle([
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('TOPPADDING', (0,0), (-1,-1), 6),
        ('BOTTOMPADDING', (0,0), (-1,-1), 6),
        ('LINEBELOW', (0,0), (-1,-1), 0.5, MID_GREY),
    ]))
    elems.append(toc_tbl)
    elems.append(PageBreak())
    return elems


def build_summary_page(styles, W):
    elems = []
    elems.append(Spacer(1, 0.5*cm))
    elems.append(Paragraph("QUICK REFERENCE SUMMARY", ParagraphStyle(
        "sumtitle", fontName="Helvetica-Bold", fontSize=20,
        textColor=ACCENT_BLUE, alignment=TA_CENTER, leading=28)))
    elems.append(HRFlowable(width="90%", thickness=2, color=ACCENT_BLUE, hAlign='CENTER'))
    elems.append(Spacer(1, 0.4*cm))

    summary_items = [
        ("Cardiovascular", "HF (4 drug classes), STEMI (90min PCI), AF (CHAβ‚‚DSβ‚‚-VASc), Valvular (IE Duke criteria)"),
        ("Respiratory", "COPD (FEV1/FVC <0.7), Asthma stepwise, PE (Wells + CTPA), Lung Ca paraneoplastic syndromes"),
        ("Gastrointestinal", "PUD (H.pylori triple therapy), IBD (CD vs UC), Cirrhosis (Child-Pugh/MELD), Pancreatitis (GET SMASHED)"),
        ("Renal", "AKI (KDIGO stages, AEIOU for dialysis), CKD (GFR staging), Acid-base (MUDPILES), FeNa <1%=pre-renal"),
        ("Neurology", "Stroke (tPA <4.5h), SE management (lorazepam→levetiracetam→anaesthesia), PD (TRAP + L-dopa)"),
        ("Endocrine", "DM diagnosis (HbA1c β‰₯6.5%), DKA vs HHS, SGLT2i benefits, Addison's crisis (IV hydrocortisone)"),
        ("Haematology", "Anaemia by MCV, CML (BCR-ABL, imatinib), Myeloma (CRAB), DIC (↑PT, ↓fibrinogen, treat cause)"),
        ("MSK", "RA vs OA, Gout (negatively birefringent, allopurinol), SLE (ANA+anti-dsDNA), APS (anticoagulate)"),
        ("Reproductive", "Pre-eclampsia (MgSO4 + deliver), PCOS (Rotterdam 2/3), Endometriosis (laparoscopy gold standard)"),
        ("Immunology", "Gell-Coombs Types I-IV, Anaphylaxis (IM adrenaline FIRST), HIV/CD4 (OI thresholds)"),
        ("Psychiatry", "MDD (SIGECAPS), Bipolar (lithium), Schizophrenia (D2 blockers/clozapine), NMS (STOP drug)"),
        ("Pharmacology", "Vd (high=tissue/not dialysable), Zero-order (phenytoin/ethanol), CYP450 (rifampicin inducer), TI (lithium/digoxin)"),
    ]

    sum_data = [[
        Paragraph(f'<b><font color="{list(SYSTEM_COLORS.values())[i].hexval()}">{sys}</font></b>',
                  ParagraphStyle("sh", fontName="Helvetica-Bold", fontSize=9.5, leading=14)),
        Paragraph(tip, ParagraphStyle("st", fontName="Helvetica", fontSize=8.5,
                                      textColor=TEXT_DARK, leading=13))
    ] for i, (sys, tip) in enumerate(summary_items)]

    sum_tbl = Table(sum_data, colWidths=[W*0.22, W*0.78])
    sum_tbl.setStyle(TableStyle([
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 5),
        ('RIGHTPADDING', (0,0), (-1,-1), 5),
        ('ROWBACKGROUNDS', (0,0), (-1,-1), [colors.white, LIGHT_GREY]),
        ('LINEBELOW', (0,0), (-1,-1), 0.5, MID_GREY),
        ('LINEAFTER', (0,0), (0,-1), 2, ACCENT_BLUE),
    ]))
    elems.append(sum_tbl)
    elems.append(Spacer(1, 0.5*cm))

    # Footer note
    elems.append(HRFlowable(width="100%", thickness=0.5, color=MID_GREY))
    elems.append(Spacer(1, 0.2*cm))
    elems.append(Paragraph(
        "This document is a high-yield exam preparation reference. Always correlate with current clinical guidelines and your institution's curriculum.",
        ParagraphStyle("footer", fontName="Helvetica-Oblique", fontSize=8,
                       textColor=TEXT_MUTED, alignment=TA_CENTER, leading=12)))
    return elems


def add_page_number(canvas, doc):
    """Add page numbers and header to each page."""
    canvas.saveState()
    W, H = A4
    # Footer bar
    canvas.setFillColor(colors.HexColor("#0D1B2A"))
    canvas.rect(0, 0, W, 20, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica", 8)
    canvas.drawString(1*cm, 6, "MD Theory Final Exam β€” All Systems Q&A Mind Map")
    canvas.drawRightString(W - 1*cm, 6, f"Page {doc.page}")
    canvas.restoreState()


def main():
    W, H = A4
    doc = SimpleDocTemplate(
        OUTPUT_PATH,
        pagesize=A4,
        leftMargin=1.5*cm,
        rightMargin=1.5*cm,
        topMargin=1.5*cm,
        bottomMargin=1.5*cm,
        title="MD Theory Final Exam - All Systems Q&A Mind Map",
        author="Orris Medical AI",
        subject="Comprehensive Medical Theory Examination Reference"
    )
    usable_W = W - 3*cm

    styles = make_styles()
    story = []

    # 1. Cover page
    story += cover_page(styles, usable_W, H)

    # 2. Table of Contents
    story += build_toc(styles, usable_W)

    # 3. System sections
    for system_name, data in QA_DATA.items():
        story += build_system_section(system_name, data, styles, usable_W)

    # 4. Summary page
    story += build_summary_page(styles, usable_W)

    doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
    print(f"βœ… PDF generated: {OUTPUT_PATH}")
    import os
    size = os.path.getsize(OUTPUT_PATH)
    print(f"   File size: {size/1024:.1f} KB")


if __name__ == "__main__":
    main()
Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.

Create a PPTX presentation version of the Mind Map

Your credits are exhausted. Your daily credits reset tomorrow, or you can purchase a top-up for more.
This is a shared conversation. Sign in to Orris to start your own chat.