Arthritis

Reading File
The query "Arthritis" is broad and covers many subtypes, mechanisms, and management approaches. Let me clarify what you need before diving in.
Asking for Preferences

What aspect of arthritis are you interested in? · What level of detail do you need?

Searching sources...
Running parallel searches across all major arthritis types now.
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Good. Now I'll pull the main content from Robbins Pathology (OA), Firestein & Kelley's Rheumatology (RA + SpA), and Family Medicine (gout, RA, OA overview) in parallel.
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
I now have rich content on OA, RA, Gout, and Septic Arthritis. Let me also pull in psoriatic arthritis and spondyloarthritis content, plus the OA pathology diagram and RA treatment sections.
Reading File
Reading File
Loading Image
I now have comprehensive content across all major arthritis types. Let me compile the full clinical deep-dive.

Arthritis: Overview of All Types - Clinical Deep Dive

Arthritis literally means "joint inflammation," but it encompasses a wide spectrum of diseases ranging from purely degenerative to strongly autoimmune and infectious. The major categories are outlined below.

1. Osteoarthritis (OA)

Definition & Epidemiology

Osteoarthritis - also called degenerative joint disease - is the most common form of arthritis and the leading cause of work disability in the United States (17% of all disability). It affects roughly 20% of the U.S. population, with radiographic evidence in almost all patients over 75. Prevalence rises exponentially after age 50, affecting about 40% of people over 70. It occurs equally in men and women ages 45-55, but becomes more common in women after 55.

Classification

TypeDescription
Primary (idiopathic)Appears insidiously as an aging phenomenon; oligoarticular, affects weight-bearing joints
HereditaryCollagen gene defects; inflammatory hand OA (Heberden/Bouchard nodes) runs in families
SecondaryPrior cartilage damage from trauma, obesity, hemochromatosis, RA, gout, CPPD, neuropathy, acromegaly

Pathogenesis

OA is primarily a degenerative disorder of articular cartilage, with inflammation acting as a secondary contributor. Biomechanical stress is the principal mechanism. The process unfolds in three stages:
OA Pathogenesis - Stages from chondrocyte injury to late OA
  1. Chondrocyte injury - Genetic/biomechanical insults damage Type II collagen and proteoglycans
  2. Early OA - Chondrocytes proliferate and release BMP (repair attempt), but MMPs degrade collagen and proteoglycans; PGE2, NO, TNF drive further damage; degradation exceeds repair
  3. Late OA - Chondrocyte dropout, apoptosis, subchondral bone changes, osteophyte formation, loose bodies
(Robbins & Kumar Basic Pathology, p. 790)

Clinical Features

  • Insidious onset of joint pain, worse with activity, relieved by rest
  • Morning stiffness < 30 minutes (vs. > 1 hour in RA)
  • Bony enlargement (osteophytes): Heberden nodes (DIP), Bouchard nodes (PIP) in hands
  • Crepitus on joint movement
  • No systemic features - OA is purely articular
  • Most OA is asymptomatic - an incidental radiographic finding

Joints Affected

Primarily weight-bearing: knees, hips, lumbar and cervical spine, first MTP joint, DIP and PIP joints of hands.

Investigations

  • X-ray: joint space narrowing, osteophytes, subchondral sclerosis, subchondral cysts
  • No serologic markers (RF and ANA negative)
  • Synovial fluid: non-inflammatory (WBC < 2000/mm³)

Treatment

  • Non-pharmacologic: Weight loss (reduces load on joints), low-impact exercise, physiotherapy, assistive devices
  • Pharmacologic: NSAIDs are the first-line pharmacologic choice; topical NSAIDs for knee/hand OA; acetaminophen for mild pain; intra-articular corticosteroids for flares
  • Surgical: Joint replacement for severe, refractory disease
(Textbook of Family Medicine 9e, p. 873)

2. Rheumatoid Arthritis (RA)

Definition & Epidemiology

RA is a chronic, systemic inflammatory autoimmune disease in which cellular and humoral immunity results in destruction of synovium and other tissues. It affects 1-2% of adults, with a 3:1 female predominance. Peak incidence is ages 20-50. Without treatment, >70% of patients with polyarticular RF-positive RA develop joint erosions within 2 years.

Pathogenesis

  • Genetic: Strong HLA-DR association (HLA-DRB1 "shared epitope"); higher concordance in monozygotic twins
  • Trigger: Unknown inciting event (possibly infectious) activates synovial lining cells and subsynovial vessels → pannus formation (aggressive proliferative synovium)
  • Immune cascade: Leukocyte invasion, protease and cytokine release (TNF-α, IL-1, IL-6 are key)
  • Autoantibodies: Rheumatoid factor (RF) targets IgG Fc; anti-citrullinated peptide antibodies (ACPA/anti-CCP) are more specific and appear years before clinical disease
  • Pannus invades and destroys cartilage and bone → ankylosis in late disease

Clinical Features

  • Symmetric synovitis of small joints of hands and feet - hallmark
  • Morning stiffness > 1 hour
  • Constitutional symptoms: fatigue, fever, weight loss
  • Progression: Wrists → MCPs → PIPs → knees → ankles → larger joints (spares DIP joints, distinguishing it from OA and psoriatic arthritis)
  • Extra-articular manifestations:
    • Rheumatoid nodules (subcutaneous, over pressure points)
    • Pulmonary: interstitial lung disease, pleural effusion
    • Cardiac: pericarditis, accelerated atherosclerosis
    • Ocular: scleritis, sicca syndrome
    • Vasculitis, neuropathy
    • Cervical spine: atlantoaxial subluxation (C1-C2 instability - risk of cord compression)

ACR 1987 Diagnostic Criteria (≥4 of 7, present ≥6 weeks)

  1. Morning stiffness ≥ 1 hour
  2. Arthritis of ≥ 3 joint areas
  3. Arthritis of hand joints (wrists, MCPs, PIPs)
  4. Symmetric arthritis
  5. Rheumatoid nodules
  6. Serum RF positive
  7. Radiographic erosions/periarticular osteopenia on hand/wrist X-ray
(Textbook of Family Medicine 9e, p. 878)

Investigations

  • RF: Positive in ~80% of RA; not specific (also positive in SLE, Sjogren's, infection)
  • Anti-CCP (ACPA): More specific (~95%), present years before symptoms
  • Elevated ESR and CRP
  • Synovial fluid: inflammatory (WBC > 2000, often > 50,000/mm³)
  • X-ray: periarticular osteopenia → marginal erosions → joint space narrowing

Treatment

  • NSAIDs/Corticosteroids: For symptom control and bridging only
  • DMARDs (Disease-Modifying Anti-Rheumatic Drugs) - start early:
    • Methotrexate - first-line DMARD; most widely used
    • Hydroxychloroquine, Sulfasalazine, Leflunomide
  • Biologic DMARDs for inadequate DMARD response:
    • Anti-TNF agents: etanercept, adalimumab, infliximab
    • IL-6 inhibitors: tocilizumab
    • B-cell depletion: rituximab
    • T-cell co-stimulation blockade: abatacept
  • JAK inhibitors (tsDMARDs): tofacitinib, baricitinib

OA vs. RA Comparison

FeatureOsteoarthritisRheumatoid Arthritis
Primary mechanismMechanical injuryAutoimmunity
InflammationSecondaryPrimary
JointsWeight-bearing, DIPSmall joints of hands (MCP, PIP), symmetric
Morning stiffness< 30 min> 1 hour
PathologyCartilage degeneration, osteophytesPannus, erosions, ankylosis
SerologyNegativeRF, anti-CCP positive
Systemic involvementNoYes (lungs, heart, eyes, etc.)
(Robbins & Kumar Basic Pathology, p. 790)

3. Gout (Gouty Arthritis)

Definition & Epidemiology

Gout is a crystal arthropathy caused by deposition of monosodium urate (MSU) crystals in joints and soft tissues. It primarily affects middle-aged men (40-60 years) and postmenopausal women. Hyperuricemia (usually > 8 mg/dL) is the underlying metabolic abnormality, though asymptomatic hyperuricemia alone is not a disease.

Pathophysiology

  • 90% of cases: reduced renal excretion of uric acid
  • 10% of cases: overproduction (inborn errors, high purine diet, increased cell turnover)
  • Secondary hyperuricemia: diuretics (especially thiazides), low-dose aspirin, cyclosporine, renal failure, myeloproliferative disorders
  • MSU crystals trigger intense neutrophil-mediated inflammation

Clinical Stages

  1. Asymptomatic hyperuricemia - elevated uric acid; no symptoms; takes ~20 years before first attack
  2. Acute gouty arthritis - sudden onset severe monoarticular pain (often nocturnal); first MTP joint (podagra) in 50% of first attacks, eventually in 75-90% of patients; heels, ankles, knees also affected; self-limited in days to weeks
  3. Intercritical gout - symptom-free intervals between attacks
  4. Chronic tophaceous gout - persistent hyperuricemia → tophi (urate deposits in soft tissue, cartilage, ear pinnae), chronic arthritis, joint damage, renal involvement (urate nephropathy, uric acid stones)

Diagnosis

  • Definitive: Needle-shaped, negatively birefringent urate crystals on polarized light microscopy of synovial fluid
  • Presumptive: clinical features + hyperuricemia + rapid response to NSAIDs/colchicine
  • Serum uric acid: usually > 8 mg/dL
  • Note: in women and elderly, gout can be polyarticular and mimic RA (tophi mistaken for rheumatoid nodules)

Treatment

PhaseTreatment
Acute attackNSAIDs (indomethacin), colchicine, corticosteroids
Urate-lowering therapy (ULT)Allopurinol (xanthine oxidase inhibitor) - first line; febuxostat; probenecid (uricosuric)
Prophylaxis during ULT initiationLow-dose colchicine or NSAID for 3-6 months (prevents mobilization flares)
(Textbook of Family Medicine 9e, p. 887)

4. Spondyloarthritis (SpA)

Definition

A group of related inflammatory arthritides linked by shared disease manifestations and genetic susceptibility. Major subtypes:
  • Ankylosing Spondylitis (AS) - axial predominant
  • Psoriatic Arthritis (PsA)
  • Reactive Arthritis (formerly Reiter's syndrome)
  • Enteropathic Arthritis (associated with IBD: Crohn's, UC)

Key Features Shared Across SpA

  • HLA-B27 association: ~90% of ankylosing spondylitis patients are HLA-B27 positive
  • Sacroiliitis and axial involvement
  • Enthesitis: inflammation at tendon/ligament insertions (hallmark of SpA - distinguishes from RA)
  • Asymmetric oligoarthritis of large joints
  • Dactylitis ("sausage digit")
  • RF negative (seronegative)
  • Eye involvement: uveitis (anterior)

Classification (ASAS)

  • Axial SpA (axSpA): back-dominated; subdivided into radiographic (= ankylosing spondylitis, with sacroiliac joint changes on X-ray) and non-radiographic
  • Peripheral SpA: peripheral joint-dominated
(Goldman-Cecil Medicine, p. 244)

Ankylosing Spondylitis (AS)

  • Chronic inflammatory disease of the spine and sacroiliac joints
  • Young men (< 40 years); insidious onset of inflammatory back pain (worse at rest/morning, improved with exercise - opposite of mechanical back pain)
  • Eventual fusion of vertebrae ("bamboo spine") on X-ray
  • Extra-articular: anterior uveitis, aortitis, apical pulmonary fibrosis, cauda equina syndrome
  • Treatment: NSAIDs first-line; physiotherapy; anti-TNF biologics for refractory disease

5. Psoriatic Arthritis (PsA)

  • Affects 5-7% of psoriasis patients (up to 40% of hospitalized patients with extensive psoriasis)
  • RF usually negative
  • Psoriatic skin lesions precede arthritis in 70% of cases; follow in 15%
  • Five clinical patterns: oligoarticular asymmetric (most common), symmetric polyarticular (resembles RA), DIP-predominant, axial/spondylitic, arthritis mutilans (most destructive)
  • DIP joint involvement and enthesitis distinguish it from RA
  • Arthritis mutilans: osteolysis of phalanges/metacarpals → "telescoping fingers"
  • X-ray: marginal erosions at DIP/PIP with new bone formation (periostitis) - "pencil-in-cup" deformity
  • Treatment: NSAIDs → DMARDs (methotrexate, sulfasalazine) → anti-TNF biologics for axial/refractory disease
(Textbook of Family Medicine 9e, p. 893)

6. Reactive Arthritis

  • Sterile inflammatory arthritis triggered by a distant infection (usually urogenital - Chlamydia - or enteric - Salmonella, Shigella, Yersinia, Campylobacter)
  • Classic triad (Reiter's): arthritis + urethritis + conjunctivitis ("can't see, can't pee, can't climb a tree")
  • Asymmetric oligoarthritis of lower limbs; enthesitis; dactylitis; oral ulcers; keratoderma blennorrhagica
  • HLA-B27 positive in ~75%
  • Usually self-limited (3-12 months); treat with NSAIDs; antibiotics for active infection; DMARDs for chronic cases

7. Septic (Infectious) Arthritis

Definition

An orthopedic emergency caused by bacterial (most commonly S. aureus) infection of a joint, usually via hematogenous spread. Loss of joint function in 25-50% of cases even with prompt treatment.

Epidemiology & Risk

  • Incidence: 2-10/100,000 in native joints; rises to 30-70/100,000 in RA patients
  • Risk factors: pre-existing joint disease (OA, RA, gout), IV drug use, immunosuppression, corticosteroids, prosthetic joints
  • Most commonly monoarticular: knee (50%), hip (25%), shoulder (15%) in adults

Clinical Features

  • Acute onset severe monoarticular pain, warmth, swelling, erythema
  • Fever in > 80% of children; only ~40% of adults
  • Restricted range of motion (most sensitive sign)
  • Position of comfort: slight flexion

Diagnosis

  • Joint aspiration is mandatory - synovial fluid: turbid, WBC > 50,000/mm³ (often > 100,000), predominantly neutrophils; Gram stain and culture
  • Blood cultures (often positive in hematogenous septic arthritis)
  • X-ray: initially normal; MRI for early osteomyelitis or hip involvement

Treatment

  • IV antibiotics targeting likely organisms; empirical anti-staphylococcal coverage (vancomycin for MRSA risk)
  • Surgical drainage/arthroscopic washout - often required; hip septic arthritis always requires surgical drainage (cannot adequately drain by aspiration alone)
  • Duration: typically 2-4 weeks IV → oral antibiotics
(Rosen's Emergency Medicine, p. 2730)

Quick Diagnostic Summary Table

TypeAge/SexJointsKey Lab/ImagingHallmark
OAElderly, F>M after 55Knees, hips, DIPX-ray: osteophytes, JSNNo systemic features; Heberden/Bouchard nodes
RA20-50, F>>MMCP, PIP, wrist (symmetric)RF+, Anti-CCP+, erosionsSymmetric synovitis, > 1 hr morning stiffness
GoutMen 40-60, postmeno F1st MTP, ankles, knees-ve birefringent crystals, ↑uric acidPodagra; acute severe monoarthritis
ASYoung men < 40Sacroiliac, spineHLA-B27+, bamboo spineInflammatory back pain, improved with exercise
PsAAny, psoriasis historyDIP, large joints, spineHLA+ (multiple), pencil-in-cupEnthesitis, DIP involvement, nail changes
ReactiveYoung adultsLower limb, asymmetricHLA-B27+, preceding infectionPost-infectious; classic triad
SepticAny (peak children/elderly)Knee > Hip > ShoulderWBC > 50,000 in joint fluid, +ve cultureOrthopedic emergency; fever + acute monoarthritis

Sources: Robbins & Kumar Basic Pathology, p. 790 | Textbook of Family Medicine 9e, pp. 873-893 | Goldman-Cecil Medicine, p. 244 | Rosen's Emergency Medicine, p. 2730 | Firestein & Kelley's Textbook of Rheumatology

All ?

Let me clarify what you mean before I research further.
Asking for Preferences

What do you mean by 'All'?

Mmm fine do you anle to make pdfs

Yes, I can make PDFs! I can take all the arthritis content from our previous response and generate a well-formatted PDF for you.
Asking for Preferences

What should the PDF include?

1 & 2

Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null && echo "OK"

Running Command

mkdir -p /home/daytona/workspace/arthritis-pdf && python3 -c "from reportlab.lib.pagesizes import A4; print('reportlab OK')"

Writing File

~/arthritis-pdf/generate_arthritis_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import ListFlowable, ListItem

OUTPUT = "/home/daytona/workspace/arthritis-pdf/Arthritis_Clinical_Overview.pdf"

# ── Colour palette ──────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1A3A5C")
MED_BLUE    = colors.HexColor("#2E6DA4")
LIGHT_BLUE  = colors.HexColor("#D6E8F7")
ACCENT      = colors.HexColor("#E84040")
GOLD        = colors.HexColor("#F5A623")
LIGHT_GREY  = colors.HexColor("#F2F4F7")
MID_GREY    = colors.HexColor("#B0BEC5")
WHITE       = colors.white
BLACK       = colors.black

# ── Styles ───────────────────────────────────────────────────────────────────
base = getSampleStyleSheet()

def S(name, parent="Normal", **kw):
    return ParagraphStyle(name, parent=base[parent], **kw)

styles = {
    "cover_title": S("cover_title", "Title",
        fontSize=34, textColor=WHITE, leading=42, alignment=TA_CENTER, spaceAfter=6),
    "cover_sub":   S("cover_sub", "Normal",
        fontSize=14, textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER, spaceAfter=4),
    "cover_note":  S("cover_note", "Normal",
        fontSize=10, textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER),
    "h1": S("h1", "Heading1",
        fontSize=18, textColor=WHITE, leading=24, spaceBefore=0, spaceAfter=0,
        leftIndent=0),
    "h2": S("h2", "Heading2",
        fontSize=13, textColor=DARK_BLUE, leading=18, spaceBefore=10, spaceAfter=4,
        borderPad=4),
    "h3": S("h3", "Heading3",
        fontSize=11, textColor=MED_BLUE, leading=15, spaceBefore=6, spaceAfter=3),
    "body": S("body", "Normal",
        fontSize=9.5, leading=14, spaceAfter=4, alignment=TA_JUSTIFY),
    "bullet": S("bullet", "Normal",
        fontSize=9.5, leading=13, leftIndent=14, spaceAfter=2),
    "table_hdr": S("table_hdr", "Normal",
        fontSize=9, textColor=WHITE, leading=12, alignment=TA_CENTER),
    "table_cell": S("table_cell", "Normal",
        fontSize=8.5, leading=12, alignment=TA_LEFT),
    "table_cell_c": S("table_cell_c", "Normal",
        fontSize=8.5, leading=12, alignment=TA_CENTER),
    "caption": S("caption", "Normal",
        fontSize=8, textColor=MID_GREY, alignment=TA_CENTER, spaceAfter=6),
    "key_point": S("key_point", "Normal",
        fontSize=9, leading=13, textColor=DARK_BLUE,
        leftIndent=10, rightIndent=10, spaceAfter=3),
    "footer": S("footer", "Normal",
        fontSize=7.5, textColor=MID_GREY, alignment=TA_CENTER),
}

PAGE_W, PAGE_H = A4
MARGIN = 2.0 * cm

# ── Helper builders ──────────────────────────────────────────────────────────
def section_header(title, subtitle=""):
    """Coloured banner for a major section."""
    data = [[Paragraph(f"<b>{title}</b>", styles["h1"])]]
    t = Table(data, colWidths=[PAGE_W - 2*MARGIN])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), DARK_BLUE),
        ("ROUNDEDCORNERS", [6,6,6,6]),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("LEFTPADDING",   (0,0), (-1,-1), 14),
    ]))
    elems = [t]
    if subtitle:
        elems.append(Paragraph(subtitle, styles["body"]))
    elems.append(Spacer(1, 6))
    return elems

def h2(text):
    return [Paragraph(text, styles["h2"]), HRFlowable(width="100%", thickness=1,
            color=MED_BLUE, spaceAfter=4)]

def h3(text):
    return [Paragraph(text, styles["h3"])]

def body(text):
    return [Paragraph(text, styles["body"])]

def bullets(items):
    return [Paragraph(f"• {i}", styles["bullet"]) for i in items]

def spacer(h=6):
    return [Spacer(1, h)]

def key_box(items, title="Key Points"):
    content = [Paragraph(f"<b>{title}</b>", styles["key_point"])]
    for i in items:
        content.append(Paragraph(f"◆  {i}", styles["key_point"]))
    t = Table([[content]], colWidths=[PAGE_W - 2*MARGIN])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), LIGHT_BLUE),
        ("ROUNDEDCORNERS", [6,6,6,6]),
        ("TOPPADDING",    (0,0), (-1,-1), 8),
        ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
        ("RIGHTPADDING",  (0,0), (-1,-1), 10),
        ("BOX", (0,0), (-1,-1), 1, MED_BLUE),
    ]))
    return [t, Spacer(1, 6)]

def make_table(headers, rows, col_widths=None):
    avail = PAGE_W - 2*MARGIN
    if col_widths is None:
        col_widths = [avail / len(headers)] * len(headers)
    hdr_row = [Paragraph(f"<b>{h}</b>", styles["table_hdr"]) for h in headers]
    data = [hdr_row]
    for row in rows:
        data.append([Paragraph(str(c), styles["table_cell"]) for c in row])
    t = Table(data, colWidths=col_widths, repeatRows=1)
    style = TableStyle([
        ("BACKGROUND",    (0,0), (-1,0),  DARK_BLUE),
        ("ROWBACKGROUNDS",(0,1), (-1,-1), [WHITE, LIGHT_GREY]),
        ("GRID",          (0,0), (-1,-1), 0.4, MID_GREY),
        ("TOPPADDING",    (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING",   (0,0), (-1,-1), 6),
        ("RIGHTPADDING",  (0,0), (-1,-1), 6),
        ("VALIGN",        (0,0), (-1,-1), "TOP"),
    ])
    t.setStyle(style)
    return [t, Spacer(1, 8)]

# ── Page callbacks ────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    # Top blue bar
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, PAGE_H - 0.7*cm, PAGE_W, 0.7*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica", 7)
    canvas.drawCentredString(PAGE_W/2, PAGE_H - 0.5*cm, "ARTHRITIS — Clinical Overview")
    # Bottom bar
    canvas.setFillColor(LIGHT_GREY)
    canvas.rect(0, 0, PAGE_W, 1.0*cm, fill=1, stroke=0)
    canvas.setFillColor(MID_GREY)
    canvas.setFont("Helvetica", 7)
    canvas.drawString(MARGIN, 0.35*cm, "Sources: Robbins & Kumar Basic Pathology | Textbook of Family Medicine 9e | Goldman-Cecil Medicine | Rosen's Emergency Medicine | Firestein & Kelley's Rheumatology")
    canvas.drawRightString(PAGE_W - MARGIN, 0.35*cm, f"Page {doc.page}")
    canvas.restoreState()

def cover_page():
    from reportlab.platypus import Frame, BaseDocTemplate
    # We'll fake a cover with a coloured table
    elems = []
    # Blue banner fill
    cover_data = [[
        Paragraph("<b>ARTHRITIS</b>", styles["cover_title"]),
    ]]
    ct = Table(cover_data, colWidths=[PAGE_W - 2*MARGIN])
    ct.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), DARK_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 40),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("LEFTPADDING",   (0,0), (-1,-1), 20),
        ("RIGHTPADDING",  (0,0), (-1,-1), 20),
        ("ROUNDEDCORNERS",[8,8,8,8]),
    ]))
    elems.append(ct)
    sub_data = [[Paragraph("Clinical Deep-Dive: All Types, Pathology, Diagnosis & Treatment", styles["cover_sub"])]]
    st = Table(sub_data, colWidths=[PAGE_W - 2*MARGIN])
    st.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), MED_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 12),
        ("BOTTOMPADDING", (0,0), (-1,-1), 12),
        ("ROUNDEDCORNERS",[0,0,8,8]),
    ]))
    elems.append(st)
    elems.append(Spacer(1, 16))

    # Type overview boxes
    types = [
        ("1", "Osteoarthritis",       "Degenerative",      GOLD),
        ("2", "Rheumatoid Arthritis", "Autoimmune",        ACCENT),
        ("3", "Gout",                 "Crystal",           colors.HexColor("#27AE60")),
        ("4", "Spondyloarthritis",    "Seronegative",      MED_BLUE),
        ("5", "Psoriatic Arthritis",  "Seronegative SpA",  colors.HexColor("#8E44AD")),
        ("6", "Reactive Arthritis",   "Post-infectious",   colors.HexColor("#E67E22")),
        ("7", "Septic Arthritis",     "Infectious/Emergency", ACCENT),
    ]
    box_rows = []
    for num, name, tag, col in types:
        box_rows.append([
            Paragraph(f"<b>{num}</b>", ParagraphStyle("n", fontSize=18, textColor=WHITE, alignment=TA_CENTER)),
            Paragraph(f"<b>{name}</b><br/><font size=8 color='#FFFFFF'>{tag}</font>",
                      ParagraphStyle("t", fontSize=11, textColor=WHITE, leading=15)),
        ])
    for i, (num, name, tag, col) in enumerate(types):
        row_data = [[
            Paragraph(f"<b>{i+1}</b>", ParagraphStyle("nn", fontSize=16, textColor=WHITE, alignment=TA_CENTER)),
            Paragraph(f"<b>{name}</b><br/><font size=8>{tag}</font>",
                      ParagraphStyle("tt", fontSize=11, textColor=WHITE, leading=15)),
        ]]
        rt = Table(row_data, colWidths=[1.2*cm, PAGE_W - 2*MARGIN - 1.2*cm - 0.2*cm])
        rt.setStyle(TableStyle([
            ("BACKGROUND",    (0,0), (-1,-1), col),
            ("TOPPADDING",    (0,0), (-1,-1), 8),
            ("BOTTOMPADDING", (0,0), (-1,-1), 8),
            ("LEFTPADDING",   (0,0), (-1,-1), 10),
            ("ROUNDEDCORNERS",[6,6,6,6]),
        ]))
        elems.append(rt)
        elems.append(Spacer(1, 5))

    elems.append(Spacer(1, 20))
    note_data = [[Paragraph(
        "Sources: Robbins & Kumar Basic Pathology • Textbook of Family Medicine 9e • Goldman-Cecil Medicine • Rosen's Emergency Medicine • Firestein & Kelley's Textbook of Rheumatology",
        styles["caption"])]]
    nt = Table(note_data, colWidths=[PAGE_W - 2*MARGIN])
    nt.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), LIGHT_GREY),
        ("TOPPADDING",    (0,0), (-1,-1), 8),
        ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("BOX", (0,0), (-1,-1), 0.5, MID_GREY),
    ]))
    elems.append(nt)
    elems.append(PageBreak())
    return elems

# ── Content ───────────────────────────────────────────────────────────────────
def build_content():
    E = []

    # ── COVER ─────────────────────────────────────────────────────────────────
    E += cover_page()

    # ── 1. OSTEOARTHRITIS ─────────────────────────────────────────────────────
    E += section_header("1. Osteoarthritis (OA)", "Degenerative Joint Disease — Most Common Arthritis")
    E += key_box([
        "Most common form of arthritis; affects ~20% of U.S. population.",
        "Primarily degenerative — cartilage breakdown with secondary inflammation.",
        "Prevalence rises exponentially after age 50; ~40% of people >70 are affected.",
        "NSAIDs (not COX-2 inhibitors alone) are first-line pharmacologic treatment.",
    ])
    E += h2("Epidemiology & Classification")
    E += body("OA occurs about equally in men and women ages 45–55, but is more common in women after 55. "
              "It is found radiographically in almost all 75-year-olds, most of whom are asymptomatic.")
    E += make_table(
        ["Type", "Description", "Examples"],
        [
            ["Primary (Idiopathic)", "Insidious onset; aging phenomenon; oligoarticular", "Knee, hip, lumbar spine OA in the elderly"],
            ["Hereditary", "Collagen gene defects; inflammatory hand OA runs in families", "Heberden nodes, Bouchard nodes in women"],
            ["Secondary", "Prior cartilage damage from identifiable cause", "Post-trauma, obesity, hemochromatosis, RA, gout, CPPD, acromegaly, neuropathy"],
        ],
        col_widths=[3.5*cm, 7*cm, 6.5*cm]
    )

    E += h2("Pathogenesis")
    E += body("OA stems from <b>biomechanical stress</b> on articular cartilage, with genetic factors (GDF5, RUNX2, SMAD3 loci) amplifying risk. "
              "The process evolves in three stages:")
    E += bullets([
        "<b>Stage 1 – Chondrocyte Injury:</b> Genetic/biomechanical insults damage Type II collagen and proteoglycans in articular cartilage.",
        "<b>Stage 2 – Early OA:</b> Chondrocytes proliferate and release BMP (repair attempt). MMPs degrade collagen and proteoglycans; PGE₂, NO, TNF drive further damage — degradation exceeds repair.",
        "<b>Stage 3 – Late OA:</b> Chondrocyte dropout and apoptosis, subchondral bone sclerosis and cysts, osteophyte formation, loose bodies in joint space.",
    ])

    E += h2("Clinical Features")
    E += make_table(
        ["Feature", "Details"],
        [
            ["Onset", "Insidious; pain worsens with activity, relieved by rest"],
            ["Morning stiffness", "< 30 minutes (key distinction from RA)"],
            ["Joint involvement", "Weight-bearing: knees, hips, lumbar/cervical spine, 1st MTP, DIP/PIP of hands"],
            ["Heberden nodes", "Bony enlargement at DIP joints (osteophytes)"],
            ["Bouchard nodes", "Bony enlargement at PIP joints"],
            ["Crepitus", "Grating sensation on joint movement"],
            ["Systemic features", "ABSENT — OA is purely articular"],
            ["Radiographic findings", "Joint space narrowing, osteophytes, subchondral sclerosis, subchondral cysts"],
        ],
        col_widths=[5*cm, 12*cm]
    )

    E += h2("Investigations")
    E += bullets([
        "X-ray: joint space narrowing, osteophytes, subchondral sclerosis/cysts — most important investigation",
        "Serology: RF and ANA negative; no specific OA biomarker",
        "Synovial fluid: non-inflammatory (WBC < 2,000/mm³); no crystals",
        "MRI: best for early cartilage damage (not routine in most cases)",
    ])

    E += h2("Treatment")
    E += make_table(
        ["Category", "Intervention"],
        [
            ["Non-pharmacologic", "Weight loss (reduces joint load), low-impact exercise (swimming, cycling), physiotherapy, quadriceps strengthening, assistive devices (cane, braces)"],
            ["Pharmacologic — 1st line", "NSAIDs (oral or topical for knee/hand); acetaminophen for mild pain"],
            ["Pharmacologic — adjuncts", "Intra-articular corticosteroids (short-term flare relief); intra-articular hyaluronic acid (controversial)"],
            ["Surgical", "Joint replacement (arthroplasty) for severe, refractory disease unresponsive to conservative measures"],
        ],
        col_widths=[4.5*cm, 12.5*cm]
    )
    E += spacer(8)

    # ── 2. RHEUMATOID ARTHRITIS ───────────────────────────────────────────────
    E += section_header("2. Rheumatoid Arthritis (RA)", "Chronic Systemic Autoimmune Inflammatory Disease")
    E += key_box([
        "Affects 1–2% of adults; female predominance 3:1; peak incidence ages 20–50.",
        "Symmetric synovitis with morning stiffness >1 hour is the hallmark.",
        ">70% of polyarticular RF-positive RA patients develop joint erosions within 2 years without treatment.",
        "Start DMARDs early — before irreversible joint destruction occurs.",
    ])

    E += h2("Pathogenesis")
    E += bullets([
        "<b>Genetic:</b> HLA-DRB1 'shared epitope' is the strongest genetic risk factor; higher concordance in monozygotic twins.",
        "<b>Trigger:</b> Unknown inciting event (possibly infectious or environmental) in a genetically susceptible host.",
        "<b>Pannus formation:</b> Synovial lining cells and subsynovial vessels proliferate → aggressive pannus invades cartilage and bone.",
        "<b>Immune cascade:</b> T-cell and B-cell activation; key cytokines TNF-α, IL-1, IL-6 drive inflammation and erosion.",
        "<b>Autoantibodies:</b> Rheumatoid factor (RF) targets IgG Fc; Anti-CCP (ACPA) — more specific, detectable years before symptoms.",
    ])

    E += h2("Clinical Features")
    E += make_table(
        ["System", "Manifestations"],
        [
            ["Articular (early)", "Symmetric synovitis of MCPs, PIPs, wrists; spares DIP joints"],
            ["Articular (late)", "Ulnar deviation, swan-neck/boutonnière deformities, Z-thumb; joint ankylosis"],
            ["Constitutional", "Fatigue, fever, weight loss, malaise (often precede joint symptoms)"],
            ["Rheumatoid nodules", "Subcutaneous; over pressure points (olecranon, fingers); indicate seropositive disease"],
            ["Pulmonary", "Interstitial lung disease, pleural effusion, pulmonary nodules, Caplan syndrome"],
            ["Cardiac", "Pericarditis, accelerated atherosclerosis (major cause of mortality), valvular disease"],
            ["Ocular", "Scleritis, episcleritis, sicca syndrome (secondary Sjögren's)"],
            ["Neurologic", "Atlantoaxial subluxation (C1–C2 instability → spinal cord compression risk), peripheral neuropathy"],
            ["Haematologic", "Anaemia of chronic disease, Felty syndrome (RA + splenomegaly + neutropenia)"],
        ],
        col_widths=[4.5*cm, 12.5*cm]
    )

    E += h2("ACR 1987 Diagnostic Criteria (≥4 of 7, symptoms ≥6 weeks)")
    E += make_table(
        ["#", "Criterion", "Definition"],
        [
            ["1", "Morning stiffness", "In and around joints; ≥1 hour before maximal improvement"],
            ["2", "Arthritis of ≥3 joint areas", "Soft-tissue swelling or fluid in ≥3 joints"],
            ["3", "Arthritis of hand joints", "Wrists, MCPs, or PIPs involved"],
            ["4", "Symmetric arthritis", "Simultaneous bilateral involvement"],
            ["5", "Rheumatoid nodules", "Subcutaneous nodules over bony prominences"],
            ["6", "Serum RF positive", "Positive by any method in <5% of normal controls"],
            ["7", "Radiographic changes", "Erosions or periarticular osteopenia on hand/wrist X-ray"],
        ],
        col_widths=[0.8*cm, 5*cm, 11.2*cm]
    )

    E += h2("Investigations")
    E += bullets([
        "RF: positive in ~80% of RA; not specific (also positive in SLE, Sjögren's, infections, elderly)",
        "Anti-CCP (ACPA): ~95% specific for RA; detectable years before clinical disease",
        "Elevated ESR and CRP — reflect inflammatory activity",
        "FBC: normocytic anaemia, thrombocytosis in active disease",
        "Synovial fluid: inflammatory (WBC >2,000/mm³, often >50,000); no crystals",
        "X-ray hands/feet: periarticular osteopenia → marginal erosions → joint space narrowing",
        "MRI/Ultrasound: detect early synovitis and erosions before X-ray changes",
    ])

    E += h2("Treatment — Treat-to-Target Strategy")
    E += make_table(
        ["Category", "Agents", "Notes"],
        [
            ["Symptomatic", "NSAIDs, corticosteroids (oral/intra-articular)", "Bridging only; not disease-modifying"],
            ["Conventional DMARDs (csDMARDs)", "Methotrexate (1st-line), hydroxychloroquine, sulfasalazine, leflunomide", "MTX is anchor drug; combinations used (triple therapy)"],
            ["Biologic DMARDs — anti-TNF", "Etanercept, adalimumab, infliximab, certolizumab, golimumab", "For inadequate response to csDMARDs"],
            ["Biologic DMARDs — other", "Tocilizumab (IL-6 inhibitor), rituximab (B-cell), abatacept (T-cell co-stim)", "Alternative biologics depending on profile"],
            ["Targeted synthetic DMARDs", "Tofacitinib, baricitinib, upadacitinib (JAK inhibitors)", "Oral; used when biologics fail or not tolerated"],
        ],
        col_widths=[3.5*cm, 6*cm, 7.5*cm]
    )
    E.append(PageBreak())

    # ── 3. GOUT ──────────────────────────────────────────────────────────────
    E += section_header("3. Gout (Crystal Arthropathy)", "Monosodium Urate Crystal Deposition Disease")
    E += key_box([
        "Primarily affects men 40–60 years and postmenopausal women.",
        "Hyperuricemia (usually >8 mg/dL) is the underlying abnormality — but asymptomatic hyperuricemia is not a disease.",
        "Definitive diagnosis: needle-shaped, negatively birefringent crystals on polarized light microscopy.",
        "First MTP joint (podagra) involved in 50% of initial attacks; eventually in 75–90% of patients.",
    ])

    E += h2("Pathophysiology")
    E += make_table(
        ["Mechanism", "Details"],
        [
            ["Reduced excretion (90%)", "Renal underexcretion of urate; genetic predisposition + thiazides, low-dose aspirin, cyclosporine, renal failure"],
            ["Overproduction (10%)", "Inborn errors (HGPRT deficiency — Lesch-Nyhan), high purine diet, myeloproliferative disorders, tumour lysis"],
            ["Crystal deposition", "MSU crystals form in cooler peripheral joints → phagocytosed by neutrophils → IL-1β release → acute intense inflammation"],
            ["Tophi", "Chronic urate deposits in soft tissue, cartilage, bone, ear pinnae; indicate years of uncontrolled hyperuricemia"],
        ],
        col_widths=[4.5*cm, 12.5*cm]
    )

    E += h2("Clinical Stages")
    E += make_table(
        ["Stage", "Features"],
        [
            ["Asymptomatic hyperuricemia", "Elevated uric acid; no symptoms; typically takes ~20 years before first attack"],
            ["Acute gouty arthritis", "Sudden severe monoarticular pain (often nocturnal); exquisite tenderness; swelling, warmth, erythema; self-limited in days–weeks"],
            ["Intercritical gout", "Symptom-free intervals; attacks become more frequent and prolonged over time"],
            ["Chronic tophaceous gout", "Persistent hyperuricemia → tophi; chronic destructive arthritis; renal complications (urate nephropathy, uric acid stones)"],
        ],
        col_widths=[5*cm, 12*cm]
    )

    E += h2("Diagnosis")
    E += bullets([
        "<b>Definitive:</b> Needle-shaped, negatively birefringent monosodium urate crystals on polarized light microscopy of synovial fluid or tophi material",
        "<b>Presumptive:</b> Clinical features + hyperuricemia + rapid response to colchicine/NSAIDs",
        "Serum uric acid: usually >8 mg/dL (note: may be normal during acute attack)",
        "Joint aspiration: cloudy fluid, high WBC (polymorphonuclear predominance)",
        "X-ray (late disease): punched-out erosions with overhanging edges ('rat bite' erosions), tophi calcifications",
        "Note: In women and elderly, gout may be <b>polyarticular</b> and mimic RA; tophi may be mistaken for rheumatoid nodules",
    ])

    E += h2("Treatment")
    E += make_table(
        ["Phase", "Treatment", "Notes"],
        [
            ["Acute attack", "NSAIDs (indomethacin, naproxen), colchicine, corticosteroids (oral/IA)", "Start within 24 hours of attack onset for best effect"],
            ["Urate-lowering therapy (ULT)", "Allopurinol (xanthine oxidase inhibitor) — 1st line; Febuxostat; Probenecid (uricosuric)", "Target serum uric acid <6 mg/dL (<5 mg/dL in tophaceous gout)"],
            ["Prophylaxis during ULT initiation", "Low-dose colchicine or NSAID for 3–6 months", "Prevents mobilization flares as urate depots dissolve"],
            ["Dietary/lifestyle", "Reduce red meat, seafood, fructose-sweetened beverages, alcohol (especially beer); increase hydration", "Address secondary causes: review diuretics, aspirin"],
        ],
        col_widths=[4*cm, 6.5*cm, 6.5*cm]
    )
    E += spacer(8)

    # ── 4. SPONDYLOARTHRITIS ─────────────────────────────────────────────────
    E += section_header("4. Spondyloarthritis (SpA)", "HLA-B27 Associated Seronegative Arthritides")
    E += key_box([
        "Group of related syndromes: ankylosing spondylitis, psoriatic arthritis, reactive arthritis, enteropathic arthritis.",
        "HLA-B27 positive in ~90% of ankylosing spondylitis patients.",
        "RF negative (seronegative); enthesitis is the pathologic hallmark.",
        "Classified as axial SpA (spine/sacroiliac predominant) or peripheral SpA.",
    ])

    E += h2("Common Features Across All SpA Subtypes")
    E += make_table(
        ["Feature", "Description"],
        [
            ["Enthesitis", "Inflammation at tendon/ligament insertions (e.g., Achilles, plantar fascia, iliac crest) — HALLMARK of SpA"],
            ["Sacroiliitis", "Inflammation of sacroiliac joints; key diagnostic feature on imaging"],
            ["Asymmetric oligoarthritis", "Typically lower limb large joints (knee, ankle, hip)"],
            ["Dactylitis", "'Sausage digit' — diffuse swelling of an entire finger/toe; very specific for SpA"],
            ["Anterior uveitis", "Most common extra-articular feature across SpA subtypes"],
            ["HLA-B27", "Present in ~90% AS, ~75% reactive arthritis, ~50% psoriatic arthritis with axial disease"],
            ["RF negative", "Key feature distinguishing SpA from RA"],
        ],
        col_widths=[4*cm, 13*cm]
    )

    E += h2("Ankylosing Spondylitis (AS)")
    E += bullets([
        "Chronic inflammatory disease of spine and sacroiliac joints; predominantly young men <40 years",
        "<b>Inflammatory back pain:</b> insidious onset, worse at night and in the morning, <b>improved with exercise</b> (opposite of mechanical back pain), relieved poorly by rest",
        "Schober test: measures lumbar flexion limitation",
        "X-ray: sacroiliitis → 'bamboo spine' (syndesmophytes, spinal fusion) in late disease",
        "MRI: detects active sacroiliitis before X-ray changes (bone marrow oedema)",
        "Extra-articular: anterior uveitis, aortitis, aortic regurgitation, apical pulmonary fibrosis, cauda equina syndrome",
        "<b>Treatment:</b> NSAIDs (first-line) + physiotherapy (mandatory); anti-TNF biologics (adalimumab, etanercept) for refractory disease; IL-17 inhibitors (secukinumab, ixekizumab)",
    ])
    E += spacer(8)

    # ── 5. PSORIATIC ARTHRITIS ────────────────────────────────────────────────
    E += section_header("5. Psoriatic Arthritis (PsA)", "Seronegative SpA Associated with Psoriasis")
    E += key_box([
        "Affects 5–7% of psoriasis patients (up to 40% of hospitalised patients with extensive psoriasis).",
        "Psoriatic skin lesions precede arthritis in 70% of cases; family history is important when skin lesions absent.",
        "DIP joint involvement and enthesitis distinguish PsA from RA.",
        "RF usually negative.",
    ])
    E += h2("Clinical Patterns (5 Types)")
    E += make_table(
        ["Pattern", "Features", "Frequency"],
        [
            ["Oligoarticular asymmetric", "Asymmetric involvement of <5 joints; large joints; most common presentation", "~70% (classic)"],
            ["Symmetric polyarticular", "Resembles RA; multiple small joints; but DIP involved, RF negative", "~15%"],
            ["DIP-predominant", "Mainly DIP joints; associated with nail disease (pitting, onycholysis)", "~5%"],
            ["Spondylitic/axial", "Sacroiliitis ± spondylitis; may be asymptomatic radiographically", "~5%"],
            ["Arthritis mutilans", "Most destructive; osteolysis of phalanges/metacarpals → 'telescoping fingers' (opera glass hand)", "~5%"],
        ],
        col_widths=[4*cm, 9*cm, 4*cm]
    )
    E += h2("Diagnosis & Treatment")
    E += bullets([
        "X-ray: marginal erosions at DIP/PIP with periostitis (new bone formation); 'pencil-in-cup' deformity in arthritis mutilans",
        "CASPAR criteria used for diagnosis (psoriasis + arthritis + RF negative + imaging findings)",
        "<b>Treatment:</b> NSAIDs (1st line) → DMARDs (methotrexate, sulfasalazine) → anti-TNF biologics for axial/refractory disease",
        "IL-17 inhibitors (secukinumab) and IL-12/23 inhibitors (ustekinumab) also approved",
        "Avoid corticosteroid injections through psoriatic skin (colonised with Staph/Strep)",
    ])
    E += spacer(8)

    # ── 6. REACTIVE ARTHRITIS ─────────────────────────────────────────────────
    E += section_header("6. Reactive Arthritis", "Post-infectious Sterile Arthritis (formerly Reiter's Syndrome)")
    E += key_box([
        "Sterile inflammatory arthritis triggered by a distant infection — usually urogenital or enteric.",
        "Classic triad: arthritis + urethritis + conjunctivitis ('can't see, can't pee, can't climb a tree').",
        "HLA-B27 positive in ~75%; strongly associated.",
        "Usually self-limited (3–12 months).",
    ])
    E += h2("Triggering Organisms")
    E += make_table(
        ["Route", "Organisms"],
        [
            ["Urogenital (STI)", "Chlamydia trachomatis (most common in developed countries)"],
            ["Enteric (food/waterborne)", "Salmonella, Shigella, Yersinia, Campylobacter, Clostridioides difficile"],
        ],
        col_widths=[4*cm, 13*cm]
    )
    E += h2("Clinical Features & Treatment")
    E += bullets([
        "Asymmetric oligoarthritis of lower limbs (knees, ankles, feet) 1–4 weeks after infection",
        "Enthesitis (Achilles, plantar fascia), dactylitis",
        "Mucocutaneous: oral ulcers (painless), keratoderma blennorrhagica (psoriasiform skin lesions on palms/soles), circinate balanitis",
        "Ocular: conjunctivitis (mild, bilateral) or anterior uveitis",
        "<b>Treatment:</b> NSAIDs for arthritis; antibiotics for active infection (Chlamydia: doxycycline/azithromycin); DMARDs (sulfasalazine, methotrexate) for chronic/recurrent disease",
    ])
    E += spacer(8)

    # ── 7. SEPTIC ARTHRITIS ───────────────────────────────────────────────────
    E += section_header("7. Septic (Infectious) Arthritis", "Orthopedic Emergency — Prompt Diagnosis Required")
    E += key_box([
        "Orthopedic emergency: loss of joint function in 25–50% of patients even with prompt treatment.",
        "Most common organism: Staphylococcus aureus (all ages).",
        "Incidence: 2–10/100,000 in native joints; jumps to 30–70/100,000 in RA patients.",
        "Joint aspiration is mandatory for diagnosis — do not delay pending imaging.",
    ])
    E += h2("Pathways & Organisms")
    E += make_table(
        ["Mechanism", "Details"],
        [
            ["Hematogenous (most common)", "Bacteraemia seeds synovial membrane; explains why septic arthritis may coexist with osteomyelitis"],
            ["Direct inoculation", "Trauma, joint aspiration, or injection"],
            ["Contiguous spread", "Adjacent osteomyelitis, soft tissue infection"],
        ],
        col_widths=[4.5*cm, 12.5*cm]
    )
    E += make_table(
        ["Population", "Common Organisms"],
        [
            ["All adults", "S. aureus (most common), Streptococcus spp."],
            ["Sexually active young adults", "Neisseria gonorrhoeae (most common cause of septic arthritis in <40 y adults)"],
            ["IV drug users, immunocompromised", "S. aureus (including MRSA), Gram-negative bacilli (Pseudomonas)"],
            ["Neonates/infants", "S. aureus, Group B Streptococcus, Gram-negative rods"],
            ["Prosthetic joint (early <3 months)", "S. aureus, coagulase-negative staph, Gram-negatives"],
        ],
        col_widths=[5*cm, 12*cm]
    )

    E += h2("Clinical Features")
    E += bullets([
        "Acute onset severe monoarticular pain; exacerbated by any range of motion",
        "Cardinal signs: swelling, erythema, warmth; joint held in position of slight flexion (greatest comfort)",
        "Fever >80% of children; only ~40% of adults (especially immunosuppressed/steroid users may have minimal fever)",
        "Adults: knee (50%), hip (25%), shoulder (15%)",
        "Gonococcal septic arthritis: may present with migratory polyarthralgia → monoarthritis + skin vesiculopustular lesions + tenosynovitis",
    ])

    E += h2("Diagnosis")
    E += make_table(
        ["Investigation", "Expected Findings"],
        [
            ["Joint aspiration (mandatory)", "Turbid fluid; WBC >50,000/mm³ (often >100,000), >90% neutrophils; Gram stain and culture"],
            ["Blood cultures", "Often positive in hematogenous septic arthritis (draw before antibiotics)"],
            ["Serum WBC, CRP, ESR", "Elevated but non-specific"],
            ["X-ray", "Initially normal; useful to exclude fracture; late: joint space loss, osteomyelitis"],
            ["MRI", "Best for hip septic arthritis; detects osteomyelitis, soft tissue extension"],
            ["Ultrasound", "Detects joint effusion; guides aspiration (especially hip)"],
        ],
        col_widths=[4.5*cm, 12.5*cm]
    )

    E += h2("Treatment")
    E += bullets([
        "<b>IV antibiotics empirically:</b> anti-staphylococcal (flucloxacillin or vancomycin for MRSA risk); adjust to culture/sensitivity",
        "<b>Duration:</b> typically 2–4 weeks IV → oral switch; total 4–6 weeks for S. aureus",
        "<b>Surgical drainage:</b> hip joint always requires surgical drainage (arthroscopy or open); knee can often be managed with repeated aspiration",
        "Gonococcal arthritis: IV ceftriaxone → oral switch; excellent prognosis",
        "Physiotherapy: early passive range of motion once infection controlled to prevent ankylosis",
    ])
    E.append(PageBreak())

    # ── COMPARISON TABLES ─────────────────────────────────────────────────────
    E += section_header("Summary & Comparison Tables", "Quick Reference for Diagnosis and Differentiation")
    E += spacer(6)

    E += h2("Table 1: Diagnostic Comparison — All 7 Types")
    E += make_table(
        ["Type", "Age/Sex", "Joints Affected", "Key Lab/Imaging", "Hallmark Feature"],
        [
            ["Osteoarthritis", "Elderly; F>M after 55", "Knees, hips, lumbar spine, DIP/PIP", "X-ray: osteophytes, JSN; Serology negative", "No systemic features; Heberden/Bouchard nodes; morning stiffness <30 min"],
            ["Rheumatoid Arthritis", "20–50 y; F>>M (3:1)", "MCP, PIP, wrists (symmetric); spares DIP", "RF+, Anti-CCP+, ↑ESR/CRP; X-ray erosions", "Symmetric synovitis; morning stiffness >1 hr; systemic features; extra-articular manifestations"],
            ["Gout", "Men 40–60; postmeno women", "1st MTP (podagra), ankles, knees", "↑Uric acid; −ve birefringent crystals in fluid", "Acute severe monoarthritis; nocturnal onset; podagra; tophi"],
            ["Ankylosing Spondylitis", "Young men <40", "Sacroiliac joints, spine", "HLA-B27+; MRI sacroiliitis; bamboo spine on X-ray", "Inflammatory back pain improved with exercise; enthesitis; iritis"],
            ["Psoriatic Arthritis", "Any; psoriasis history", "DIP joints, large joints, axial; asymmetric", "HLA+(multiple); pencil-in-cup deformity; RF neg", "Nail changes (pitting, onycholysis); DIP involvement; enthesitis; dactylitis"],
            ["Reactive Arthritis", "Young adults post-infection", "Lower limb large joints; asymmetric", "HLA-B27+; cultures of infection trigger", "Post-infectious; classic triad (urethritis, conjunctivitis, arthritis)"],
            ["Septic Arthritis", "Any (children, elderly, immunocomp)", "Knee > Hip > Shoulder; monoarticular", "Joint fluid WBC >50,000; Gram stain/culture +ve", "Orthopedic emergency; fever; acute severe monoarthritis"],
        ],
        col_widths=[3*cm, 3*cm, 4*cm, 4*cm, 4.5*cm]
    )

    E += h2("Table 2: OA vs. RA — Head-to-Head Comparison")
    E += make_table(
        ["Feature", "Osteoarthritis", "Rheumatoid Arthritis"],
        [
            ["Primary mechanism", "Mechanical injury to articular cartilage", "Autoimmunity (T-cell and antibody-mediated)"],
            ["Role of inflammation", "Secondary; exacerbates cartilage damage", "Primary — drives all joint destruction"],
            ["Joints involved", "Weight-bearing: knees, hips; DIP joints", "Small joints: MCPs, PIPs, wrists (symmetric); spares DIP"],
            ["Morning stiffness", "<30 minutes", ">1 hour"],
            ["Systemic involvement", "No", "Yes: lungs, heart, eyes, cervical spine, blood"],
            ["Serology", "RF, ANA negative", "RF+ in 80%; Anti-CCP+ in ~70% (95% specific)"],
            ["Pathology", "Cartilage degeneration, osteophytes, subchondral cysts", "Pannus formation, marginal erosions, ankylosis"],
            ["Synovial fluid", "Non-inflammatory (<2,000 WBC/mm³)", "Inflammatory (>2,000–50,000+ WBC/mm³)"],
            ["Treatment", "NSAIDs, physiotherapy, joint replacement", "DMARDs (MTX), biologics (anti-TNF, IL-6i, JAKi)"],
        ],
        col_widths=[4.5*cm, 6*cm, 6*cm]
    )

    E += h2("Table 3: Synovial Fluid Analysis in Arthritis")
    E += make_table(
        ["Category", "WBC/mm³", "Appearance", "Conditions"],
        [
            ["Normal", "<200", "Clear, viscous", "Normal joint"],
            ["Non-inflammatory", "200–2,000", "Clear/yellow, viscous", "OA, trauma, early SLE"],
            ["Inflammatory", "2,000–50,000", "Turbid, yellow, low viscosity", "RA, gout, pseudogout, SpA, reactive arthritis"],
            ["Septic (presumed)", ">50,000 (often >100,000)", "Turbid/purulent, very low viscosity", "Bacterial septic arthritis"],
            ["Haemorrhagic", "Variable (RBCs)", "Red/bloody", "Trauma, haemophilia, pigmented villonodular synovitis"],
        ],
        col_widths=[3.5*cm, 3.5*cm, 5*cm, 5.5*cm]
    )

    E += h2("Table 4: Crystal Arthropathies Comparison")
    E += make_table(
        ["Feature", "Gout (MSU)", "Pseudogout (CPPD)"],
        [
            ["Crystal type", "Monosodium urate (MSU)", "Calcium pyrophosphate dihydrate (CPPD)"],
            ["Birefringence", "Negatively birefringent; needle-shaped", "Weakly positively birefringent; rhomboid-shaped"],
            ["Common joints", "1st MTP (podagra), ankles, knees", "Knees (most common), wrists, hips"],
            ["Age/sex", "Middle-aged men; postmeno women", "Elderly; equal sex distribution"],
            ["X-ray", "Punched-out erosions; tophi calcifications", "Chondrocalcinosis (calcification in cartilage)"],
            ["Underlying causes", "Hyperuricemia; thiazides, renal failure", "Hyperparathyroidism, haemochromatosis, hypomagnesaemia"],
            ["Acute treatment", "NSAIDs, colchicine, corticosteroids", "NSAIDs, colchicine, corticosteroids"],
            ["Long-term treatment", "Allopurinol/febuxostat (urate-lowering)", "No specific crystal-reducing therapy available"],
        ],
        col_widths=[4*cm, 6*cm, 7*cm]
    )

    E += h2("Table 5: Key Drug Summary in Arthritis Management")
    E += make_table(
        ["Drug/Class", "Mechanism", "Used In", "Key Side Effects"],
        [
            ["NSAIDs", "COX-1/2 inhibition → ↓prostaglandins", "OA, RA, Gout (acute), SpA, PsA, Reactive arthritis", "GI ulcers, renal impairment, CV risk, fluid retention"],
            ["Colchicine", "Inhibits microtubule polymerisation → ↓neutrophil chemotaxis", "Gout (acute + prophylaxis), CPPD, pericarditis", "GI: diarrhoea, nausea; myopathy (high dose); drug interactions (CYP3A4)"],
            ["Allopurinol", "Xanthine oxidase inhibitor → ↓uric acid synthesis", "Gout prevention (ULT)", "Rash (SJS in HLA-B*58:01 carriers), hypersensitivity syndrome"],
            ["Methotrexate", "Folic acid antagonist → anti-inflammatory via adenosine pathway", "RA (1st-line DMARD), PsA, other inflammatory arthritis", "Hepatotoxicity, myelosuppression, mucositis, pneumonitis; folate supplementation required"],
            ["Anti-TNF biologics", "Block TNF-α (key pro-inflammatory cytokine)", "RA, AS, PsA, IBD-related arthritis", "Infection risk (TB reactivation — screen with IGRA before use), injection site reactions"],
            ["IL-6 inhibitors (tocilizumab)", "Block IL-6 receptor", "RA (especially with systemic features)", "Infection, dyslipidaemia, liver enzyme elevation; may mask fever"],
            ["JAK inhibitors (tofacitinib)", "Inhibit JAK1/3 → ↓cytokine signalling", "RA, PsA, AS", "Infection, VTE risk, CV events; avoid in high CV risk patients"],
            ["Corticosteroids", "Broad anti-inflammatory via glucocorticoid receptor", "Bridging in RA, acute gout, septic arthritis (adjunct in some cases)", "Osteoporosis, hyperglycaemia, adrenal suppression, Cushing's features with prolonged use"],
        ],
        col_widths=[3.5*cm, 4*cm, 4*cm, 5.5*cm]
    )
    E += spacer(8)

    # Sources
    sources = [
        "Robbins & Kumar Basic Pathology, p. 790 — OA pathogenesis and OA vs RA comparison",
        "Textbook of Family Medicine 9e, pp. 873–893 — OA, RA, Gout, PsA, Reactive Arthritis",
        "Goldman-Cecil Medicine (International Edition) — Spondyloarthritis (Chapter 244)",
        "Rosen's Emergency Medicine — Septic Arthritis (p. 2730)",
        "Firestein & Kelley's Textbook of Rheumatology (2-Volume Set) — OA genetics, SpA",
    ]
    E += h2("Sources")
    E += bullets(sources)

    return E

# ── Build PDF ─────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=MARGIN,
    rightMargin=MARGIN,
    topMargin=MARGIN + 0.7*cm,
    bottomMargin=MARGIN + 1.0*cm,
    title="Arthritis — Clinical Overview",
    author="Orris Medical AI",
    subject="All types of arthritis: pathology, diagnosis, treatment",
)

story = build_content()
doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print(f"PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/arthritis-pdf && python3 generate_arthritis_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/arthritis-pdf/Arthritis_Clinical_Overview.pdf

Your PDF is ready! Here's the download link:

Arthritis Clinical Overview

PDF Document · PDF

What's inside (46 KB, A4, multi-page):
  • Cover page with colour-coded index of all 7 types
  • 7 clinical sections - OA, RA, Gout, Spondyloarthritis, Psoriatic Arthritis, Reactive Arthritis, Septic Arthritis - each with key points box, pathogenesis, clinical features, investigations, and treatment tables
  • 5 summary/comparison tables:
    1. Diagnostic comparison across all 7 types
    2. OA vs. RA head-to-head
    3. Synovial fluid analysis guide
    4. Gout vs. Pseudogout (crystal arthropathies)
    5. Key drug summary (NSAIDs, colchicine, allopurinol, MTX, biologics, JAK inhibitors, steroids)
  • Sourced from Robbins Pathology, Goldman-Cecil Medicine, Rosen's Emergency Medicine, and Firestein & Kelley's Rheumatology

Unable to download it

Let me verify the file exists and try an alternative delivery method.
Running Command

ls -lh /home/daytona/workspace/arthritis-pdf/ && echo "---" && python3 -c " with open('/home/daytona/workspace/arthritis-pdf/Arthritis_Clinical_Overview.pdf','rb') as f: data = f.read() print(f'File size: {len(data)} bytes') print(f'PDF header: {data[:8]}') "

The file is valid (46 KB, proper PDF format). The issue is likely that the sandbox file path link isn't clickable in your browser environment. Let me convert it to a base64 data URI you can open directly, or provide it as inline content.
Running Command

python3 -c " import base64 with open('/home/daytona/workspace/arthritis-pdf/Arthritis_Clinical_Overview.pdf','rb') as f: data = f.read() b64 = base64.b64encode(data).decode() # Write an HTML file with embedded PDF download button html = f'''<!DOCTYPE html> <html> <head><title>Arthritis PDF Download</title></head> <body style=\"font-family:sans-serif;text-align:center;padding:40px\"> <h2>Arthritis Clinical Overview PDF</h2> <p>Click the button below to download your PDF.</p> <a href=\"data:application/pdf;base64,{b64}\" download=\"Arthritis_Clinical_Overview.pdf\" style=\"background:#1A3A5C;color:white;padding:14px 28px;text-decoration:none;border-radius:6px;font-size:16px\"> ⬇ Download PDF </a> </body> </html>''' with open('/home/daytona/workspace/arthritis-pdf/download.html','w') as f: f.write(html) print('HTML created, size:', len(html), 'chars') "

Try these two options:
Option 1 - Direct file link (try right-click → Save As):

Arthritis Clinical Overview

PDF Document · PDF

Option 2 - HTML download page (click to open, then click the download button inside):

download

HTML File · HTML


If neither works, the issue is your platform/browser restricting sandbox file access. In that case, here's what I can do instead:
  1. Email it to you - if your platform supports that
  2. Recreate as a web-viewable format - I can produce the full content as a clean HTML page you can print-to-PDF from your own browser (File → Print → Save as PDF)
  3. Upload to a file host - if the sandbox has internet outbound access
Which would you prefer?

Thank you I downloaded it

Glad it worked! 🎉
Whenever you need more topics covered — whether it's a deeper dive into any arthritis type, a new medical subject, or another PDF — just let me know. Good luck with your studies!

I'm a final year medical student (Sri Lanka- preparing for final exam), I'll give you my references, whenever I ask can you give answers, explanations or notes including important exam aspects, by get adhere to those references and please make sure not make any mistakes. References: Medicine :Kumar and clerk 11th edition Oxford handbook for Medicine Harrison principles of medicine Pead : Illustrated pediatrics Concise peadiatrics(Sri lankan book) Oxford hand book for peadiatrics Surgery : Bailey and love Oxford handbook Gyn & Obs : Oxford hand book for gyn and obs Ten teachers eranthi Madam's book(gyn and obs) --( in Sri Lanka) dutta's textbook of gynecology Psychiatry : Oxford hand book Hanwela sir's book (sri lankan book) Mim's Microbiology Robin's pathology Bennerd and brown's pharmacology And accepted national and other standards updated guidelines for all of them

Understood! I've noted all your references. Here's how I'll work with you:

Your Reference Stack (saved):
SubjectReferences
MedicineKumar & Clark 11th ed, Oxford Handbook of Medicine, Harrison's Principles
PaediatricsIllustrated Paediatrics, Concise Paediatrics (SL), Oxford Handbook of Paediatrics
SurgeryBailey & Love, Oxford Handbook of Surgery
Gyn & ObsOxford Handbook G&O, Ten Teachers, Eranthi Madam's book (SL), Dutta's Gynaecology
PsychiatryOxford Handbook of Psychiatry, Hanwela Sir's book (SL)
Cross-cuttingMims' Microbiology, Robbins' Pathology, Brenner & Rector's Pharmacology, Current national/international guidelines

How I'll answer every question:
  • Content aligned to those references as the primary authority
  • Sri Lankan context respected (local guidelines, SL-specific books prioritised where relevant)
  • Exam-focused: I'll flag high-yield points, common exam traps, and structured answer formats (SAQ/MCQ style where helpful)
  • No guessing - if something is uncertain or outside your references, I'll say so clearly
  • PDFs available on request for any topic

Go ahead - ask away! What topic do you want to start with?

Epilepsy

Reading File
Searching sources...
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Excellent content gathered. Now compiling the full exam-focused notes.

EPILEPSY

Final Year MBBS - Exam Notes | Kumar & Clark | Harrison's | Oxford Handbook of Medicine


DEFINITION

Epilepsy = a disorder of the brain characterised by an enduring predisposition to generate epileptic seizures, defined as 2 or more unprovoked seizures >24 hours apart, OR 1 unprovoked seizure with ≥60% risk of recurrence (ILAE 2014).
An epileptic seizure = a transient occurrence of signs and/or symptoms due to abnormal, excessive, or synchronous neuronal activity in the brain.
⚠️ Exam Trap: A single seizure is NOT epilepsy. A provoked seizure (e.g., from hypoglycaemia, fever, drugs) is NOT epilepsy.

EPIDEMIOLOGY

  • Prevalence: ~1% of the population
  • Most common serious neurological disorder
  • Bimodal age distribution: peak in childhood and >60 years
  • ~30% of patients remain refractory to medical treatment

AETIOLOGY (ILAE Classification)

CategoryExamples
StructuralHippocampal sclerosis (mesial TLE), cortical dysplasia, post-stroke, tumour, trauma, post-encephalitis
GeneticIon channel mutations (SCN1A in Dravet, KCNQ2); chromosomal (Angelman, Down syndrome)
InfectiousNeurocysticercosis (most common cause worldwide), TB, cerebral malaria, HIV encephalopathy
MetabolicHypoglycaemia, hyponatraemia, hypocalcaemia, uraemia, pyridoxine deficiency
ImmuneAutoimmune encephalitis (anti-NMDAR, anti-LGI1)
UnknownMajority (~50% of cases)
⚠️ Exam High-Yield: In Sri Lanka/South Asia - neurocysticercosis and CNS TB are important infective causes. Always ask about travel, diet (pork), and TB contacts.

SEIZURE CLASSIFICATION (ILAE 2017)

A. By Onset Type

                    SEIZURES
                  /          \
          FOCAL             GENERALISED         UNKNOWN ONSET
        (partial)
       /        \
  Aware    Impaired        → Can evolve to bilateral tonic-clonic
(Simple)   Awareness       ("focal to bilateral tonic-clonic")
(Complex)

1. Focal Onset Seizures

Originate in one hemisphere (or network).
Old TermNew ILAE 2017 Term
Simple partialFocal aware seizure
Complex partialFocal impaired awareness seizure
Secondary generalisedFocal to bilateral tonic-clonic
  • Motor features: clonic jerking, tonic posturing, automatisms (lip smacking, fumbling)
  • Non-motor features: aura (epigastric rising, déjà vu, smell - temporal lobe), sensory, autonomic, emotional
  • Todd's paresis: post-ictal focal weakness lasting minutes to hours after focal seizure - IMPORTANT for exams

2. Generalised Onset Seizures

Both hemispheres involved from onset.
TypeFeatures
Tonic-clonic (grand mal)Tonic phase (stiffening) → clonic phase (jerking); post-ictal confusion; tongue biting; urinary incontinence
Absence (petit mal)Brief 5-20 sec staring; no post-ictal phase; 3 Hz spike-wave on EEG; childhood onset
MyoclonicBrief muscle jerks; usually morning; juvenile myoclonic epilepsy (JME)
Atonic (drop attacks)Sudden loss of muscle tone; falls; seen in Lennox-Gastaut syndrome
TonicSustained muscle contraction; falls
ClonicRhythmic jerking without prior tonic phase
⚠️ Exam High-Yield: Absence vs. focal impaired awareness - Absence: no aura, no post-ictal phase, very brief (<30 sec), 3 Hz spike-wave. Complex partial: may have aura, post-ictal confusion, longer, temporal EEG focus.

IMPORTANT EPILEPSY SYNDROMES

SyndromeAgeFeaturesEEGDrug of Choice
West Syndrome (Infantile spasms)3-12 monthsSalaam attacks; developmental regressionHypsarrhythmiaACTH / Vigabatrin
Lennox-Gastaut Syndrome1-7 yearsMultiple seizure types (tonic, atonic, absence); intellectual disabilitySlow spike-wave (<2.5 Hz)Valproate, Clobazam; Rufinamide
Childhood Absence Epilepsy (CAE)4-10 yearsMultiple daily absences; normal development3 Hz spike-waveEthosuximide / Valproate
Juvenile Myoclonic Epilepsy (JME)12-18 yearsMorning myoclonic jerks + GTCS; precipitated by sleep deprivationPolyspike-wave 4-6 HzValproate (lifelong often needed)
Temporal Lobe Epilepsy (TLE)AnyFocal impaired awareness + automatisms; aura commonTemporal spike-waveCarbamazepine / Lamotrigine
Dravet Syndrome<1 yearFebrile seizures → refractory epilepsy; SCN1A mutationVariesValproate + Clobazam; avoid Na+ channel blockers
Benign Rolandic Epilepsy5-12 yearsNocturnal GTCS + facial twitching; self-limitedCentrotemporal spikesOften no treatment needed

DIAGNOSIS

History (Most Important)

  • From witness (patient unaware during seizure): detailed account of ictal behaviour
  • Onset: focal or generalised? Aura?
  • Duration, frequency, precipitants (sleep deprivation, alcohol, flickering lights, fever, menstruation - catamenial epilepsy)
  • Post-ictal phase: confusion, Todd's paresis, headache
  • Birth history, developmental history, family history
  • Drug/alcohol history

Investigations

1. EEG
  • Most important investigation for epilepsy
  • Epileptiform activity (spikes/sharp waves) in ~90% of epileptics depending on recording circumstances
  • Only ~2% of non-epileptics show epileptiform activity
  • Interictal EEG is usual (not during seizure)
  • Normal EEG does NOT exclude epilepsy
  • Ictal EEG (video-EEG monitoring) = gold standard
  • Sleep-deprived EEG, hyperventilation, photic stimulation increase yield
  • Photosensitive epilepsy: photoparoxysmal response on photic stimulation
⚠️ Exam Trap: "The EEG is always abnormal in epilepsy" - FALSE. A substantial number of epileptics have consistently normal interictal EEGs.
2. Neuroimaging
  • MRI brain - preferred; detects structural causes (hippocampal sclerosis, tumours, cortical dysplasia, vascular malformations)
  • CT brain - for acute settings (haemorrhage, calcification e.g. neurocysticercosis)
  • Hippocampal sclerosis (mesial temporal sclerosis): most common structural cause of TLE; MRI shows hippocampal atrophy and T2 hyperintensity
3. Blood Tests
  • FBC, electrolytes (Na, Ca, Mg, glucose), renal/liver function
  • AED levels (if on treatment)
  • Prolactin: rises after tonic-clonic seizures (within 20 min) - helps differentiate from pseudoseizures (non-epileptic attack disorder / NEAD)
4. Lumbar Puncture
  • If meningitis/encephalitis suspected
  • Not routine

DIFFERENTIAL DIAGNOSIS

⚠️ Very commonly tested - Differentiating seizure from syncope/pseudoseizure
FeatureEpileptic SeizureSyncopeNon-Epileptic Attack (NEAD/Pseudoseizure)
ProdromeAura (specific)Pre-syncope: dizziness, dimming visionVariable, emotional trigger often
PositionAnyUprightAny
ColourCyanosis (GTCS)PallorNormal or flushing
DurationUsually <3 minSecondsOften prolonged (>2 min), waxing-waning
JerkingSynchronous, rhythmicBrief myoclonic (if prolonged)Asynchronous, thrashing, pelvic thrusting
Tongue biteSide of tongueTip of tongue (rare)Rare
IncontinenceCommon (GTCS)UncommonUncommon
Post-ictal confusionYes (mins-hours)Rapid recoveryVariable, often prolonged
ProlactinElevated (20 min post-GTCS)NormalNormal
EEG during attackAbnormalNormalNormal

MANAGEMENT OF EPILEPSY

When to Start AEDs?

  • After 2 or more unprovoked seizures
  • After 1 seizure if: known structural lesion, abnormal EEG, abnormal neurology, strong family history, or high personal risk (e.g., driver)

General Principles

  • Monotherapy first - start low, go slow; 70% controlled with first AED
  • If first drug fails at adequate dose → try second monotherapy
  • Combination only after 2 monotherapies fail
  • Drug-refractory epilepsy = failure of 2 appropriate AEDs at adequate doses

AED Selection by Seizure Type

Seizure/SyndromeFirst-lineSecond-line/Alternatives
Focal seizuresCarbamazepine, Lamotrigine, OxcarbazepineLevetiracetam, Sodium valproate, Gabapentin
Generalised tonic-clonicSodium valproate, LamotrigineLevetiracetam, Carbamazepine (with caution)
AbsenceEthosuximide, Sodium valproateLamotrigine
MyoclonicSodium valproateLevetiracetam, Clonazepam
JMESodium valproateLevetiracetam, Lamotrigine
TLE (focal)CarbamazepineLamotrigine, Levetiracetam
⚠️ Critical Exam Point: Carbamazepine WORSENS absence, myoclonic and atonic seizures - NEVER use in generalised epilepsy syndromes with these types.
⚠️ Valproate in women of childbearing age: HIGH teratogenicity risk (neural tube defects, cognitive effects in child) - AVOID if possible; requires Pregnancy Prevention Programme in UK (relevant for Harrison's/Kumar & Clark).

Key AED Side Effects (High Yield)

DrugImportant Side Effects
CarbamazepineDiplopia, ataxia, hyponatraemia (SIADH), rash (Stevens-Johnson in HLA-B*1502 - Asian patients), aplastic anaemia, enzyme inducer
PhenytoinNystagmus, ataxia, gingival hyperplasia, hirsutism, coarse facies, folate deficiency, peripheral neuropathy, zero-order kinetics (small dose change = large level change)
Sodium ValproateTremor, weight gain, hair loss (reversible), teratogenicity (neural tube defects), hepatotoxicity (especially in children <2 y), thrombocytopenia, pancreatitis
LamotrigineRash (SJS if titrated too fast), insomnia, diplopia; must titrate SLOWLY especially with valproate
LevetiracetamBehavioural problems, irritability, depression; otherwise well tolerated
EthosuximideGI upset, headache; only for absence seizures
PhenobarbitoneSedation, tolerance, hyperactivity in children, enzyme inducer, dependence
Carbamazepine/Phenytoin/PhenobarbEnzyme inducers - affect OCP, warfarin, other drugs
⚠️ HLA-B*1502 (common in Sri Lankan/South Asian populations) - associated with carbamazepine-induced Stevens-Johnson Syndrome. Consider testing before starting carbamazepine.

Stopping AEDs

  • Consider after 2 years seizure-free
  • Must discuss driving licence implications
  • Gradual taper over months (never abrupt - risk of withdrawal seizures)
  • Higher risk of recurrence: structural cause, abnormal EEG, focal epilepsy

Drug-Refractory Epilepsy (20%)

  • Surgery: anterior temporal lobectomy - 80-90% seizure freedom in mesial TLE with hippocampal sclerosis
  • Vagus Nerve Stimulation (VNS): ~50% get ≥50% seizure reduction
  • Deep Brain Stimulation (DBS): anterior nucleus of thalamus
  • Responsive Neurostimulation (RNS): closed-loop device
  • Ketogenic diet: especially in children; high fat, low carbohydrate

STATUS EPILEPTICUS (SE)

Definition

  • Convulsive SE: seizure lasting >5 minutes (operational - time to treat; older definition was 30 min)
  • Traditional definition: >30 minutes of continuous seizure OR ≥2 seizures without full recovery between them
  • A medical emergency - mortality 10-20%

Causes (VITAMINS mnemonic)

Vascular, Infection, Trauma, AED withdrawal/non-compliance (most common), Metabolic (Na, Ca, glucose), Infection, Neoplasm, Structure
Most common cause in a known epileptic = AED non-compliance

Management - Time-Based Protocol

TimeAction
0-5 minABC, O₂, position (left lateral), IV access, blood glucose (BM), bloods (FBC, U&E, Ca, Mg, glucose, LFT, AED levels, ABG), ECG, monitor
5-10 min (1st line)Lorazepam IV 0.1 mg/kg (4 mg in adult) - drug of choice; or Diazepam IV 0.15-0.25 mg/kg; Midazolam buccal/IM if no IV access
If seizure continues 5 min after 1st benzodiazepineRepeat benzodiazepine (second dose)
10-30 min (2nd line)Levetiracetam IV (preferred now) OR Fosphenytoin IV OR Sodium valproate IV; start while giving 2nd benzo
30-60 min (Refractory SE)Anaesthetic agents: Propofol OR Thiopental OR Midazolam infusion; intubation; ICU; continuous EEG monitoring
>60 min (Super-refractory SE)Ketamine, hypothermia, ketogenic diet, immunotherapy (if autoimmune encephalitis), surgery
⚠️ Exam Point: Lorazepam (not diazepam) is drug of choice for IV SE because it has longer CNS duration of action. Diazepam preferred if IV access unavailable (rectal). Midazolam IM/buccal for pre-hospital.
⚠️ Fosphenytoin preferred over phenytoin IV (less cardiotoxic, can give faster, no propylene glycol).
⚠️ If glucose low or alcoholic → give thiamine BEFORE dextrose (prevents Wernicke's).

EPILEPSY IN SPECIAL SITUATIONS

Epilepsy & Driving

  • Must be seizure-free for 1 year before driving a private car (UK/most countries; Sri Lanka guidelines similar)
  • Heavy goods/bus: seizure-free for 10 years off medication
  • Must notify the licensing authority

Epilepsy & Pregnancy

  • Uncontrolled seizures are MORE dangerous to foetus than most AEDs
  • Valproate: highest teratogenic risk - avoid (neural tube defects, spina bifida, developmental delay)
  • Carbamazepine: lowest teratogenic risk among older AEDs; still causes neural tube defects
  • Lamotrigine/Levetiracetam: preferred in pregnancy
  • Give folic acid 5 mg/day pre-conception and throughout pregnancy
  • Vitamin K to neonate at birth (enzyme-inducing AEDs reduce clotting factor synthesis)

Febrile Convulsions (relevant to Paeds rotation)

  • Age 6 months - 6 years; fever >38°C
  • Simple: <15 min, generalised, single episode in 24h, complete recovery
  • Complex: >15 min OR focal OR >1 episode in 24h → investigate further
  • NOT the same as epilepsy; only 2-3% develop epilepsy later
  • Treatment: diazepam rectal/buccal midazolam for seizure; antipyretics; NOT regular AEDs for simple febrile convulsions

EXAM SUMMARY - HIGH-YIELD POINTS

#Key Point
1Epilepsy = ≥2 unprovoked seizures; a provoked seizure is NOT epilepsy
2ILAE 2017: focal aware / focal impaired awareness / focal to bilateral tonic-clonic
3EEG: ~90% show epileptiform activity; normal EEG does NOT exclude epilepsy
4Absence: 3 Hz spike-wave; no post-ictal phase; ethosuximide or valproate
5Carbamazepine worsens absence/myoclonic/atonic seizures - never use
6Valproate: most teratogenic - avoid in women of childbearing age
7HLA-B*1502 (Asian): carbamazepine → Stevens-Johnson Syndrome
8Phenytoin: zero-order kinetics, gingival hyperplasia, hirsutism, nystagmus
9SE first-line = IV Lorazepam; second-line = Levetiracetam/Fosphenytoin/Valproate IV
10Status epilepticus operational definition = >5 min (treat now, don't wait for 30 min)
11Todd's paresis = post-ictal focal weakness; distinguishes focal from generalised
12Prolactin elevated after GTCS (within 20 min); normal in pseudoseizures
13Febrile convulsions: do NOT give regular AEDs for simple febrile convulsions
14Drug-refractory TLE → temporal lobectomy; 80-90% seizure freedom
15Drive only after 1 year seizure-free (private car)

Sources: Kumar & Clark's Clinical Medicine 11e | Harrison's Principles of Internal Medicine | Bradley & Daroff's Neurology in Clinical Practice | Katzung Basic & Clinical Pharmacology | Rosen's Emergency Medicine | Textbook of Family Medicine 9e

Would you like me to make a PDF of these epilepsy notes, or move on to the next topic?

I need as pdf

Running Command

mkdir -p /home/daytona/workspace/epilepsy-pdf && python3 -c "from reportlab.lib.pagesizes import A4; print('OK')"

Writing File

~/epilepsy-pdf/generate_epilepsy_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY, TA_RIGHT

OUTPUT = "/home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes.pdf"

# ── Colour palette ────────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1A3A5C")
MED_BLUE    = colors.HexColor("#2E6DA4")
LIGHT_BLUE  = colors.HexColor("#D6E8F7")
TEAL        = colors.HexColor("#1A7A6E")
LIGHT_TEAL  = colors.HexColor("#D0EFEB")
RED         = colors.HexColor("#C0392B")
LIGHT_RED   = colors.HexColor("#FADBD8")
ORANGE      = colors.HexColor("#E67E22")
LIGHT_ORANGE= colors.HexColor("#FDEBD0")
GOLD        = colors.HexColor("#D4AC0D")
LIGHT_GOLD  = colors.HexColor("#FEF9E7")
PURPLE      = colors.HexColor("#6C3483")
LIGHT_PURPLE= colors.HexColor("#E8DAEF")
GREEN       = colors.HexColor("#1E8449")
LIGHT_GREEN = colors.HexColor("#D5F5E3")
LIGHT_GREY  = colors.HexColor("#F2F4F7")
MID_GREY    = colors.HexColor("#95A5A6")
WHITE       = colors.white
BLACK       = colors.black

PAGE_W, PAGE_H = A4
MARGIN = 1.8 * cm

# ── Styles ────────────────────────────────────────────────────────────────────
base = getSampleStyleSheet()

def S(name, parent="Normal", **kw):
    return ParagraphStyle(name, parent=base[parent], **kw)

sty = {
    "h1":       S("h1",  fontSize=16, textColor=WHITE,     leading=22, spaceBefore=0, spaceAfter=0, leftIndent=0),
    "h2":       S("h2",  fontSize=12, textColor=DARK_BLUE, leading=17, spaceBefore=10, spaceAfter=3, fontName="Helvetica-Bold"),
    "h3":       S("h3",  fontSize=10.5, textColor=TEAL,    leading=15, spaceBefore=7,  spaceAfter=2, fontName="Helvetica-Bold"),
    "body":     S("body",fontSize=9,   leading=14, spaceAfter=4, alignment=TA_JUSTIFY),
    "bullet":   S("bul", fontSize=9,   leading=13, leftIndent=14, spaceAfter=2),
    "sub_bul":  S("sbul",fontSize=8.5, leading=12, leftIndent=28, spaceAfter=2, textColor=colors.HexColor("#34495E")),
    "th":       S("th",  fontSize=8.5, textColor=WHITE,    leading=12, alignment=TA_CENTER, fontName="Helvetica-Bold"),
    "td":       S("td",  fontSize=8.5, leading=12, alignment=TA_LEFT),
    "td_c":     S("tdc", fontSize=8.5, leading=12, alignment=TA_CENTER),
    "warn":     S("wrn", fontSize=8.5, leading=13, textColor=RED,     leftIndent=8),
    "tip":      S("tip", fontSize=8.5, leading=13, textColor=TEAL,    leftIndent=8),
    "caption":  S("cap", fontSize=7.5, textColor=MID_GREY, alignment=TA_CENTER, spaceAfter=4),
    "cover_t":  S("ct",  fontSize=36, textColor=WHITE,     leading=44, alignment=TA_CENTER, fontName="Helvetica-Bold"),
    "cover_s":  S("cs",  fontSize=13, textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER, leading=18),
    "cover_b":  S("cb",  fontSize=9,  textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER),
    "num_lbl":  S("nl",  fontSize=18, textColor=WHITE, alignment=TA_CENTER, fontName="Helvetica-Bold"),
    "toc_item": S("ti",  fontSize=10, textColor=DARK_BLUE, leading=16, leftIndent=20),
    "toc_hdr":  S("th2", fontSize=12, textColor=WHITE,     leading=16, fontName="Helvetica-Bold"),
    "footer":   S("ft",  fontSize=7,  textColor=MID_GREY,  alignment=TA_CENTER),
    "warn_box": S("wb",  fontSize=8.5,leading=13, textColor=RED, leftIndent=8, fontName="Helvetica-Bold"),
    "exam_tip": S("et",  fontSize=8.5,leading=13, textColor=colors.HexColor("#7D3C98"), leftIndent=8),
}

# ── Helpers ───────────────────────────────────────────────────────────────────
W = PAGE_W - 2 * MARGIN

def sec_hdr(title, subtitle="", color=DARK_BLUE):
    data = [[Paragraph(f"<b>{title}</b>", sty["h1"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), color),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("LEFTPADDING",   (0,0), (-1,-1), 14),
        ("RIGHTPADDING",  (0,0), (-1,-1), 14),
    ]))
    out = [t]
    if subtitle:
        out.append(Paragraph(subtitle, sty["body"]))
    out.append(Spacer(1, 6))
    return out

def h2(txt, color=DARK_BLUE):
    p = Paragraph(f"<b>{txt}</b>", sty["h2"])
    hr = HRFlowable(width="100%", thickness=1.2, color=MED_BLUE, spaceAfter=4)
    return [p, hr]

def h3(txt):
    return [Paragraph(f"<b>{txt}</b>", sty["h3"])]

def body(txt):
    return [Paragraph(txt, sty["body"])]

def bul(items, sub=False):
    s = sty["sub_bul"] if sub else sty["bullet"]
    return [Paragraph(f"• {i}", s) for i in items]

def sp(h=6):
    return [Spacer(1, h)]

def warn(txt, label="⚠ EXAM TRAP"):
    data = [[Paragraph(f"<b>{label}:</b> {txt}", sty["warn"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_RED),
        ("BOX",           (0,0), (-1,-1), 1, RED),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 5)]

def tip(txt, label="★ HIGH-YIELD"):
    data = [[Paragraph(f"<b>{label}:</b> {txt}", sty["tip"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_TEAL),
        ("BOX",           (0,0), (-1,-1), 1, TEAL),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 5)]

def note(txt, label="NOTE"):
    data = [[Paragraph(f"<b>{label}:</b> {txt}", sty["exam_tip"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_PURPLE),
        ("BOX",           (0,0), (-1,-1), 1, PURPLE),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 5)]

def mk_table(headers, rows, col_widths=None, hdr_color=DARK_BLUE):
    if col_widths is None:
        col_widths = [W / len(headers)] * len(headers)
    hdr_row = [Paragraph(f"<b>{h}</b>", sty["th"]) for h in headers]
    data = [hdr_row] + [[Paragraph(str(c), sty["td"]) for c in row] for row in rows]
    t = Table(data, colWidths=col_widths, repeatRows=1)
    t.setStyle(TableStyle([
        ("BACKGROUND",     (0,0), (-1,0),  hdr_color),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, LIGHT_GREY]),
        ("GRID",           (0,0), (-1,-1), 0.4, MID_GREY),
        ("TOPPADDING",     (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",  (0,0), (-1,-1), 5),
        ("LEFTPADDING",    (0,0), (-1,-1), 6),
        ("RIGHTPADDING",   (0,0), (-1,-1), 6),
        ("VALIGN",         (0,0), (-1,-1), "TOP"),
    ]))
    return [t, Spacer(1, 8)]

def colored_box(items, title, bg, border):
    paras = [Paragraph(f"<b>{title}</b>", ParagraphStyle("bxtl", fontSize=10, textColor=border, fontName="Helvetica-Bold", spaceAfter=4))]
    for i in items:
        paras.append(Paragraph(f"◆  {i}", ParagraphStyle("bxi", fontSize=9, leading=13, textColor=colors.HexColor("#1a1a1a"))))
    t = Table([[paras]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), bg),
        ("BOX",           (0,0), (-1,-1), 1.2, border),
        ("TOPPADDING",    (0,0), (-1,-1), 8),
        ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
        ("RIGHTPADDING",  (0,0), (-1,-1), 10),
    ]))
    return [t, Spacer(1, 6)]

# ── Page header/footer ────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, PAGE_H - 0.65*cm, PAGE_W, 0.65*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 7)
    canvas.drawString(MARGIN, PAGE_H - 0.45*cm, "EPILEPSY  —  Final Year MBBS Exam Notes")
    canvas.setFont("Helvetica", 7)
    canvas.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.45*cm, "Kumar & Clark 11e | Harrison's | Oxford Handbook of Medicine")
    canvas.setFillColor(LIGHT_GREY)
    canvas.rect(0, 0, PAGE_W, 0.9*cm, fill=1, stroke=0)
    canvas.setFillColor(MID_GREY)
    canvas.setFont("Helvetica", 6.5)
    canvas.drawString(MARGIN, 0.32*cm, "References: Kumar & Clark 11e • Harrison's Principles • Oxford Handbook of Medicine • Bradley & Daroff Neurology • Katzung Pharmacology • Rosen's Emergency Medicine")
    canvas.drawRightString(PAGE_W - MARGIN, 0.32*cm, f"Page {doc.page}")
    canvas.restoreState()

# ── Cover page ────────────────────────────────────────────────────────────────
def cover():
    E = []
    # main banner
    d = [[Paragraph("EPILEPSY", sty["cover_t"])]]
    t = Table(d, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), DARK_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 38),
        ("BOTTOMPADDING", (0,0), (-1,-1), 14),
        ("LEFTPADDING",   (0,0), (-1,-1), 20),
    ]))
    E.append(t)
    sub_d = [[Paragraph("Final Year MBBS Exam Notes — Complete Clinical Overview", sty["cover_s"])]]
    sub_t = Table(sub_d, colWidths=[W])
    sub_t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), MED_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
    ]))
    E.append(sub_t)
    E.append(Spacer(1, 18))

    # Contents overview boxes
    sections = [
        (DARK_BLUE,   "1", "Definition & Epidemiology"),
        (MED_BLUE,    "2", "Aetiology (ILAE)"),
        (TEAL,        "3", "Seizure Classification (ILAE 2017)"),
        (PURPLE,      "4", "Epilepsy Syndromes"),
        (colors.HexColor("#1A7A6E"), "5", "Diagnosis & Investigations"),
        (ORANGE,      "6", "Differential Diagnosis (Seizure vs Syncope vs NEAD)"),
        (colors.HexColor("#1E8449"), "7", "Management & AED Selection"),
        (colors.HexColor("#922B21"), "8", "Status Epilepticus — Emergency Protocol"),
        (colors.HexColor("#6C3483"), "9", "Special Situations (Pregnancy, Driving, Febrile Convulsions)"),
        (colors.HexColor("#1A3A5C"), "10", "High-Yield Exam Summary Table"),
    ]
    for col, num, name in sections:
        rd = [[
            Paragraph(f"<b>{num}</b>", sty["num_lbl"]),
            Paragraph(f"<b>{name}</b>", ParagraphStyle("sn", fontSize=11, textColor=WHITE, leading=15)),
        ]]
        rt = Table(rd, colWidths=[1.2*cm, W - 1.2*cm - 0.15*cm])
        rt.setStyle(TableStyle([
            ("BACKGROUND",    (0,0), (-1,-1), col),
            ("TOPPADDING",    (0,0), (-1,-1), 8),
            ("BOTTOMPADDING", (0,0), (-1,-1), 8),
            ("LEFTPADDING",   (0,0), (-1,-1), 10),
            ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ]))
        E.append(rt)
        E.append(Spacer(1, 4))

    E.append(Spacer(1, 16))
    ref_d = [[Paragraph(
        "<b>References:</b> Kumar &amp; Clark's Clinical Medicine 11e  •  Harrison's Principles of Internal Medicine  •  "
        "Oxford Handbook of Medicine  •  Bradley &amp; Daroff's Neurology  •  Katzung Basic &amp; Clinical Pharmacology  •  "
        "Rosen's Emergency Medicine  •  Current ILAE Guidelines 2017",
        sty["caption"])]]
    ref_t = Table(ref_d, colWidths=[W])
    ref_t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_GREY),
        ("BOX",           (0,0), (-1,-1), 0.5, MID_GREY),
        ("TOPPADDING",    (0,0), (-1,-1), 7),
        ("BOTTOMPADDING", (0,0), (-1,-1), 7),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
    ]))
    E.append(ref_t)
    E.append(PageBreak())
    return E

# ── Main content ──────────────────────────────────────────────────────────────
def content():
    E = []

    # ── SECTION 1: Definition & Epidemiology ─────────────────────────────────
    E += sec_hdr("1. Definition & Epidemiology", color=DARK_BLUE)
    E += colored_box([
        "Epilepsy = disorder of the brain characterised by enduring predisposition to epileptic seizures",
        "ILAE 2014 definition: ≥2 unprovoked seizures >24 hours apart, OR 1 unprovoked seizure with ≥60% risk of recurrence",
        "Epileptic seizure = transient occurrence of signs/symptoms due to abnormal, excessive or synchronous neuronal activity",
    ], "DEFINITIONS", LIGHT_BLUE, DARK_BLUE)
    E += warn("A single seizure is NOT epilepsy. A provoked seizure (hypoglycaemia, fever, drugs, metabolic) is NOT epilepsy — this distinction is a favourite exam question.")
    E += h2("Epidemiology")
    E += mk_table(
        ["Parameter", "Details"],
        [
            ["Prevalence", "~1% of the general population"],
            ["Incidence", "Bimodal — peak in childhood AND >60 years (most common neurological disorder in elderly)"],
            ["Drug refractoriness", "~30% of epilepsy patients fail to achieve seizure control despite optimal medical therapy"],
            ["Mortality", "SUDEP (Sudden Unexpected Death in Epilepsy) — important complication; risk higher in uncontrolled GTCS"],
        ],
        col_widths=[4.5*cm, W-4.5*cm]
    )
    E += sp()

    # ── SECTION 2: Aetiology ─────────────────────────────────────────────────
    E += sec_hdr("2. Aetiology — ILAE Classification", color=MED_BLUE)
    E += mk_table(
        ["Category", "Examples"],
        [
            ["Structural", "Hippocampal sclerosis (mesial TLE — most common structural cause), cortical dysplasia, post-stroke, brain tumour (primary or secondary), post-traumatic, post-encephalitic, tuberous sclerosis, Sturge-Weber"],
            ["Genetic", "Ion channel mutations: SCN1A (Dravet syndrome), KCNQ2, KCNQ3; chromosomal: Down syndrome, Angelman syndrome; copy number variants"],
            ["Infectious", "Neurocysticercosis (most common cause of epilepsy worldwide), cerebral TB/tuberculoma, cerebral malaria, HSV encephalitis, HIV encephalopathy, bacterial abscess"],
            ["Metabolic", "Hypoglycaemia, hyponatraemia, hypocalcaemia, hypomagnesaemia, uraemia, hepatic encephalopathy, pyridoxine (B6) deficiency (neonates), non-ketotic hyperglycaemia"],
            ["Immune", "Autoimmune encephalitis: anti-NMDAR antibodies, anti-LGI1, anti-CASPR2, anti-AMPAR, anti-GABABR"],
            ["Unknown", "~50% of all epilepsy cases — largest category"],
        ],
        col_widths=[3.5*cm, W-3.5*cm]
    )
    E += tip("In Sri Lanka / South Asia: Neurocysticercosis and CNS tuberculosis are important infective causes. Always ask about dietary history (pork), travel, and TB contacts. Consider CT brain for ring-enhancing lesions.")
    E += sp()

    # ── SECTION 3: Seizure Classification ────────────────────────────────────
    E += sec_hdr("3. Seizure Classification — ILAE 2017", color=TEAL)
    E += body("The ILAE 2017 classification reorganised seizures based on: <b>(1) Onset type</b> (focal / generalised / unknown), <b>(2) Level of awareness</b> (for focal), and <b>(3) Motor vs non-motor features</b>.")
    E += sp(4)

    E += h2("A. Focal Onset Seizures (originate in one hemisphere or network)")
    E += mk_table(
        ["Old Term (Pre-2017)", "New ILAE 2017 Term", "Key Features"],
        [
            ["Simple partial seizure", "Focal AWARE seizure", "Consciousness fully preserved; patient aware throughout"],
            ["Complex partial seizure", "Focal IMPAIRED AWARENESS seizure", "Consciousness impaired; automatisms common (lip smacking, fumbling, chewing)"],
            ["Partial seizure 2° generalised / Grand mal", "Focal to BILATERAL TONIC-CLONIC seizure", "Starts focally, spreads to both hemispheres → GTCS; preceded by aura"],
        ],
        col_widths=[4.5*cm, 4.5*cm, W-9*cm]
    )
    E += h3("Auras (focal aware seizure features by lobe):")
    E += mk_table(
        ["Lobe of Origin", "Aura / Ictal Features"],
        [
            ["Temporal lobe", "Epigastric rising sensation (most common), déjà vu / jamais vu, olfactory hallucinations, fear, automatisms (lip smacking, chewing, fumbling)"],
            ["Frontal lobe", "Motor manifestations, nocturnal, brief, hypermotor behaviour, rapid secondary generalisation"],
            ["Parietal lobe", "Sensory (tingling, numbness), pain, distorted body image"],
            ["Occipital lobe", "Visual hallucinations (colours, shapes), eye deviation, nystagmus"],
        ],
        col_widths=[3.5*cm, W-3.5*cm]
    )
    E += tip("Todd's Paresis = post-ictal focal weakness (minutes to hours) following a focal motor seizure. Important localising sign. Distinguishes focal from primary generalised epilepsy.")

    E += h2("B. Generalised Onset Seizures (both hemispheres involved from onset)")
    E += mk_table(
        ["Type", "Clinical Features", "EEG Pattern"],
        [
            ["Tonic-Clonic (Grand Mal)", "Tonic phase (stiffening, apnoea, cyanosis) → clonic phase (rhythmic jerking); tongue biting (lateral); urinary incontinence; post-ictal confusion (minutes–hours)", "Generalised polyspike-wave during seizure; post-ictal diffuse slowing"],
            ["Absence (Petit Mal)", "Brief 5–20 sec staring spells; abrupt onset and offset; NO post-ictal phase; NO aura; may have subtle eye blinking; childhood onset", "3 Hz spike-and-wave; activated by hyperventilation"],
            ["Myoclonic", "Brief (milliseconds) shock-like muscle jerks; bilateral; typically morning; consciousness usually preserved", "Polyspike-wave 4–6 Hz; may be photosensitive"],
            ["Atonic (Drop Attacks)", "Sudden loss of muscle tone → fall injuries; consciousness briefly lost", "Spike-wave or polyspike-wave"],
            ["Tonic", "Sustained muscle contraction; falls; nocturnal common", "Low amplitude fast activity or polyspikes"],
            ["Clonic", "Rhythmic jerking without preceding tonic phase; rare", "Spike-wave"],
            ["Epileptic Spasms", "Infantile spasms (salaam attacks); flexion/extension of trunk; clusters; developmental regression", "Hypsarrhythmia (West syndrome)"],
        ],
        col_widths=[3.5*cm, 8.5*cm, W-12*cm]
    )
    E += warn("Absence vs Focal Impaired Awareness: Absence — no aura, no post-ictal phase, <30 sec, 3 Hz spike-wave, childhood, multiple daily. Complex partial — aura present, post-ictal confusion, longer (1–3 min), temporal EEG focus. This distinction is very commonly tested.")
    E += warn("Carbamazepine and Phenytoin WORSEN absence, myoclonic, and atonic seizures. NEVER prescribe for these seizure types or for generalised epilepsy syndromes containing them.")
    E += sp()

    # ── SECTION 4: Epilepsy Syndromes ────────────────────────────────────────
    E += sec_hdr("4. Important Epilepsy Syndromes", color=PURPLE)
    E += mk_table(
        ["Syndrome", "Age of Onset", "Key Clinical Features", "EEG", "First-Line Drug"],
        [
            ["West Syndrome\n(Infantile Spasms)", "3–12 months", "Salaam/jackknife attacks in clusters; developmental regression/arrest; poor prognosis", "Hypsarrhythmia (chaotic high-amplitude slow waves + multifocal spikes)", "ACTH / Vigabatrin"],
            ["Lennox-Gastaut Syndrome", "1–7 years", "Multiple seizure types (tonic, atonic, atypical absence, myoclonic); intellectual disability; treatment-resistant", "Slow spike-wave (<2.5 Hz); paroxysmal fast activity during sleep", "Valproate + Clobazam; Rufinamide; Lamotrigine"],
            ["Childhood Absence Epilepsy (CAE)", "4–10 years; girls > boys", "Multiple (>10/day) brief absences; normal development; good prognosis; may remit in adolescence", "3 Hz spike-wave; induced by hyperventilation", "Ethosuximide (1st line); Valproate"],
            ["Juvenile Myoclonic Epilepsy (JME)", "12–18 years", "Morning myoclonic jerks (drop things at breakfast); GTCS (especially after sleep deprivation); absence in 30%; lifelong treatment often needed", "Polyspike-wave 4–6 Hz; photosensitive", "Sodium Valproate (most effective); Levetiracetam; Lamotrigine"],
            ["Temporal Lobe Epilepsy (TLE)", "Any age (usually >10 y)", "Most common focal epilepsy; epigastric aura; déjà vu; automatisms; hippocampal sclerosis on MRI; may be drug-refractory", "Anterior temporal sharp waves / spikes; rhythmic theta ictal pattern", "Carbamazepine; Lamotrigine; Levetiracetam"],
            ["Dravet Syndrome", "First year of life", "Prolonged febrile seizures → refractory epilepsy; SCN1A mutation (80%); intellectual disability; AVOID Na+ channel blockers", "Varies; photosensitive", "Valproate + Clobazam; Stiripentol; Cannabidiol"],
            ["Benign Rolandic Epilepsy\n(BECTS)", "5–12 years", "Nocturnal GTCS ± daytime facial twitching/salivation; speech arrest; SELF-LIMITED — remits by adolescence", "Centrotemporal (rolandic) spikes; enhanced by sleep", "Often no treatment needed; Carbamazepine if required"],
            ["EIEE / Ohtahara Syndrome", "Neonatal", "Severe, refractory tonic spasms; burst-suppression on EEG; very poor prognosis", "Burst-suppression", "No effective treatment"],
        ],
        col_widths=[3.2*cm, 2*cm, 6.5*cm, 3.5*cm, W-15.2*cm]
    )
    E += tip("JME is characterised by the triad: morning myoclonus + GTCS + absence. Precipitants include sleep deprivation, alcohol, and early awakening. Valproate is most effective but avoid in women of childbearing age.")
    E += sp()

    # ── SECTION 5: Diagnosis ─────────────────────────────────────────────────
    E += sec_hdr("5. Diagnosis & Investigations", color=colors.HexColor("#1A7A6E"))
    E += h2("Clinical Diagnosis (History is Key)")
    E += colored_box([
        "Witness account is ESSENTIAL — patient may be unaware of ictal behaviour",
        "Onset: focal or generalised? Was there an aura? What was the first thing that happened?",
        "Duration, frequency, and timing (nocturnal, morning, random)",
        "Precipitants: sleep deprivation, alcohol, flickering lights (photosensitive), fever, menstruation (catamenial epilepsy)",
        "Post-ictal phase: confusion, headache, Todd's paresis, myalgia, tongue bite",
        "Past history: birth injury, febrile convulsions, head trauma, CNS infection, stroke",
        "Family history, developmental history, drug/alcohol history",
    ], "HISTORY TAKING", LIGHT_GOLD, GOLD)

    E += h2("Investigations")
    E += h3("1. EEG (Most Important Investigation)")
    E += body("<b>Epileptiform activity</b> (spikes and sharp waves) is the specific EEG finding associated with epilepsy.")
    E += mk_table(
        ["EEG Type", "Details"],
        [
            ["Interictal EEG", "Most commonly obtained (between attacks); epileptiform activity in ~90% of epileptics (depending on circumstances and number of studies)"],
            ["Normal interictal EEG", "Does NOT exclude epilepsy — a substantial number have consistently normal interictal EEGs"],
            ["False positive rate", "Only ~2% of non-epileptics show epileptiform discharges (high specificity)"],
            ["Ictal EEG (Video-EEG)", "GOLD STANDARD — recording electrographic seizure discharge during a typical attack; used in pre-surgical evaluation"],
            ["Yield enhancement techniques", "Sleep-deprived EEG, hyperventilation (absence), intermittent photic stimulation (photosensitive epilepsy), prolonged ambulatory EEG"],
            ["Photoparoxysmal response", "Generalised spike-wave bursts triggered by photic stimulation → indicates photosensitive epilepsy"],
        ],
        col_widths=[4*cm, W-4*cm]
    )
    E += warn("'The EEG is always abnormal in epilepsy' — FALSE. A significant proportion of epilepsy patients have normal interictal EEGs. Diagnosis is CLINICAL, supported by EEG.")

    E += h3("2. Neuroimaging")
    E += mk_table(
        ["Modality", "Use"],
        [
            ["MRI brain (preferred)", "Detects structural causes: hippocampal sclerosis, cortical dysplasia, tumours, cavernomas, gliosis. MRI shows hippocampal atrophy + T2/FLAIR signal in mesial TLE."],
            ["CT brain", "Acute settings: haemorrhage; calcification (neurocysticercosis, toxoplasmosis, tuberous sclerosis)"],
            ["FDG-PET", "Pre-surgical evaluation — shows interictal hypometabolism at seizure focus"],
            ["Ictal SPECT", "Ictal hyperperfusion at seizure onset zone; used in pre-surgical evaluation when MRI/EEG inconclusive"],
        ],
        col_widths=[3.5*cm, W-3.5*cm]
    )

    E += h3("3. Blood Investigations")
    E += bul([
        "FBC, ESR/CRP — infection, anaemia",
        "U&E (Na, K, Cr) — hyponatraemia, renal failure",
        "Blood glucose — hypoglycaemia / hyperglycaemia",
        "Ca²⁺, Mg²⁺ — hypocalcaemia, hypomagnesaemia",
        "LFTs — hepatic encephalopathy; valproate monitoring",
        "AED drug levels — if on treatment and seizure breakthrough or toxicity suspected",
        "<b>Prolactin</b> — rises 2-3x above baseline within 20 minutes of a GTCS or complex partial seizure; NORMAL in non-epileptic attack disorder (NEAD/pseudoseizures); measure within 20 min of event",
    ])
    E += h3("4. Lumbar Puncture")
    E += bul(["Indicated if meningitis / encephalitis / autoimmune encephalitis suspected", "NOT routine in established epilepsy"])
    E += sp()

    # ── SECTION 6: Differential Diagnosis ────────────────────────────────────
    E += sec_hdr("6. Differential Diagnosis", color=ORANGE)
    E += body("Differentiating an epileptic seizure from syncope and non-epileptic attack disorder (NEAD/pseudoseizures) is a very common exam scenario.")
    E += mk_table(
        ["Feature", "Epileptic Seizure (GTCS)", "Vasovagal Syncope", "NEAD / Pseudoseizure"],
        [
            ["Prodrome", "Aura (specific — epigastric, déjà vu, smell)", "Pre-syncope: dizziness, dimming vision, nausea, sweating", "Variable; emotional trigger often identifiable; vague feeling"],
            ["Trigger", "Often none; sleep deprivation, lights, alcohol", "Prolonged standing, heat, pain, emotional stress", "Emotional stress, anxiety, trauma history"],
            ["Body position", "Any", "Typically upright (standing)", "Any"],
            ["Skin colour", "Cyanosis (especially GTCS)", "Pallor", "Normal or flushing"],
            ["Duration", "Usually <3 minutes", "Seconds (rapid recovery)", "Often prolonged (>2 min); waxing and waning pattern"],
            ["Movements", "Tonic-clonic: synchronous, rhythmic, bilateral", "Brief myoclonic jerks if prolonged (convulsive syncope)", "Asynchronous, thrashing, pelvic thrusting, head rolling, eyes closed (resisting opening)"],
            ["Tongue bite", "Lateral border of tongue (SPECIFIC)", "Tip of tongue (rare)", "Rare; if present, tip of tongue"],
            ["Incontinence", "Common in GTCS", "Uncommon", "Uncommon"],
            ["Post-ictal confusion", "YES — minutes to hours", "Rapid recovery (seconds)", "Variable; may be prolonged; tearfulness"],
            ["Eyes", "Open, deviated; may have nystagmus", "Open or closed", "Typically CLOSED (a key distinguishing sign)"],
            ["Serum prolactin", "Elevated (within 20 min of GTCS)", "Normal", "Normal"],
            ["EEG during attack", "Abnormal ictal pattern", "Normal (may show slowing before loss of consciousness)", "Normal during attack"],
        ],
        col_widths=[3.8*cm, 4.5*cm, 4*cm, W-12.3*cm]
    )
    E += tip("Eyes CLOSED during a seizure-like episode strongly suggests NEAD. Patients with true GTCS almost always have eyes OPEN during the event.")
    E += warn("Other differentials: TIA (no post-ictal confusion, usually negative symptoms), migraine with aura (gradual march, headache follows), hypoglycaemia (responds to glucose), cardiac arrhythmia, narcolepsy/cataplexy, REM sleep disorder.")
    E += sp()

    # ── SECTION 7: Management ─────────────────────────────────────────────────
    E += sec_hdr("7. Management & AED Selection", color=GREEN)
    E += h2("When to Start AEDs?")
    E += mk_table(
        ["Situation", "Decision"],
        [
            ["2 or more unprovoked seizures", "START AEDs — standard indication"],
            ["Single unprovoked seizure + high recurrence risk", "START AEDs if: known structural lesion (tumour, hippocampal sclerosis), abnormal EEG, abnormal neurology, strong family history, patient's occupation/lifestyle at risk"],
            ["Single provoked seizure", "Treat the underlying cause; AEDs generally NOT indicated"],
            ["Single unprovoked seizure, low risk", "Discuss risk/benefit; often observe; patient preference matters"],
        ],
        col_widths=[5*cm, W-5*cm]
    )

    E += h2("General Principles of AED Therapy")
    E += bul([
        "<b>Monotherapy first</b> — start at low dose, titrate slowly to effective dose",
        "~70% of patients achieve seizure control with the first appropriate AED",
        "If first drug fails at adequate dose → switch to second monotherapy",
        "Combination therapy (polypharmacy) only after ≥2 monotherapy failures",
        "<b>Drug-refractory epilepsy</b> = failure of 2 appropriate AEDs at adequate doses — refer for specialist evaluation and pre-surgical assessment",
        "Never stop AEDs abruptly — risk of withdrawal seizures and status epilepticus",
    ])

    E += h2("AED Selection by Seizure Type / Syndrome")
    E += mk_table(
        ["Seizure Type / Syndrome", "First-Line", "Second-Line / Alternatives", "Avoid"],
        [
            ["Focal seizures (all types)", "Carbamazepine, Lamotrigine", "Levetiracetam, Oxcarbazepine, Sodium Valproate, Lacosamide", "—"],
            ["Generalised tonic-clonic", "Sodium Valproate, Lamotrigine", "Levetiracetam, Topiramate", "Carbamazepine (may worsen)"],
            ["Absence seizures", "Ethosuximide, Sodium Valproate", "Lamotrigine", "Carbamazepine, Phenytoin, Tiagabine (worsen absence)"],
            ["Myoclonic seizures", "Sodium Valproate", "Levetiracetam, Clonazepam, Topiramate", "Carbamazepine, Phenytoin, Gabapentin, Pregabalin (worsen myoclonus)"],
            ["Juvenile Myoclonic Epilepsy", "Sodium Valproate (most effective)", "Levetiracetam, Lamotrigine, Topiramate", "Carbamazepine, Phenytoin"],
            ["Temporal Lobe Epilepsy", "Carbamazepine, Lamotrigine", "Levetiracetam, Oxcarbazepine", "—"],
            ["West Syndrome", "ACTH, Vigabatrin", "Valproate, Pyridoxine (if B6-dependent)", "—"],
            ["Dravet Syndrome", "Valproate + Clobazam", "Stiripentol, Cannabidiol, Fenfluramine", "Carbamazepine, Lamotrigine, Phenytoin (worsen — Na+ channel blockers)"],
            ["Lennox-Gastaut", "Valproate + Clobazam", "Rufinamide, Lamotrigine, Topiramate, Cannbidiol", "—"],
        ],
        col_widths=[4.5*cm, 3.5*cm, 5.5*cm, W-13.5*cm]
    )
    E += warn("Carbamazepine and Phenytoin are Na+ channel blockers — they WORSEN absence, myoclonic, and atonic seizures. A common exam question: 'Which AED is contraindicated in JME?' Answer: Carbamazepine.")

    E += h2("Key AED Side Effects — High Yield")
    E += mk_table(
        ["Drug", "Mechanism", "Important Side Effects", "Special Points"],
        [
            ["Carbamazepine", "Na+ channel blocker", "Diplopia, ataxia, dizziness, drowsiness; hyponatraemia (SIADH); rash → SJS (especially HLA-B*1502 carriers); aplastic anaemia; benign leukopenia", "Enzyme INDUCER (↓OCP, warfarin, other AEDs); check HLA-B*1502 in Asian patients before prescribing"],
            ["Phenytoin", "Na+ channel blocker", "Dose-related: nystagmus, ataxia, diplopia, dysarthria; chronic: gingival hyperplasia, hirsutism, coarsening of facies, peripheral neuropathy, folate deficiency, osteoporosis", "Zero-order (saturable) kinetics — small dose increase = large rise in blood level → toxicity. Enzyme INDUCER. IV: arrhythmias if given too fast"],
            ["Sodium Valproate", "Multiple (Na+ channel, GABA enhancement, T-Ca2+ channel)", "Tremor (dose-related), weight gain, hair loss (reversible), polycystic ovaries; TERATOGENIC (neural tube defects, cognitive impairment in child); hepatotoxicity (especially children <2 y); thrombocytopenia; pancreatitis", "AVOID in women of childbearing age unless no alternative; if used, requires Pregnancy Prevention Programme; highest teratogenic risk of all AEDs"],
            ["Lamotrigine", "Na+ channel blocker", "Rash → SJS if titrated too fast (especially when added to valproate — valproate doubles lamotrigine levels); diplopia, ataxia, insomnia", "Titrate VERY slowly when adding to valproate. Relatively safe in pregnancy (preferred with levetiracetam)"],
            ["Levetiracetam", "SV2A synaptic vesicle protein", "Behavioural problems (irritability, aggression, depression) — 'Levetiracetam rage'; otherwise very well tolerated; no hepatic metabolism; no drug interactions", "Safe in pregnancy; no enzyme induction/inhibition; preferred in renal/hepatic impairment relative to others"],
            ["Ethosuximide", "T-type Ca2+ channel blocker", "GI upset (nausea, vomiting, abdominal pain); headache; drowsiness; rare: blood dyscrasias, SLE-like syndrome", "ONLY for absence seizures; does NOT treat GTCS — add valproate if GTCS also present"],
            ["Phenobarbitone", "GABA-A receptor agonist", "Sedation, cognitive impairment, paradoxical hyperactivity in children; dependence and withdrawal seizures; osteoporosis", "Enzyme INDUCER; cheap and effective; still used in resource-limited settings"],
            ["Topiramate", "Multiple mechanisms", "Cognitive slowing ('dopy on topiramate'), word-finding difficulty, weight loss, kidney stones (carbonic anhydrase inhibition), angle-closure glaucoma, teratogenic (cleft palate)", "Useful in migraine prophylaxis; weight-neutral benefit"],
            ["Oxcarbazepine", "Na+ channel blocker", "Hyponatraemia (more than CBZ); dizziness, diplopia; less enzyme induction than CBZ; rash (cross-reactivity with CBZ in ~25%)", "Active metabolite of CBZ; better tolerated; still check Na+ levels"],
        ],
        col_widths=[2.8*cm, 3*cm, 6*cm, W-11.8*cm]
    )
    E += note("HLA-B*1502 is common in Sri Lankan, South Asian, and Southeast Asian populations and is strongly associated with carbamazepine-induced Stevens-Johnson Syndrome / toxic epidermal necrolysis. Consider HLA testing before prescribing carbamazepine in these populations.")
    E += warn("Valproate in women of childbearing age: HIGHEST teratogenic risk. Causes neural tube defects (spina bifida), craniofacial abnormalities, and cognitive impairment in the child. Requires effective contraception and Pregnancy Prevention Programme if used.")

    E += h2("Stopping AEDs")
    E += bul([
        "Consider withdrawal after <b>2 years seizure-free</b>",
        "Discuss risks: ~30-40% relapse risk after withdrawal; higher in structural epilepsy, abnormal EEG, focal seizures",
        "Must warn about driving licence implications (must not drive during withdrawal and for 6 months after)",
        "Taper <b>gradually over months</b> — never stop abruptly",
        "If on polytherapy — withdraw one drug at a time",
    ])

    E += h2("Drug-Refractory Epilepsy — Non-pharmacological Options")
    E += mk_table(
        ["Option", "Details", "Outcome"],
        [
            ["Epilepsy Surgery", "Anterior temporal lobectomy (ATL) for mesial TLE with hippocampal sclerosis; lesionectomy for focal structural lesions; requires comprehensive pre-surgical evaluation (video-EEG, MRI, neuropsychology, PET, SPECT)", "80–90% seizure freedom in well-selected TLE patients — BEST outcome"],
            ["Vagus Nerve Stimulation (VNS)", "Implanted programmable pulse generator; electrode on left vagus nerve; open-loop continuous stimulation; approved for drug-refractory focal epilepsy", "~50% of patients achieve ≥50% reduction in seizure frequency"],
            ["Responsive Neurostimulation (RNS)", "Closed-loop device; detects ictal EEG → delivers stimulation to abort seizure; FDA approved 2014", "~50-66% seizure reduction at 2+ years"],
            ["Deep Brain Stimulation (DBS)", "Bilateral stimulation of anterior nucleus of thalamus; approved for focal seizures with/without generalisation", "~68% have >50% reduction at 5 years (SANTE trial)"],
            ["Ketogenic Diet", "High-fat, low-carbohydrate, adequate-protein diet; especially useful in children; also modified Atkins diet", "~50% achieve >50% reduction; particularly useful in West syndrome, Dravet, glucose transporter deficiency"],
        ],
        col_widths=[3.5*cm, 8*cm, W-11.5*cm]
    )
    E += sp()

    # ── SECTION 8: Status Epilepticus ────────────────────────────────────────
    E += sec_hdr("8. Status Epilepticus (SE) — Emergency Protocol", color=colors.HexColor("#922B21"))
    E += colored_box([
        "Status epilepticus is a TRUE MEDICAL EMERGENCY",
        "OPERATIONAL definition (for treatment): seizure lasting >5 minutes → START TREATMENT",
        "TRADITIONAL definition: >30 minutes continuous seizure OR ≥2 seizures without full recovery between",
        "Mortality: 10–20% in convulsive SE",
        "Delays in benzodiazepine administration >10 minutes associated with higher mortality and longer seizure duration",
    ], "DEFINITION & URGENCY", LIGHT_RED, RED)

    E += h2("Common Causes")
    E += bul([
        "<b>Most common in known epileptic</b> = AED non-compliance / sudden AED withdrawal",
        "Acute symptomatic: CNS infection (meningitis, encephalitis), head trauma, stroke, hypoxia, metabolic (hyponatraemia, hypoglycaemia, hypocalcaemia)",
        "Alcohol withdrawal",
        "Drug toxicity / overdose",
        "New onset epilepsy in elderly: stroke, tumour",
        "Autoimmune encephalitis (anti-NMDAR especially in young women → super-refractory SE)",
    ])
    E += warn("Most common cause of SE in a known epileptic = AED non-compliance. Always check compliance and drug levels.")

    E += h2("Time-Based Management Protocol")
    E += mk_table(
        ["Time", "Action", "Drugs / Doses"],
        [
            ["0–5 min\n(Stabilisation)", "ABC, left lateral position, O₂ (15L via non-rebreather mask), suction airway; IV/IO access; continuous monitoring (HR, BP, SpO₂, ECG); blood glucose (BM); blood tests: FBC, U&E, glucose, Ca²⁺, Mg²⁺, LFT, AED levels, blood culture, ABG; ECG; urine toxicology", "If BM low: IV Thiamine 250 mg FIRST (if alcoholic or malnourished), then IV Glucose 50 mL of 50% dextrose"],
            ["5–10 min\n(1st Line — Benzodiazepines)", "IV access: Lorazepam IV — DRUG OF CHOICE\nNo IV access: Midazolam IM/buccal or Diazepam rectal\nRepeat once after 5 min if seizure continues", "Lorazepam IV: 0.1 mg/kg (adult: 4 mg IV bolus)\nMidazolam buccal/IM: 10 mg (adult)\nDiazepam rectal: 10–20 mg (adult)"],
            ["10–30 min\n(2nd Line — AED loading)", "If seizure persists after 2 doses of benzodiazepine → 2nd-line AED; begin concurrently with 2nd benzo dose\nThree options equally supported:", "Levetiracetam IV: 60 mg/kg (max 4500 mg) over 10 min (PREFERRED — safest profile)\nFosphenytoin IV: 20 mg PE/kg over 15 min (monitor ECG/BP)\nSodium Valproate IV: 40 mg/kg over 10 min"],
            ["30–60 min\n(Refractory SE)", "Refractory SE = seizure continues despite 2nd-line AED; requires anaesthesia, intubation, ICU admission, continuous EEG monitoring", "Propofol IV infusion OR Thiopental IV infusion OR Midazolam IV infusion (titrate to burst-suppression on EEG)"],
            [">60 min\n(Super-refractory SE)", "Seizure continues despite 24h of anaesthesia; consider rare causes (autoimmune encephalitis, paraneoplastic, rare genetic); MDT approach", "Ketamine IV; Hypothermia (35–35.5°C); Ketogenic diet; Immunotherapy (IVIG, steroids, plasmapheresis if autoimmune); Isoflurane inhalational anaesthesia; Consider ECT (rare)"],
        ],
        col_widths=[2.5*cm, 6.5*cm, W-9*cm]
    )
    E += tip("Fosphenytoin is PREFERRED over phenytoin IV: water-soluble, less cardiotoxic, can be given IM, administered 3x faster, compatible with glucose-containing IV fluids.")
    E += warn("Phenytoin IV must be given slowly (<50 mg/min in adults) with continuous cardiac monitoring — risk of hypotension and arrhythmias if given too fast. NEVER give phenytoin in dextrose-containing solutions (precipitates).")
    E += note("If propylene glycol is a concern (phenytoin) or in neonates/pregnancy — fosphenytoin or levetiracetam are preferred over phenytoin.")
    E += sp()

    # ── SECTION 9: Special Situations ────────────────────────────────────────
    E += sec_hdr("9. Special Situations", color=PURPLE)

    E += h2("Epilepsy & Driving")
    E += mk_table(
        ["Licence Type", "Requirement"],
        [
            ["Private car (Group 1)", "Seizure-free for 1 year before driving; or if sleep-only seizures for ≥3 years; must notify licensing authority"],
            ["Heavy goods / Bus (Group 2)", "Seizure-free for 10 years, off AEDs for 10 years"],
            ["During AED withdrawal", "Must not drive during gradual withdrawal and for 6 months after final dose"],
            ["Physician's duty", "Advise patient of duty to notify licensing authority; document advice in notes"],
        ],
        col_widths=[4*cm, W-4*cm]
    )

    E += h2("Epilepsy & Pregnancy")
    E += colored_box([
        "PRINCIPLE: Uncontrolled seizures (especially GTCS) are MORE dangerous to the foetus than most AEDs",
        "Do NOT stop AEDs in pregnancy without specialist advice",
        "Folic acid 5 mg/day: start PRE-CONCEPTION and continue throughout first trimester (all women on AEDs)",
        "Give Vitamin K to neonate at birth if mother on enzyme-inducing AEDs (reduce neonatal haemorrhagic disease)",
        "Breastfeeding: generally encouraged; levetiracetam and lamotrigine pass into breast milk but considered safe",
    ], "KEY PRINCIPLES", LIGHT_BLUE, DARK_BLUE)
    E += mk_table(
        ["AED", "Teratogenic Risk", "Comment"],
        [
            ["Sodium Valproate", "HIGHEST — avoid if possible", "Neural tube defects (spina bifida 1–2%), craniofacial abnormalities, limb defects, neonatal bleeding, cognitive impairment in child (10–15 point IQ reduction); requires Pregnancy Prevention Programme"],
            ["Carbamazepine", "Moderate (neural tube defects ~0.5–1%)", "Lowest risk among older AEDs; folic acid supplementation essential"],
            ["Phenytoin", "Moderate", "Fetal hydantoin syndrome: craniofacial abnormalities, digit hypoplasia, IUGR; cardiac defects"],
            ["Lamotrigine", "Low (preferred)", "Preferred in pregnancy; levels fall significantly in pregnancy — monitor and increase dose accordingly"],
            ["Levetiracetam", "Low (preferred)", "Growing evidence of safety; preferred with lamotrigine; no dose adjustment required in most"],
            ["Phenobarbitone", "Moderate", "Cardiac defects, cleft palate; neonatal withdrawal and sedation"],
            ["Topiramate", "Moderate (cleft palate, SGA)", "Avoid if possible"],
        ],
        col_widths=[3*cm, 3.5*cm, W-6.5*cm]
    )
    E += warn("Valproate: UK Valproate Pregnancy Prevention Programme (PPP) mandates highly effective contraception and annual pregnancy testing in all women of childbearing potential prescribed valproate.")

    E += h2("Febrile Convulsions")
    E += body("Febrile convulsions = seizures occurring in children aged <b>6 months to 6 years</b> associated with fever (>38°C) but without evidence of intracranial infection or defined CNS cause.")
    E += mk_table(
        ["Type", "Definition", "Action"],
        [
            ["Simple febrile convulsion", "Generalised; <15 minutes; single episode in 24 hours; complete recovery", "Reassure parents; antipyretics (paracetamol/ibuprofen); NO regular AEDs; diazepam rectal/midazolam buccal for prolonged seizure"],
            ["Complex febrile convulsion", "Focal seizure OR >15 minutes OR >1 seizure in 24 hours OR incomplete recovery", "Investigate: LP (exclude meningitis), blood cultures, EEG, MRI; neurological referral"],
        ],
        col_widths=[3.5*cm, 6*cm, W-9.5*cm]
    )
    E += bul([
        "Overall risk of developing epilepsy later = only <b>2–3%</b> (vs ~1% in general population)",
        "Risk factors for later epilepsy: complex febrile convulsion, family history of epilepsy, prior neurological abnormality",
        "Recurrence risk of further febrile convulsions = ~30–40%",
        "Simple febrile convulsions do NOT cause brain damage",
    ])
    E += warn("Do NOT prescribe regular prophylactic AEDs for simple febrile convulsions — evidence shows no benefit and significant side effects. A frequently tested exam point.")
    E += sp()

    # ── SECTION 10: Exam Summary Table ───────────────────────────────────────
    E += sec_hdr("10. High-Yield Exam Summary", color=DARK_BLUE)
    E += mk_table(
        ["#", "Key Exam Point", "Answer / Fact"],
        [
            ["1",  "Definition of epilepsy", "≥2 unprovoked seizures >24h apart, OR 1 unprovoked + ≥60% recurrence risk"],
            ["2",  "Is a provoked seizure = epilepsy?", "NO — treat the underlying cause; not epilepsy"],
            ["3",  "ILAE 2017 seizure types", "Focal (aware / impaired awareness / to bilateral TC) | Generalised | Unknown"],
            ["4",  "Old 'complex partial' = new term?", "Focal impaired awareness seizure"],
            ["5",  "Absence EEG pattern", "3 Hz spike-and-wave; enhanced by hyperventilation"],
            ["6",  "Drug for absence seizures", "Ethosuximide (1st line); Sodium valproate"],
            ["7",  "AED that worsens absence/myoclonus", "Carbamazepine and Phenytoin — NEVER use in these seizure types"],
            ["8",  "Most teratogenic AED", "Sodium Valproate — highest risk of neural tube defects and cognitive impairment"],
            ["9",  "AEDs preferred in pregnancy", "Lamotrigine and Levetiracetam"],
            ["10", "HLA-B*1502 significance", "Asian patients: carbamazepine → Stevens-Johnson Syndrome / TEN. Test before prescribing."],
            ["11", "Phenytoin kinetics", "Zero-order (saturable) kinetics — small dose increase = disproportionately large rise in level"],
            ["12", "Phenytoin chronic side effects", "Gingival hyperplasia, hirsutism, coarse facies, peripheral neuropathy, osteoporosis"],
            ["13", "Enzyme-inducing AEDs", "Carbamazepine, Phenytoin, Phenobarbitone, Primidone → reduce efficacy of OCP, warfarin"],
            ["14", "Valproate side effects", "Tremor, weight gain, hair loss, teratogenicity, hepatotoxicity, thrombocytopenia, pancreatitis"],
            ["15", "Levetiracetam side effect", "Behavioural/psychiatric (irritability, aggression, depression) — 'levetiracetam rage'"],
            ["16", "Todd's paresis", "Post-ictal focal weakness after focal motor seizure — localising sign; minutes to hours"],
            ["17", "Prolactin in GTCS", "Elevated within 20 minutes of GTCS; NORMAL in NEAD/pseudoseizures"],
            ["18", "Eyes in NEAD vs true seizure", "NEAD: eyes usually CLOSED. True GTCS: eyes usually OPEN"],
            ["19", "SE operational definition", ">5 minutes → TREAT NOW (don't wait for 30 min)"],
            ["20", "SE 1st-line drug", "Lorazepam IV 0.1 mg/kg (4 mg adult); Midazolam IM/buccal if no IV access"],
            ["21", "SE 2nd-line drug", "Levetiracetam IV / Fosphenytoin IV / Sodium Valproate IV"],
            ["22", "Fosphenytoin vs Phenytoin", "Fosphenytoin: water-soluble, less cardiotoxic, can give IM, 3x faster IV rate"],
            ["23", "Most common SE cause in known epileptic", "AED non-compliance"],
            ["24", "Driving after epilepsy (private car)", "1 year seizure-free before driving"],
            ["25", "Simple febrile convulsion management", "Reassure + antipyretics; NO regular AEDs; only diazepam/midazolam for prolonged episode"],
            ["26", "Febrile convulsion → epilepsy risk", "2–3% (only slightly above general population risk of ~1%)"],
            ["27", "Best surgical outcome in epilepsy", "Temporal lobectomy for mesial TLE with hippocampal sclerosis: 80-90% seizure freedom"],
            ["28", "EEG in epilepsy diagnosis", "Normal EEG does NOT exclude epilepsy; only ~2% of non-epileptics have epileptiform discharges"],
            ["29", "JME triad", "Morning myoclonic jerks + GTCS + absence; precipitants: sleep deprivation, alcohol"],
            ["30", "West syndrome EEG", "Hypsarrhythmia; treat with ACTH / Vigabatrin"],
        ],
        col_widths=[0.7*cm, 6.5*cm, W-7.2*cm],
        hdr_color=DARK_BLUE
    )
    E += sp(8)

    # Sources
    E += h2("References")
    E += bul([
        "Kumar & Clark's Clinical Medicine, 11th Edition",
        "Harrison's Principles of Internal Medicine",
        "Oxford Handbook of Medicine",
        "Bradley & Daroff's Neurology in Clinical Practice",
        "Katzung Basic & Clinical Pharmacology, 16th Edition",
        "Rosen's Emergency Medicine — Concepts and Clinical Practice",
        "ILAE 2017 Operational Classification of Seizure Types (Fisher et al., Epilepsia 2017)",
        "ILAE 2014 Definition of Epilepsy (Fisher et al., Epilepsia 2014)",
    ])
    return E

# ── Build ─────────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=MARGIN, rightMargin=MARGIN,
    topMargin=MARGIN + 0.65*cm,
    bottomMargin=MARGIN + 0.9*cm,
    title="Epilepsy — Final Year MBBS Exam Notes",
    author="Orris Medical AI",
    subject="Epilepsy: Classification, Syndromes, Diagnosis, AEDs, Status Epilepticus",
)

story = cover() + content()
doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print(f"PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/epilepsy-pdf && python3 generate_epilepsy_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes.pdf

Your epilepsy PDF is ready:

Epilepsy Final Year Notes

PDF Document · PDF

What's inside (52 KB, A4, colour-coded):
SectionContent
Cover pageColour-coded index of all 10 sections
1. Definition & EpidemiologyILAE 2014 definition, bimodal incidence, SUDEP
2. AetiologyFull ILAE categories including neurocysticercosis/TB for Sri Lanka
3. Seizure ClassificationILAE 2017 full table (old vs new terms), auras by lobe, GTCS/absence/myoclonic/atonic details
4. Epilepsy SyndromesWest, LGS, CAE, JME, TLE, Dravet, Benign Rolandic — all in one table
5. DiagnosisEEG (interictal vs ictal, false +/-), MRI, prolactin, LP
6. Differential DiagnosisSeizure vs Syncope vs NEAD — full comparison table
7. ManagementWhen to start AEDs, selection by seizure type, all side effects, stopping AEDs, surgery/VNS/DBS/RNS/ketogenic diet
8. Status EpilepticusFull time-based emergency protocol (0 min → super-refractory)
9. Special SituationsDriving, pregnancy (all AED risks), febrile convulsions
10. Exam Summary30-point high-yield table — all key exam facts in one place
Red ⚠ boxes = exam traps | Teal ★ boxes = high-yield points | Purple boxes = Sri Lanka-specific notes. Good luck with your finals! 🎓

(And hereafter add this too -- if any mx plan all pharmacology and non pharmacological mx options, and incase any emergency or any mx a algorithm)

Understood! From now on, for every topic I cover, I will always include:

Updated Template — Every Topic Will Have:
SectionWhat's Included
Complete Management PlanFull pharmacological AND non-pharmacological options, nothing left out
PharmacologyDrug name, dose, mechanism, side effects, contraindications, monitoring
Non-pharmacologicalLifestyle, dietary, surgical, physiotherapy, psychological, social, device-based — all relevant options
Emergency ManagementStep-by-step time-based algorithm (like the SE protocol) whenever there is an acute/emergency presentation
Management AlgorithmVisual flowchart-style decision tree built into the PDF for any condition with a management pathway

This applies to all future topics — Medicine, Paediatrics, Surgery, Obs & Gynae, Psychiatry.
The epilepsy notes already covered most of this — the Status Epilepticus section had the full time-based emergency algorithm, and the AED section covered full pharmacology. If you want me to regenerate the epilepsy PDF with even more detail (e.g. a visual management algorithm for chronic epilepsy, full non-pharmacological section), just say the word.
Otherwise — what's your next topic?

Now I wanr Everything about AUR and CUR And then recreate by expanding the epilepsy pdf

Searching sources...
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
I now have comprehensive content from Campbell Walsh Urology, Schwartz's Surgery, Smith & Tanagho's Urology, and Symptom to Diagnosis. Let me now generate both PDFs simultaneously.
general-purpose

Generate a professional medical PDF for a final year Sri Lankan MBBS student on Acute Urinary Retention (AUR) and Chronic Urinary Retention (CUR). Create a Python script at /home/daytona/workspace/aur-cur-pdf/generate_aur_cur.py and run it to produce /home/daytona/workspace/aur-cur-pdf/AUR_CUR_Final_Year_Notes.pdf Use ReportLab (already installed). The PDF must be A4, professional, colour-coded, and exam-focused, matching the style of previous PDFs (dark blue #1A3A5C headers, coloured warning/tip boxes, tables with alternating rows). CONTENT TO INCLUDE (use ALL of this): === COVER PAGE === Title: "ACUTE & CHRONIC URINARY RETENTION" Subtitle: "Final Year MBBS Exam Notes — Surgery & Urology" List 8 sections on cover === SECTION 1: DEFINITIONS === AUR: Sudden, painful inability to void voluntarily. Inability to pass urine despite a full bladder. PAINFUL (distinguish from CUR). CUR: Painless, persistent incomplete bladder emptying with large post-void residual (PVR >300 mL). May cause overflow incontinence. Often PAINLESS. Key difference table: AUR vs CUR (onset, pain, bladder size, PVR, complications, treatment urgency) === SECTION 2: AETIOLOGY === AUR Causes (classify as): OBSTRUCTIVE (most common): - BPH (benign prostatic hyperplasia) — most common cause in men >50 years - Urethral stricture (post-infection/instrumentation/trauma) - Prostatic carcinoma - Bladder neck obstruction - Bladder stone impacted at neck - Clot retention (haematuria with clot formation) - Phimosis / paraphimosis - Meatal stenosis - Pelvic organ prolapse (in women — cystocele, uterine prolapse) - Constipation/faecal impaction (extrinsic compression) - Pelvic mass (fibroids, ovarian cyst, gravid uterus) NEUROGENIC: - Spinal cord injury / spinal cord compression - Multiple sclerosis - Parkinson's disease - Diabetic autonomic neuropathy - Post-operative (especially after spinal/epidural anaesthesia, anorectal surgery, hernia repair) - Cauda equina syndrome (EMERGENCY — saddle anaesthesia + AUR) PHARMACOLOGICAL (drug-induced — important exam list): - Anticholinergics (oxybutynin, TCAs, antihistamines) - Alpha-adrenergic agonists (pseudoephedrine, decongestants) - Opioids/narcotics - NSAIDs - Calcium channel blockers - Antipsychotics (haloperidol, clozapine) - Alcohol (acute) - Bethanechol overdose OTHERS: - Acute prostatitis / prostatic abscess - Herpes simplex urethritis (Elsberg syndrome — rare) - Post-partum urinary retention - Psychogenic retention (Fowler syndrome — young women, large bladder capacity) CUR Causes: - All causes of chronic bladder outlet obstruction (BPH, stricture, carcinoma) - Neurogenic bladder (detrusor underactivity, acontractile bladder) - Diabetic cystopathy - Multiple sclerosis - Spinal cord lesions - Long-standing BPH with detrusor decompensation (atonic bladder) - Post-radiation bladder Risk factors for AUR (exam — men): - Age >70 - Prostate volume >30 mL - PSA >1.4 ng/mL - Peak flow rate <12 mL/sec - IPSS score >7 - Previous episode of AUR (recurrence risk 56-64% within 1 week) === SECTION 3: PATHOPHYSIOLOGY === - Normal voiding: detrusor contraction + external urethral sphincter relaxation (coordinated by micturition centre in pons, cortical override) - AUR: imbalance — BOO exceeds detrusor contractility OR detrusor contractility lost - Bladder pressure rises → ureters affected → hydronephrosis → renal impairment (post-renal AKI) in severe untreated cases - CUR: chronic distension → detrusor fibrosis → irreversible acontractile bladder - Overflow incontinence: intravesical pressure finally exceeds urethral resistance → constant dribbling (paradoxical incontinence) - "High-pressure CUR" vs "Low-pressure CUR": * High-pressure CUR: significant upper tract dilatation, bilateral hydronephrosis, renal impairment — SURGICAL URGENCY * Low-pressure CUR: large capacity, compliant bladder, no upper tract dilatation — less urgent === SECTION 4: CLINICAL FEATURES === AUR: - Sudden complete inability to void - Severe lower abdominal/suprapubic pain and distress - Intense urge to void but cannot - Suprapubic swelling (palpable/percussable full bladder) - Typically >300-500 mL in bladder at presentation - Tachycardia, hypertension, diaphoresis (pain response) - May dribble small amounts (overflow) — distinguishes from anuria - Haematuria may be present if clot retention CUR: - Often asymptomatic / insidious onset - Hesitancy, poor stream, straining, incomplete emptying (voiding LUTS) - Overflow incontinence — constant dribbling "like water over a dam" - Nocturia, frequency (storage LUTS from small functional capacity) - Recurrent UTIs (stagnant urine) - Painless palpable bladder - Signs of renal failure (if high-pressure CUR): hypertension, oedema, uraemic symptoms - Bilateral hydroureteronephrosis on USS Signs on examination: - Palpable/percussable suprapubic mass (dull to percussion = full bladder) - DRE: enlarged prostate (smooth = BPH; irregular/hard = carcinoma), rectal mass - Neurological exam: saddle anaesthesia, anal tone (cauda equina) - External genitalia: phimosis, meatal stenosis, urethral discharge === SECTION 5: INVESTIGATIONS === Bedside: - Bladder scanner (USS) — confirms retention, measures volume (>150 mL significant, >300 mL = retention) - Urine dipstick + MSU — infection, haematuria - Blood glucose (diabetic neuropathy) Bloods: - U&E, Creatinine — renal function (AKI in AUR; chronic renal failure in high-pressure CUR) - FBC — infection, anaemia - PSA — prostate cancer (check BEFORE catheterisation as catheter elevates PSA) - Clotting if haematuria (clot retention) - Blood cultures if sepsis suspected Imaging: - KUB X-ray — calculi, constipation/faecal loading - USS renal tract (kidneys, ureters, bladder) — hydronephrosis, bladder volume, PVR, prostate size - CT KUB — calculi, mass lesions - MRI spine — if cord compression/cauda equina suspected Urodynamics (for CUR/neurogenic): - Free flow rate (uroflowmetry) — peak flow <10 mL/sec suggests obstruction - Post-void residual (PVR) — >100 mL significant; >300 mL = CUR - Pressure flow studies — distinguish BOO from detrusor underactivity - Cystoscopy — urethral stricture, bladder tumour, stone Other: - IPSS (International Prostate Symptom Score) — severity of LUTS (0-35; mild <7, moderate 8-19, severe ≥20) - Flexible cystoscopy — if stricture, haematuria, or atypical features === SECTION 6: MANAGEMENT === --- AUR EMERGENCY MANAGEMENT ALGORITHM --- Build a clear step-by-step algorithm as a table: STEP 1 (IMMEDIATE — 0-30 min): - Confirm diagnosis: history + examination + bladder scanner - IV access + bloods (U&E, Cr, FBC, PSA, clotting) - Analgesia (IV morphine/paracetamol) - Urethral catheterisation (FIRST-LINE) * Use 14-16Fr Foley for most cases * BPH: use 16-18Fr COUDÉ (curved-tip) catheter — tip at 12 o'clock position * Urethral stricture: use 12-14Fr straight catheter; if fails → urologist * Record: time, volume drained, colour of urine STEP 2 (IF URETHRAL CATHETER FAILS): - Do NOT force catheter — risk of false passage - Urgent urology referral - Options: * Coudé catheter under LA gel * Cystoscopy + guidewire + urethral dilatation * Suprapubic catheter (SPC) — 2 fingerbreadths above pubic symphysis; USS guidance recommended; contraindications: previous lower midline surgery, bladder tumour, clotting disorders, unconfirmed full bladder STEP 3 (POST-CATHETERISATION): - Monitor: hourly urine output - "Post-obstructive diuresis" monitoring — may produce large volumes after decompression (>200 mL/hr for >2 hours = significant) * Replace 50% of hourly output with IV N/Saline if diuresis significant * Risk: hypovolaemia, electrolyte disturbance - Avoid rapid decompression controversy: older teaching said drain 500 mL at a time; current evidence does NOT support this; drain completely - Treat the cause STEP 4 (TRIAL WITHOUT CATHETER — TWOC): - After 24-72 hours (ideally 2-3 days) of catheterisation - Start alpha-blocker 24-48 hours BEFORE TWOC: * Tamsulosin 400 mcg OD (most evidence) — improves TWOC success rate from ~50% to ~60-70% * Alfuzosin 10 mg OD - Remove catheter in morning (better voiding success in daytime) - Patient voids and measure: * Voided volume + PVR (bladder scan within 15 min) * TWOC SUCCESSFUL: void >150 mL + PVR <200 mL * TWOC FAILED: unable to void OR PVR >200 mL → re-catheterise → re-refer urology STEP 5 (AFTER FAILED TWOC): - Second TWOC after another 3-5 days (success rate ~30%) - OR proceed to definitive treatment: * TURP (Trans-Urethral Resection of Prostate) — GOLD STANDARD for BPH-related AUR * HoLEP (Holmium Laser Enucleation of Prostate) — for large prostates * Open prostatectomy — prostate >100 mL * Clean Intermittent Self-Catheterisation (CISC) — for neurogenic/non-surgical candidates --- CUR MANAGEMENT --- Assess: High-pressure vs Low-pressure CUR - HIGH-PRESSURE: Urgent catheterisation + treat cause + monitor renal function + urology referral - LOW-PRESSURE: Investigate cause + elective management Catheterisation for CUR: - Urethral catheter or suprapubic catheter - For HIGH-PRESSURE CUR: drain SLOWLY initially (500 mL/hour) to avoid rapid decompression syndrome - Monitor for post-obstructive diuresis (more marked in CUR) --- PHARMACOLOGICAL MANAGEMENT --- 1. ALPHA-BLOCKERS (first-line for BPH-related AUR/LUTS): - Tamsulosin 400 mcg OD — most selective (α1A/α1D); minimal cardiovascular side effects - Alfuzosin 10 mg OD — less selective - Doxazosin 4-8 mg OD — also treats hypertension - Silodosin 8 mg OD — highly selective α1A - MOA: relax smooth muscle of prostate, bladder neck, urethra → reduce outlet resistance - Side effects: orthostatic hypotension (less with tamsulosin), retrograde ejaculation (tamsulosin > others), dizziness, nasal congestion - Onset: DAYS to weeks (use in TWOC — start 48h before) - Note: Do NOT use tamsulosin if planning cataract surgery — Intraoperative Floppy Iris Syndrome (IFIS) 2. 5-ALPHA-REDUCTASE INHIBITORS (5-ARIs — for BPH, long-term): - Finasteride 5 mg OD — inhibits 5α-reductase type 2 → reduces DHT → prostate shrinkage (20-30%) - Dutasteride 0.5 mg OD — inhibits both type 1 and 2 (more complete DHT suppression) - MOA: block conversion of testosterone → DHT → reduce prostate volume - Onset: 3-6 MONTHS for full effect (not useful acutely) - Reduce AUR risk by 50% and need for surgery by 55% (long-term) - Side effects: sexual dysfunction (erectile dysfunction, decreased libido, ejaculatory dysfunction), gynaecomastia, teratogenic (women must not handle crushed tablets — Pregnancy Category X) - Reduce PSA by ~50% after 6 months — double PSA value when interpreting if on 5-ARI 3. COMBINATION THERAPY (Alpha-blocker + 5-ARI): - CombAT trial: dutasteride + tamsulosin → superior to monotherapy for symptom relief and AUR prevention - Use in: large prostate (>30 mL), elevated PSA, high AUR risk 4. MUSCARINIC ANTAGONISTS (for overactive bladder — storage LUTS, not for retention): - Oxybutynin, Tolterodine, Solifenacin, Darifenacin - CONTRAINDICATED in significant bladder outlet obstruction / urinary retention (worsen retention) - Use only AFTER BOO excluded 5. BETA-3 AGONIST (for OAB): - Mirabegron 50 mg OD - Can be used if BOO mild (unlike antimuscarinic, less retention risk) 6. PHOSPHODIESTERASE-5 INHIBITORS: - Tadalafil 5 mg OD — licensed for LUTS/BPH ± erectile dysfunction - Relaxes smooth muscle of bladder neck and prostate 7. ANTIBIOTICS: - If acute prostatitis → IV Ceftriaxone or Ciprofloxacin (covers Gram-negatives) - If UTI in CUR → culture-guided antibiotics 8. ANALGESIA FOR AUR: - IV morphine 0.1 mg/kg OR oral morphine equivalents - IV paracetamol 1g - Avoid NSAIDs if renal impairment (AKI in AUR) --- NON-PHARMACOLOGICAL MANAGEMENT --- Conservative: - Fluid restriction (avoid excessive fluid loading — worsens retention) - Avoid constipation, avoid alcohol - Review and stop offending medications (anticholinergics, opioids) - Warm bath/shower (relax sphincter — may help in early retention) - Running tap water (psychological voiding trigger) Catheterisation: - Urethral Foley catheter (most common) - Coudé catheter (for BPH) - Suprapubic catheter (SPC) — if urethral not possible, long-term better for patient comfort - Clean Intermittent Self-Catheterisation (CISC) — GOLD STANDARD for neurogenic bladder and non-surgical CUR * Every 4-6 hours * Reduces UTI risk vs indwelling catheter * Maintains bladder capacity and function Surgical (definitive for BOO): - TURP (Gold Standard for BPH) — resection of prostatic tissue through scope; risks: bleeding, retrograde ejaculation (50-90%), TURP syndrome (hyponatraemia from irrigation fluid absorption — now rare with bipolar TURP), UTI, incontinence (<1%) - HoLEP (Holmium Laser Enucleation of Prostate) — for large prostates; lower bleeding risk; faster recovery - Open prostatectomy (Millin's retropubic / transvesical) — prostate >100 g - TUIP (Trans-Urethral Incision of Prostate) — small prostates <30 g; preserves ejaculation - Prostatic urethral lift (UroLift) — for suitable small prostates; preserves sexual function - Laser procedures: Greenlight laser photoselective vaporisation (PVP) - Urethral dilatation / direct vision urethrotomy (DVIU) — for urethral stricture - Urethroplasty — definitive repair for urethral stricture - Sacral nerve modulation (Interstim) — for neurogenic bladder / detrusor underactivity - Botulinum toxin injection into detrusor (for NDO/OAB) — via cystoscopy === SECTION 7: COMPLICATIONS === AUR complications: - Acute Kidney Injury (post-renal) — if untreated; may be severe - Post-obstructive diuresis — after catheterisation of prolonged retention - Haematuria after decompression (decompression haematuria) - UTI / urosepsis - Bladder rupture (extremely rare, spontaneous in overdistended bladder) - Autonomic dysreflexia (in spinal cord injury patients — hypertensive emergency) CUR complications: - Recurrent UTIs (stagnant urine) - Bladder stones (infection stones — struvite; also calcium oxalate) - Vesicoureteric reflux → bilateral hydroureteronephrosis - Chronic Kidney Disease / End-stage renal failure (HIGH-PRESSURE CUR) - Bladder diverticula (from raised pressure) - Irreversible detrusor damage (atonic acontractile bladder) - Overflow incontinence Post-TURP complications (exam high-yield): - Immediate: bleeding, clot retention, infection - Early: UTI, DVT, PE - Late: urethral stricture, bladder neck stenosis, retrograde ejaculation (most common ~90%), incontinence (<1%), erectile dysfunction (rare), re-operation (10-15% at 10 years) - TURP syndrome: hyponatraemia + fluid overload (now less common with bipolar TURP / saline irrigation) === SECTION 8: HIGH-YIELD EXAM SUMMARY (30 POINTS) === 1. AUR = painful; CUR = usually painless 2. Most common cause of AUR in men = BPH (10% of men in 70s, 33% in 80s) 3. Most common cause of AUR in women = neurogenic / Fowler syndrome 4. Drug-induced AUR: anticholinergics, opioids, alpha-agonists, TCAs, antihistamines 5. Cauda equina syndrome = AUR + saddle anaesthesia + bilateral leg weakness → SURGICAL EMERGENCY 6. Diagnosis of AUR = clinical (painful full bladder) confirmed by bladder scan >300 mL 7. First-line treatment = urethral catheterisation 8. Coudé catheter used in BPH (tip at 12 o'clock) 9. Suprapubic catheter = 2 fingerbreadths above pubic symphysis; USS guidance needed 10. Check PSA BEFORE catheterisation (catheter elevates PSA) 11. Alpha-blocker (tamsulosin) given 48h before TWOC improves success rate 12. TWOC success = void >150 mL + PVR <200 mL 13. TWOC success rate ~60-70% with alpha-blocker (vs ~50% without) 14. 5-ARIs reduce AUR risk by 50% (long-term); NOT useful acutely (take 3-6 months) 15. 5-ARIs reduce PSA by ~50% — double PSA when interpreting if on 5-ARI 16. Tamsulosin → Intraoperative Floppy Iris Syndrome (IFIS) — tell ophthalmologist before cataract surgery 17. Post-obstructive diuresis: monitor UO hourly; replace 50% output if >200 mL/hr 18. High-pressure CUR = bilateral hydronephrosis + renal impairment → urgent catheterisation 19. CUR pathology: PVR >300 mL, overflow incontinence, recurrent UTI, renal damage 20. TURP = gold standard for BPH 21. TURP most common late complication = retrograde ejaculation (90%) 22. TURP syndrome = dilutional hyponatraemia (now less common with bipolar TURP) 23. HoLEP = for large prostates (>80-100 mL) 24. CISC = gold standard for neurogenic bladder long-term management 25. Acute prostatitis causing AUR → IV antibiotics + avoid TWOC until treated 26. Clot retention → 3-way catheter + continuous bladder irrigation (CBI) 27. Spontaneous AUR → 75% ultimately need surgery; Precipitated AUR → only 26% need surgery 28. 5-ARI teratogenicity — women must not handle crushed finasteride/dutasteride tablets 29. DVIU = for short urethral stricture; urethroplasty = for long/recurrent strictures 30. Autonomic dysreflexia in SCI + AUR = hypertensive emergency → drain bladder immediately DESIGN REQUIREMENTS: - Cover page with section index in coloured boxes - Red warning boxes (⚠ EXAM TRAP) - Teal tip boxes (★ HIGH-YIELD) - Orange note boxes for Sri Lanka-specific/clinical points - Full AUR emergency algorithm as a step-by-step table - TWOC decision algorithm as a table - All tables with dark blue headers, alternating row colours - Page header: "ACUTE & CHRONIC URINARY RETENTION — Final Year MBBS Exam Notes" - Page footer: sources + page number - References: Bailey & Love's Surgery, Campbell Walsh Wein Urology, Schwartz's Principles of Surgery, Smith & Tanagho's General Urology, Oxford Handbook of Surgery Make the script robust and run it. Return the exact output path of the generated PDF and confirm file size.

general-purpose

Expand and regenerate the Epilepsy PDF for a final year Sri Lankan MBBS student. The previous PDF exists at /home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes.pdf (52KB) but we need an EXPANDED version. Create a new Python script at /home/daytona/workspace/epilepsy-pdf/generate_epilepsy_v2.py and run it to produce /home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes_v2.pdf Use ReportLab (already installed). A4, professional, colour-coded, exam-focused. The new version must ADD the following on top of the existing content: === NEW ADDITIONS TO INCLUDE === 1. COMPLETE NON-PHARMACOLOGICAL MANAGEMENT section: - Lifestyle modifications: * Sleep hygiene (especially for JME — sleep deprivation is major trigger) * Alcohol avoidance (lowers seizure threshold) * Stress management * Photosensitive epilepsy: avoid flickering lights, use polarised glasses, don't use strobing video games * Catamenial epilepsy (seizures linked to menstrual cycle): diary keeping, hormonal manipulation (progesterone supplementation, GnRH analogues in refractory cases) * Driving restrictions (must be seizure-free 1 year — private car; 10 years — HGV) * Swimming safety (supervised only, no bath alone), heights precautions, cooking safety * Wear medical alert bracelet - Dietary therapies: * Ketogenic diet: 4:1 fat:carbohydrate+protein ratio; high fat (cream, butter, oils); mainly in children; reduces seizures by >50% in ~50% of patients; particularly effective in: West syndrome, Dravet, glucose transporter (GLUT-1) deficiency, pyruvate dehydrogenase deficiency * Modified Atkins diet: less restrictive, similar efficacy in adults * Low glycaemic index treatment (LGIT) * Medium chain triglyceride (MCT) diet * Monitoring on ketogenic diet: urinary ketones, growth parameters, lipid profile, renal USS (kidney stones), FBC, LFTs - Psychological support: * CBT for anxiety/depression (common in epilepsy) * Neuropsychological assessment * Seizure diary keeping (identify triggers) * Patient education and epilepsy nurse specialist - Social support: * DVLA/driving notifications * Employment advice (avoid heights, operating heavy machinery, working near water) * Benefits/disability support * Support groups 2. SURGICAL MANAGEMENT (expanded): - Pre-surgical evaluation: video-EEG + high-res MRI + neuropsychology + PET + SPECT + fMRI (language/memory lateralisation) + Wada test (amytal test — determines language dominance and memory reserve of each hemisphere) - Types of surgery: * Temporal lobectomy (anterior temporal resection) — for mesial TLE + hippocampal sclerosis; 60-80% seizure freedom; risk: memory impairment (especially dominant hemisphere), visual field defect (Meyer's loop - superior quadrantanopia "pie in the sky"), language deficits if dominant hemisphere * Lesionectomy — resection of structural lesion (tumour, cavernoma, dysplasia) * Hemispherectomy — for severe unilateral hemispheric epilepsy (Rasmussen encephalitis, hemimegalencephaly); young children with already-deficient hemisphere function * Corpus callosotomy — for drop attacks (atonic seizures) in LGS; prevents generalisation; not curative * Multiple subpial transection (MST) — when epileptogenic zone overlaps eloquent cortex; reduces seizure spread - Patient selection criteria: drug-refractory (failed ≥2 AEDs), seizure focus identifiable and resectable, benefit > risk 3. DEVICE-BASED (NEUROMODULATION) — expanded: - Vagus Nerve Stimulation (VNS): * Left vagus nerve (right has cardiac effects) * Programmed pulse generator implanted in chest * Additional: magnet swipe to abort individual seizures * Approved for focal epilepsy refractory to AEDs; also used in LGS * Result: ~50% get ≥50% seizure reduction; 3% seizure freedom * Side effects: hoarseness (most common), cough, throat pain, dyspnoea during stimulation - Responsive Neurostimulation (RNS NeuroPace): * Closed-loop: detects ictal EEG → stimulates focus to abort * Implanted in skull * For focal epilepsy with 1-2 foci - Deep Brain Stimulation (DBS): * Target: anterior nucleus of thalamus (ANT-DBS) * SANTE trial: 68% patients had >50% reduction at 5 years * Also: centromedian nucleus (CM-DBS) for generalised/LGS - Transcranial magnetic stimulation (TMS) — investigational - External trigeminal nerve stimulation (eTNS) — non-invasive, licensed for adjunctive focal epilepsy in some countries 4. CHRONIC EPILEPSY MANAGEMENT ALGORITHM (visual flowchart as table): New seizure diagnosis → Step 1: Confirm diagnosis (clinical + EEG + MRI) Step 2: Identify seizure type/syndrome Step 3: First AED monotherapy (appropriate for type) → Seizure free 2 years → Consider withdrawal → Seizure continues at adequate dose → Switch to 2nd AED monotherapy → Still fails → 3rd AED monotherapy OR dual therapy → Fails 2 AEDs → Drug-refractory epilepsy → Refer epilepsy centre → Pre-surgical evaluation → Surgery if suitable → Not surgical candidate → VNS / DBS / RNS / Ketogenic diet 5. FIRST SEIZURE MANAGEMENT ALGORITHM: First seizure → → Provoked? (fever, metabolic, drugs, acute brain injury) → Treat cause; AEDs usually not needed → Unprovoked? → Investigations (EEG + MRI + bloods) → High recurrence risk? (structural lesion, abnormal EEG, focal deficit, family history) → START AED → Low recurrence risk? → Discuss with patient; may observe or start AED based on preference/occupation/driving 6. WOMEN WITH EPILEPSY — complete section: - Contraception + AEDs: * Enzyme-inducing AEDs (CBZ, PHT, PB, primidone, topiramate >200 mg/day, oxcarbazepine) reduce OCP efficacy → use ≥50 mcg ethinylestradiol pill OR barrier method OR non-hormonal IUD * Non-enzyme-inducing AEDs (valproate, lamotrigine, levetiracetam, gabapentin) — standard OCP OK * Valproate increases levels of OCP (minor) * Lamotrigine levels reduced by OCP (can halve lamotrigine levels) — adjust dose - Pre-conception counselling: * Folic acid 5 mg/day (start at least 3 months pre-conception) * Switch valproate to safer AED if possible * Aim for lowest effective dose, monotherapy * Counsel on teratogenic risks - During pregnancy: * Seizure frequency may increase (hormonal changes, sleep deprivation, changed AED pharmacokinetics, non-compliance) * Lamotrigine levels fall significantly in pregnancy (renal clearance increases) → monitor levels and increase dose * Levetiracetam levels also fall * Monthly AED level monitoring recommended * Detailed anomaly scan at 18-20 weeks * Vitamin K supplementation in last 4 weeks (if on enzyme-inducers): 10 mg/day oral * Neonatal vitamin K 1 mg IM at birth - Labour and delivery: * Continue AEDs throughout labour * IV lorazepam/diazepam available for seizures during labour * Caesarean only if obstetric indication or seizure risk very high - Post-partum: * Breastfeeding: generally safe with most AEDs (lamotrigine, levetiracetam, valproate — low milk levels; phenobarbitone — sedation in baby; ethosuximide — significant milk levels) * Reduce lamotrigine/LEV back to pre-pregnancy dose after delivery (or levels will rise above therapeutic) * Sleep deprivation triggers seizures — arrange baby care support 7. FEBRILE CONVULSIONS — expanded: - Immediate management: * Lay child on side (recovery position), time seizure, call for help * Airway, check breathing * Seizure >5 minutes: buccal midazolam 0.5 mg/kg (max 10 mg) OR rectal diazepam 0.5 mg/kg * If still seizing at 10 min: second dose * If still seizing at 20 min: paediatric SE protocol * Antipyretics: paracetamol 15 mg/kg (NOT aspirin — Reye's syndrome) * Cool environment, tepid sponging * Investigate if complex features: LP (if <18 months or signs of meningism), FBC, U&E, glucose, cultures - NOT proven to prevent recurrence: regular antipyretics, prophylactic AEDs 8. SUDEP (Sudden Unexpected Death in Epilepsy): - Annual risk: ~1:1000 in general epilepsy; up to 1:150 in refractory epilepsy - Risk factors: frequent uncontrolled GTCS, nocturnal seizures, male sex, young adult, poor AED compliance, sleeping alone, prone position during sleep - Mechanism: likely post-ictal respiratory depression + cardiac arrhythmia - Prevention: optimise seizure control, nocturnal supervision/monitoring devices (movement monitors), prone position avoidance, seizure alert dogs DESIGN: Same style as before — dark blue #1A3A5C section headers, red warning boxes, teal tip boxes, orange note boxes, professional tables with alternating rows. Cover page with full section index. All algorithms as step-by-step tables with arrow/flow indicators. Page header: "EPILEPSY — Final Year MBBS Exam Notes (Expanded)" Page footer: References + page number References: Kumar & Clark 11e, Harrison's, Oxford Handbook of Medicine, Bradley & Daroff Neurology, Katzung Pharmacology, ILAE Guidelines 2017 IMPORTANT: This is an EXPANDED version — keep ALL the original content (definitions, classification, syndromes, diagnosis, AED table, SE protocol, exam summary 30 points) AND add all the new sections above. Run the script and return the output PDF path and file size.

Reading File
Browsing Directory

~/epilepsy-pdf

Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/aur-cur-pdf && ls /home/daytona/workspace/aur-cur-pdf

Reading File
Reading File
Reading File

Ok ?

It looks like both tasks were cancelled when a new message came in. Let me restart both now.
general-purpose

Generate TWO professional medical PDFs for a final year Sri Lankan MBBS student using ReportLab (already installed). Run both scripts and confirm both files exist with their sizes. --- PDF 1: AUR & CUR Script: /home/daytona/workspace/aur-cur-pdf/generate_aur_cur.py Output: /home/daytona/workspace/aur-cur-pdf/AUR_CUR_Final_Year_Notes.pdf PDF 2: Epilepsy Expanded Script: /home/daytona/workspace/epilepsy-pdf/generate_epilepsy_v2.py Output: /home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes_v2.pdf Both PDFs: A4, professional, dark blue (#1A3A5C) section banners, red warning boxes, teal tip boxes, alternating row tables. Cover page with section index. Page headers/footers. =========================== PDF 1 — AUR & CUR CONTENT =========================== COVER: "ACUTE & CHRONIC URINARY RETENTION" | "Final Year MBBS Exam Notes — Surgery & Urology" List sections: 1.Definitions 2.Aetiology 3.Pathophysiology 4.Clinical Features 5.Investigations 6.Management 7.Complications 8.Exam Summary SECTION 1 — DEFINITIONS AUR: Sudden, PAINFUL inability to void voluntarily despite a full bladder. Emergency. CUR: Painless, persistent incomplete emptying. PVR >300 mL. May cause overflow incontinence. Comparison table (AUR vs CUR): Onset | AUR: Sudden | CUR: Insidious Pain | AUR: Severe suprapubic | CUR: Usually painless Bladder | AUR: Distended, tender | CUR: Large, non-tender PVR | AUR: Total (no voiding) | CUR: >300 mL Complications | AUR: AKI, urosepsis | CUR: CKD, bilateral hydronephrosis, recurrent UTI Urgency | AUR: EMERGENCY | CUR: Urgent/elective SECTION 2 — AETIOLOGY Obstructive causes: - BPH (most common in men >50 — 10% of men in 70s, 33% in 80s) - Urethral stricture (post-trauma/instrumentation/infection) - Prostate carcinoma - Bladder neck obstruction - Bladder stone at neck - Clot retention (haematuria) - Phimosis / paraphimosis / meatal stenosis - Pelvic organ prolapse (cystocele, uterine prolapse — women) - Constipation / faecal impaction - Pelvic mass (fibroids, ovarian cyst, gravid uterus) Neurogenic causes: - Spinal cord injury / compression - Cauda equina syndrome (EMERGENCY — AUR + saddle anaesthesia + bilateral leg weakness) - Multiple sclerosis - Parkinson's disease - Diabetic autonomic neuropathy - Post-operative (spinal/epidural anaesthesia, anorectal/hernia surgery) - Fowler syndrome (young women — large acontractile bladder, no neurological cause) Pharmacological (drug-induced — exam list): - Anticholinergics (oxybutynin, TCAs, antihistamines, antipsychotics) - Opioids/narcotics - Alpha-adrenergic agonists (pseudoephedrine, decongestants) - NSAIDs - Calcium channel blockers - Alcohol (acute) Other: - Acute prostatitis / prostatic abscess - Post-partum urinary retention - Psychogenic / Fowler syndrome AUR risk factors table (men): Age >70 | Prostate volume >30 mL | PSA >1.4 ng/mL | Peak flow <12 mL/sec | IPSS >7 | Previous AUR episode Two types of AUR: - Spontaneous AUR: natural history of BPH → 75% ultimately need surgery - Precipitated AUR: triggered by event (anaesthesia, drugs, instrumentation) → only 26% need surgery SECTION 3 — PATHOPHYSIOLOGY - Normal voiding: detrusor contraction + urethral sphincter relaxation (pontine micturition centre coordinated) - AUR: BOO exceeds detrusor contractility OR detrusor contractility lost → bladder cannot empty - Rising bladder pressure → ureteric obstruction → hydronephrosis → post-renal AKI - CUR: chronic distension → detrusor fibrosis → irreversible acontractile bladder - Overflow incontinence: intravesical pressure = urethral resistance → constant dribbling ("water over a dam") - HIGH-PRESSURE CUR: upper tract dilatation + bilateral hydronephrosis + renal impairment → SURGICAL URGENCY - LOW-PRESSURE CUR: large compliant bladder, no upper tract dilatation → less urgent SECTION 4 — CLINICAL FEATURES AUR: sudden complete inability to void, severe suprapubic pain and distress, urge to void cannot, suprapubic swelling (palpable/percussable), >300-500 mL in bladder, tachycardia, hypertension, diaphoresis, may dribble small amounts (overflow — distinguishes from anuria) CUR: insidious, often asymptomatic, hesitancy + poor stream + straining (voiding LUTS), overflow incontinence (constant dribbling), nocturia/frequency, recurrent UTIs, painless palpable bladder, signs of renal failure (hypertension, oedema, uraemia) if high-pressure Examination findings: - Suprapubic dullness to percussion (full bladder) - DRE: enlarged smooth prostate (BPH) vs irregular/hard (carcinoma); rectal mass - Neurological: saddle anaesthesia, anal tone (cauda equina screen) - External genitalia: phimosis, meatal stenosis SECTION 5 — INVESTIGATIONS Bedside: Bladder scanner (confirms retention, measures volume — >300 mL = retention), urine dipstick + MSU Bloods: U&E + Creatinine (renal function/AKI), FBC (infection/anaemia), PSA (CHECK BEFORE CATHETERISATION — catheter raises PSA), clotting (if haematuria), blood cultures (if septic) Imaging: KUB X-ray (calculi, constipation), USS renal tract (hydronephrosis, prostate size, PVR), CT KUB (calculi/masses), MRI spine (cord compression) Urodynamics: Uroflowmetry (peak flow <10 mL/sec = obstruction), PVR (>300 mL = CUR), pressure-flow studies (BOO vs detrusor underactivity), cystoscopy IPSS scoring: 0-7 mild, 8-19 moderate, ≥20 severe SECTION 6 — MANAGEMENT --- AUR EMERGENCY ALGORITHM (step-by-step table) --- Phase | Action | Key Points STEP 1: 0-30 min — Confirm + Stabilise | Bladder scan, IV access, bloods (U&E/Cr/FBC/PSA/clotting), analgesia (IV morphine 0.1mg/kg + IV paracetamol 1g — avoid NSAIDs if AKI) | PSA before catheter! Avoid NSAIDs in renal impairment STEP 2: Urethral Catheterisation (FIRST-LINE) | 14-16Fr Foley catheter. BPH → 16-18Fr COUDÉ catheter (tip at 12 o'clock). Stricture → 12-14Fr straight. Record: time, volume, colour | COUDÉ tip at 12 o'clock for BPH. Larger catheter (18-20Fr) better for BPH — less flexible, won't curl. Smaller (12-14Fr) for stricture STEP 3: Urethral catheter FAILS | DO NOT FORCE. Urgent urology. Options: (a) Coudé under LA gel, (b) Cystoscopy + guidewire + dilatation, (c) Suprapubic catheter (SPC) — 2 fingerbreadths above pubic symphysis, USS guidance | SPC contraindications: previous lower midline surgery, bladder tumour, unconfirmed bladder fullness, bleeding diathesis STEP 4: Post-catheterisation monitoring | Monitor hourly urine output. Post-obstructive diuresis if UO >200 mL/hr for >2 hours → replace 50% hourly output with IV 0.9% NaCl. Drain completely (no evidence for staged drainage) | Post-obstructive diuresis = polyuria after relief of obstruction; risk: hypovolaemia, electrolyte disturbance STEP 5: Start alpha-blocker | Tamsulosin 400 mcg OD — start 24-48 hours BEFORE TWOC | Give for 24-72 hours before removal STEP 6: TWOC (Trial Without Catheter) — at 48-72 hours | Remove catheter in morning. Patient voids. Measure: voided volume + PVR (bladder scan within 15 min). SUCCESS = void >150 mL + PVR <200 mL. FAILURE = unable to void OR PVR >200 mL → re-catheterise | TWOC success rate: ~60-70% with alpha-blocker vs ~50% without STEP 7: Failed TWOC | Option A: Re-catheterise + 2nd TWOC in 3-5 days (success ~30%). Option B: Proceed to definitive surgical treatment | Spontaneous AUR → 75% need surgery ultimately --- DEFINITIVE SURGICAL OPTIONS TABLE --- Procedure | Indication | Notes TURP (Gold Standard) | BPH, prostate <100g | Resect prostatic tissue via scope; risks: retrograde ejaculation (90%), TURP syndrome (rare now), bleeding HoLEP | Large prostate >80g | Laser enucleation; lower bleeding; faster recovery; steep learning curve Open prostatectomy (Millin's) | Prostate >100g | Retropubic or transvesical; for very large prostates TUIP | Small prostate <30g | Incision only; preserves ejaculation better than TURP UroLift | Small-moderate BPH | Mechanical lift; preserves sexual function; no resection DVIU | Short urethral stricture (<1.5 cm) | Direct vision urethrotomy; high recurrence rate Urethroplasty | Long/recurrent stricture | Gold standard for complex strictures; anastomotic or augmentation Sacral nerve modulation | Neurogenic bladder / detrusor underactivity | Implanted electrode; stimulates S3 root --- PHARMACOLOGICAL MANAGEMENT TABLE --- Drug/Class | Mechanism | Dose | Key Side Effects | Notes Alpha-blockers (tamsulosin) | Relax smooth muscle of prostate/bladder neck/urethra | Tamsulosin 400 mcg OD; Alfuzosin 10 mg OD; Doxazosin 4-8 mg OD | Orthostatic hypotension (less with tamsulosin), retrograde ejaculation, dizziness, nasal congestion | Onset: days-weeks; Tamsulosin → IFIS (tell ophthalmologist before cataract surgery) 5-Alpha-reductase inhibitors | Block testosterone→DHT conversion → reduce prostate volume 20-30% | Finasteride 5 mg OD; Dutasteride 0.5 mg OD | Erectile dysfunction, decreased libido, ejaculatory dysfunction, gynaecomastia | Onset: 3-6 months; reduce AUR risk 50%; reduce PSA 50% (double when interpreting); TERATOGENIC — women must not handle crushed tablets Combination (alpha-blocker + 5-ARI) | Combined | Both drugs above | Additive | CombAT trial: superior to monotherapy for large prostates; use if prostate >30 mL + high AUR risk PDE-5 inhibitors | Relax smooth muscle of bladder/prostate | Tadalafil 5 mg OD | Headache, flushing, hypotension with nitrates | Licensed for LUTS/BPH ± ED Antibiotics | Infection | IV Ceftriaxone or Ciprofloxacin | Per drug | If acute prostatitis or UTI causing AUR --- NON-PHARMACOLOGICAL MANAGEMENT --- - Fluid management: avoid excessive fluid loading; spread fluid intake through day - Avoid constipation (aggravates retention): high-fibre diet, laxatives - Review and STOP offending medications (anticholinergics, opioids — taper if possible) - Voiding techniques: double voiding, timed voiding, Credé manoeuvre (manual suprapubic pressure — only in neurogenic) - Pelvic floor exercises (for stress incontinence post-TURP) - Warm bath/shower (relax sphincter — may help early retention) - Bladder training - Clean Intermittent Self-Catheterisation (CISC): GOLD STANDARD for neurogenic bladder long-term; every 4-6 hours; reduces UTI risk vs indwelling catheter; maintains bladder capacity --- CUR MANAGEMENT --- Assess type: HIGH-PRESSURE (bilateral hydronephrosis + renal impairment → urgent catheterisation + monitor renal recovery) vs LOW-PRESSURE (large compliant bladder → elective) Catheterisation for HIGH-PRESSURE CUR: drain slowly initially (500 mL/hour) to prevent rapid decompression haematuria; monitor post-obstructive diuresis carefully Ongoing: Treat underlying cause; CISC preferred for long-term; SPC if urethral catheter not possible; surgical correction of BOO when stable SECTION 7 — COMPLICATIONS AUR: Post-renal AKI (if untreated), post-obstructive diuresis (after decompression), decompression haematuria, UTI/urosepsis, autonomic dysreflexia (SCI patients — hypertensive emergency → drain bladder immediately) CUR: Recurrent UTIs, bladder stones (struvite/infection stones), vesicoureteric reflux → bilateral hydroureteronephrosis → CKD/ESRD, bladder diverticula, detrusor decompensation (irreversible atonic bladder), overflow incontinence Post-TURP (HIGH-YIELD): - Immediate: haemorrhage, clot retention, infection - Early: UTI, DVT, PE - Late: retrograde ejaculation (MOST COMMON ~90%), urethral stricture, bladder neck stenosis, incontinence (<1%), erectile dysfunction (rare), re-operation (10-15% at 10 years) - TURP syndrome: dilutional hyponatraemia + fluid overload from glycine irrigation absorption → confusion, visual disturbance, bradycardia (now rare with bipolar/saline TURP) SECTION 8 — EXAM SUMMARY (30 high-yield points in table) 1. AUR = painful; CUR = usually painless 2. Most common cause AUR in men = BPH (10% of men in 70s, 33% in 80s) 3. Most common cause AUR in women = neurogenic / Fowler syndrome 4. Drug-induced AUR: anticholinergics, opioids, alpha-agonists, TCAs, antihistamines 5. Cauda equina = AUR + saddle anaesthesia + bilateral leg weakness → SURGICAL EMERGENCY 6. Diagnosis confirmed by bladder scan >300 mL 7. First-line treatment = urethral catheterisation 8. Coudé catheter for BPH — tip at 12 o'clock; use 18-20Fr (larger = less flexible = won't curl in prostate) 9. SPC inserted 2 fingerbreadths above pubic symphysis; USS guidance essential 10. PSA must be checked BEFORE catheterisation 11. Two types of AUR: spontaneous (75% need surgery) vs precipitated (26% need surgery) 12. Tamsulosin (alpha-blocker) given 48h before TWOC improves success rate to 60-70% 13. TWOC success criteria: void >150 mL + PVR <200 mL 14. 5-ARIs reduce AUR risk by 50% but take 3-6 months — not useful acutely 15. 5-ARIs reduce PSA by 50% — always double PSA when interpreting result 16. Tamsulosin → IFIS — warn ophthalmologist before cataract surgery 17. Post-obstructive diuresis: replace 50% hourly output if UO >200 mL/hr 18. High-pressure CUR = bilateral hydronephrosis + renal impairment → urgent 19. TURP gold standard for BPH; most common late complication = retrograde ejaculation (90%) 20. TURP syndrome = dilutional hyponatraemia (now rare with bipolar TURP) 21. HoLEP for large prostates (>80-100 mL) 22. CISC = gold standard for neurogenic bladder long-term management 23. Clot retention → 3-way Foley catheter + continuous bladder irrigation (CBI) 24. DVIU for short strictures; urethroplasty for long/recurrent strictures 25. Acute prostatitis causing AUR → IV antibiotics + avoid TWOC until treated 26. Spontaneous AUR recurrence risk = 56-64% within 1 week without treatment 27. Finasteride/dutasteride teratogenic — women must not handle crushed tablets 28. Autonomic dysreflexia in SCI + AUR = hypertensive emergency → drain immediately 29. CombAT trial: dutasteride + tamsulosin superior to monotherapy for large prostates 30. Overflow incontinence in CUR = paradoxical incontinence — intravesical pressure = urethral resistance =========================== PDF 2 — EPILEPSY EXPANDED CONTENT =========================== Keep ALL content from the previous epilepsy notes (the existing file at /home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes.pdf contains the original). Reproduce ALL of it plus add these NEW sections: ORIGINAL SECTIONS (reproduce fully): 1. Definition & Epidemiology 2. Aetiology (ILAE) 3. Seizure Classification ILAE 2017 (full table with old/new terms, auras by lobe, all seizure types) 4. Epilepsy Syndromes table (West, LGS, CAE, JME, TLE, Dravet, Benign Rolandic) 5. Diagnosis (EEG, MRI, bloods, LP, prolactin) 6. Differential Diagnosis table (seizure vs syncope vs NEAD) 7. Management — when to start AEDs, AED selection table, full side effects table 8. Status Epilepticus time-based protocol 9. Special situations (driving, pregnancy AED table, febrile convulsions) 10. 30-point exam summary table NEW SECTIONS TO ADD: NEW SECTION A — FIRST SEIZURE MANAGEMENT ALGORITHM Step-by-step table: First seizure → Is it provoked? (fever, metabolic, drugs, acute brain injury, alcohol withdrawal) → YES: Treat underlying cause; AEDs usually NOT indicated → NO (unprovoked): Investigations (EEG + MRI brain + bloods) → High recurrence risk? (structural lesion on MRI, abnormal EEG, focal deficit, strong family history, nocturnal seizure) → YES: Start AED after counselling → No high risk factors → Discuss with patient; consider lifestyle + occupation + driving; patient may choose to observe OR start AED → If AED started: choose appropriate drug for seizure type, start low and titrate NEW SECTION B — CHRONIC EPILEPSY MANAGEMENT ALGORITHM (full flowchart as table) New diagnosis → Confirm with EEG + MRI → Identify syndrome/type → First AED monotherapy (appropriate for type) → → Seizure-free ≥2 years: consider gradual withdrawal (warn driving) → Seizures continue at adequate dose: switch to 2nd AED monotherapy → 2nd AED fails: try 3rd monotherapy OR dual therapy → Failed 2 appropriate AEDs at adequate doses = DRUG-REFRACTORY EPILEPSY (20%) → Refer specialist epilepsy centre → Pre-surgical evaluation: Video-EEG + High-res MRI + Neuropsychology + FDG-PET + Ictal SPECT + fMRI (language) + Wada test → SURGICAL CANDIDATE? YES → Surgery (temporal lobectomy 80-90% seizure-free in mesial TLE) → NOT surgical: VNS / DBS (ANT) / RNS / Ketogenic diet / Combination NEW SECTION C — NON-PHARMACOLOGICAL MANAGEMENT (complete) Lifestyle modifications: - Sleep hygiene (critical for JME — sleep deprivation is #1 trigger) - Alcohol avoidance (lowers seizure threshold) - Stress management and relaxation techniques - Photosensitive epilepsy: avoid flickering lights/strobing games, polarised/tinted glasses (FL-41 tint), cover one eye if exposed - Catamenial epilepsy (seizures perimenstrual): seizure diary, clobazam 10 mg TDS day -3 to +3 of cycle, progesterone supplementation (days 14-26), GnRH analogues (refractory) - Safety precautions: supervised swimming, no baths alone (shower preferred), no cooking over open flame unattended, no working at heights, no operating heavy machinery, no driving until seizure-free - Medical alert bracelet/card - Seizure diary (identify triggers, patterns, frequency) Dietary therapies (full table): Diet | Ratio | Best For | Side Effects | Monitoring Ketogenic diet | 4:1 fat:(carb+protein) | Children with refractory epilepsy, West syndrome, Dravet, GLUT-1 deficiency, pyruvate dehydrogenase deficiency | Constipation, hyperlipidaemia, kidney stones, growth retardation, bone demineralisation, vitamin/mineral deficiencies | Urinary ketones daily, growth, lipid profile, renal USS, FBC, LFTs Modified Atkins diet | Less strict | Adults and adolescents | Similar but milder | Less monitoring needed Low Glycaemic Index Treatment (LGIT) | Low GI foods | Alternative for adults | Fewer restrictions | Dietary review MCT diet | Medium chain triglyceride | Alternative ketogenic | GI upset, bloating | Titrate MCT oil slowly Psychological support: - CBT for depression/anxiety (very common comorbidities in epilepsy — up to 30-50%) - Neuropsychological assessment (memory, cognitive function) - Epilepsy nurse specialist / key worker - Patient and family education - Seizure first aid training for carers Social support: - DVLA/licensing authority notification (mandatory) - Employment guidance: avoid jobs at heights, near water, heavy machinery, piloting - Benefits and disability support - Support groups (Epilepsy Action, etc.) NEW SECTION D — SURGICAL MANAGEMENT (expanded) Pre-surgical evaluation includes: - Prolonged video-EEG monitoring (identify seizure onset zone) - High-resolution MRI (3T, epilepsy protocol) — hippocampal volumetry, T2/FLAIR for sclerosis - Neuropsychological testing (cognitive baseline, predict post-surgical deficits) - FDG-PET: interictal hypometabolism at seizure focus - Ictal SPECT (SISCOM): ictal hyperperfusion at onset zone - fMRI language/memory lateralisation - Wada test (intracarotid amobarbital test): determines language dominance and memory reserve of each hemisphere before dominant hemisphere surgery Types of surgery: Temporal lobectomy: for mesial TLE + hippocampal sclerosis; 60-80% seizure freedom; risks: memory impairment (dominant side), visual field defect — superior quadrantanopia "pie in the sky" (Meyer's loop injury), language deficits Lesionectomy: resection of structural lesion (tumour, cavernoma, focal cortical dysplasia); outcome depends on complete resection Hemispherectomy/hemispherotomy: for severe unilateral hemispheric epilepsy (Rasmussen encephalitis, hemimegalencephaly, Sturge-Weber); young children; already-deficient hemisphere Corpus callosotomy: for drop attacks (atonic seizures) in LGS; prevents bilateral propagation; not curative; palliative Multiple subpial transection (MST): when epileptogenic zone overlaps eloquent cortex; reduces propagation without resection NEW SECTION E — NEUROMODULATION (device-based, expanded) VNS: Left vagus nerve (right has cardiac projections); chest pulse generator; magnet swipe aborts individual seizure; side effects: hoarseness (most common), cough, throat pain, dyspnoea during stimulation; ~50% get ≥50% reduction DBS: Anterior nucleus of thalamus (ANT); SANTE trial: 68% had >50% reduction at 5 years; also centromedian nucleus for LGS/generalised RNS NeuroPace: closed-loop; detects ictal EEG → stimulates focus; implanted in skull; for 1-2 foci NEW SECTION F — WOMEN WITH EPILEPSY (comprehensive) Contraception: - Enzyme-inducing AEDs (CBZ, PHT, phenobarb, primidone, topiramate >200mg, oxcarbazepine) → reduce OCP efficacy → use ≥50 mcg ethinylestradiol OR barrier/IUD - Non-enzyme-inducing AEDs (valproate, lamotrigine, LEV, gabapentin) → standard OCP OK - OCP reduces lamotrigine levels by up to 50% → increase lamotrigine dose; monitor levels Pre-conception: folic acid 5mg/day ≥3 months before; switch valproate; lowest effective dose; monotherapy; counsel on risks Pregnancy monitoring: lamotrigine/LEV levels fall → monitor monthly and increase doses; detailed anomaly scan 18-20 weeks; oral vitamin K 10mg/day last 4 weeks if on enzyme inducers Labour: continue AEDs; IV lorazepam available; caesarean only if obstetric indication Post-partum: reduce lamotrigine/LEV back to pre-pregnancy dose; breastfeeding generally safe; sleep deprivation precautions NEW SECTION G — SUDEP Annual risk: 1:1000 general epilepsy; up to 1:150 refractory epilepsy Risk factors: frequent uncontrolled nocturnal GTCS, sleeping alone, prone position, young adult male, poor compliance Mechanism: post-ictal respiratory depression + cardiac arrhythmia (post-ictal generalised EEG suppression — PGES) Prevention: optimal seizure control, nocturnal supervision, movement monitors, avoid prone sleep, seizure alert dogs NEW SECTION H — FEBRILE CONVULSIONS MANAGEMENT ALGORITHM Immediate: 0-5 min: Recovery position, airway, time seizure, O2, BM glucose If >5 min: Buccal midazolam 0.5 mg/kg (max 10 mg) OR rectal diazepam 0.5 mg/kg If still seizing at 10 min: Second dose If still seizing at 20 min: Paediatric status epilepticus protocol Antipyretics: Paracetamol 15 mg/kg (NOT aspirin — Reye's syndrome) Cool environment, tepid sponging Investigate if complex: LP (if <18 months OR meningism), FBC, U&E, glucose, blood culture For complex febrile convulsions: MRI brain, EEG, neurology referral NOT proven to prevent recurrence: regular antipyretics, prophylactic AEDs DESIGN REQUIREMENTS FOR BOTH PDFs: - Cover page with coloured section boxes - Section banners: dark blue #1A3A5C - Warning boxes: red background with red border, "⚠ EXAM TRAP" label - Tip boxes: teal background (#1A7A6E border), "★ HIGH-YIELD" label - Note boxes: purple/orange background, "NOTE/CLINICAL PEARL" label - Algorithm sections: formatted as step-by-step tables with clear phases - All tables: dark blue headers, alternating white/light grey rows - Page header on every page with document title - Page footer: references + page number - Professional medical exam notes style RUN BOTH SCRIPTS. Return: 1. Exact path of AUR/CUR PDF + file size in KB 2. Exact path of Epilepsy v2 PDF + file size in KB 3. Confirm both are valid PDFs (check header bytes)

Browsing Directory

/home/daytona/workspace

Browsing Directory

~/epilepsy-pdf

Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/aur-cur-pdf

Writing File

~/aur-cur-pdf/generate_aur_cur.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY, TA_RIGHT

OUTPUT = "/home/daytona/workspace/aur-cur-pdf/AUR_CUR_Final_Year_Notes.pdf"

# ── Colour palette ────────────────────────────────────────────────────────────
DARK_BLUE    = colors.HexColor("#1A3A5C")
MED_BLUE     = colors.HexColor("#2E6DA4")
LIGHT_BLUE   = colors.HexColor("#D6E8F7")
TEAL         = colors.HexColor("#1A7A6E")
LIGHT_TEAL   = colors.HexColor("#D0EFEB")
RED          = colors.HexColor("#C0392B")
LIGHT_RED    = colors.HexColor("#FADBD8")
ORANGE       = colors.HexColor("#E67E22")
LIGHT_ORANGE = colors.HexColor("#FDEBD0")
GOLD         = colors.HexColor("#D4AC0D")
LIGHT_GOLD   = colors.HexColor("#FEF9E7")
PURPLE       = colors.HexColor("#6C3483")
LIGHT_PURPLE = colors.HexColor("#E8DAEF")
GREEN        = colors.HexColor("#1E8449")
LIGHT_GREEN  = colors.HexColor("#D5F5E3")
LIGHT_GREY   = colors.HexColor("#F2F4F7")
MID_GREY     = colors.HexColor("#95A5A6")
WHITE        = colors.white
BLACK        = colors.black

PAGE_W, PAGE_H = A4
MARGIN = 1.8 * cm

# ── Styles ────────────────────────────────────────────────────────────────────
base = getSampleStyleSheet()

def S(name, parent="Normal", **kw):
    return ParagraphStyle(name, parent=base[parent], **kw)

sty = {
    "h1":       S("h1",   fontSize=16, textColor=WHITE,     leading=22, spaceBefore=0, spaceAfter=0),
    "h2":       S("h2",   fontSize=12, textColor=DARK_BLUE, leading=17, spaceBefore=10, spaceAfter=3, fontName="Helvetica-Bold"),
    "h3":       S("h3",   fontSize=10.5, textColor=TEAL,    leading=15, spaceBefore=7,  spaceAfter=2, fontName="Helvetica-Bold"),
    "body":     S("body", fontSize=9,   leading=14, spaceAfter=4, alignment=TA_JUSTIFY),
    "bullet":   S("bul",  fontSize=9,   leading=13, leftIndent=14, spaceAfter=2),
    "sub_bul":  S("sbul", fontSize=8.5, leading=12, leftIndent=28, spaceAfter=2, textColor=colors.HexColor("#34495E")),
    "th":       S("th",   fontSize=8.5, textColor=WHITE,    leading=12, alignment=TA_CENTER, fontName="Helvetica-Bold"),
    "td":       S("td",   fontSize=8.5, leading=12, alignment=TA_LEFT),
    "td_c":     S("tdc",  fontSize=8.5, leading=12, alignment=TA_CENTER),
    "warn":     S("wrn",  fontSize=8.5, leading=13, textColor=RED,     leftIndent=8),
    "tip":      S("tip",  fontSize=8.5, leading=13, textColor=TEAL,    leftIndent=8),
    "exam_tip": S("et",   fontSize=8.5, leading=13, textColor=colors.HexColor("#7D3C98"), leftIndent=8),
    "caption":  S("cap",  fontSize=7.5, textColor=MID_GREY, alignment=TA_CENTER, spaceAfter=4),
    "cover_t":  S("ct",   fontSize=30, textColor=WHITE,     leading=40, alignment=TA_CENTER, fontName="Helvetica-Bold"),
    "cover_s":  S("cs",   fontSize=12, textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER, leading=18),
    "cover_b":  S("cb",   fontSize=9,  textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER),
    "num_lbl":  S("nl",   fontSize=18, textColor=WHITE, alignment=TA_CENTER, fontName="Helvetica-Bold"),
    "footer":   S("ft",   fontSize=7,  textColor=MID_GREY,  alignment=TA_CENTER),
    "warn_box": S("wb",   fontSize=8.5, leading=13, textColor=RED, leftIndent=8, fontName="Helvetica-Bold"),
}

# ── Helpers ───────────────────────────────────────────────────────────────────
W = PAGE_W - 2 * MARGIN

def sec_hdr(title, subtitle="", color=DARK_BLUE):
    data = [[Paragraph(f"<b>{title}</b>", sty["h1"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), color),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
        ("LEFTPADDING",   (0,0), (-1,-1), 14),
        ("RIGHTPADDING",  (0,0), (-1,-1), 14),
    ]))
    out = [t]
    if subtitle:
        out.append(Paragraph(subtitle, sty["body"]))
    out.append(Spacer(1, 6))
    return out

def h2(txt):
    p = Paragraph(f"<b>{txt}</b>", sty["h2"])
    hr = HRFlowable(width="100%", thickness=1.2, color=MED_BLUE, spaceAfter=4)
    return [p, hr]

def h3(txt):
    return [Paragraph(f"<b>{txt}</b>", sty["h3"])]

def body(txt):
    return [Paragraph(txt, sty["body"])]

def bul(items, sub=False):
    s = sty["sub_bul"] if sub else sty["bullet"]
    return [Paragraph(f"• {i}", s) for i in items]

def sp(h=6):
    return [Spacer(1, h)]

def warn(txt, label="⚠ EXAM TRAP"):
    data = [[Paragraph(f"<b>{label}:</b> {txt}", sty["warn"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_RED),
        ("BOX",           (0,0), (-1,-1), 1, RED),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 5)]

def tip(txt, label="★ HIGH-YIELD"):
    data = [[Paragraph(f"<b>{label}:</b> {txt}", sty["tip"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_TEAL),
        ("BOX",           (0,0), (-1,-1), 1, TEAL),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 5)]

def note(txt, label="CLINICAL PEARL"):
    data = [[Paragraph(f"<b>{label}:</b> {txt}", sty["exam_tip"])]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_PURPLE),
        ("BOX",           (0,0), (-1,-1), 1, PURPLE),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 8),
        ("RIGHTPADDING",  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 5)]

def mk_table(headers, rows, col_widths=None, hdr_color=DARK_BLUE):
    if col_widths is None:
        col_widths = [W / len(headers)] * len(headers)
    hdr_row = [Paragraph(f"<b>{h}</b>", sty["th"]) for h in headers]
    data = [hdr_row] + [[Paragraph(str(c), sty["td"]) for c in row] for row in rows]
    t = Table(data, colWidths=col_widths, repeatRows=1)
    t.setStyle(TableStyle([
        ("BACKGROUND",     (0,0), (-1,0),  hdr_color),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [WHITE, LIGHT_GREY]),
        ("GRID",           (0,0), (-1,-1), 0.4, MID_GREY),
        ("TOPPADDING",     (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",  (0,0), (-1,-1), 5),
        ("LEFTPADDING",    (0,0), (-1,-1), 6),
        ("RIGHTPADDING",   (0,0), (-1,-1), 6),
        ("VALIGN",         (0,0), (-1,-1), "TOP"),
    ]))
    return [t, Spacer(1, 8)]

def colored_box(items, title, bg, border):
    paras = [Paragraph(f"<b>{title}</b>", ParagraphStyle("bxtl", fontSize=10, textColor=border, fontName="Helvetica-Bold", spaceAfter=4))]
    for i in items:
        paras.append(Paragraph(f"◆  {i}", ParagraphStyle("bxi", fontSize=9, leading=13, textColor=colors.HexColor("#1a1a1a"))))
    t = Table([[paras]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), bg),
        ("BOX",           (0,0), (-1,-1), 1.2, border),
        ("TOPPADDING",    (0,0), (-1,-1), 8),
        ("BOTTOMPADDING", (0,0), (-1,-1), 8),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
        ("RIGHTPADDING",  (0,0), (-1,-1), 10),
    ]))
    return [t, Spacer(1, 6)]

# ── Page header/footer ────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, PAGE_H - 0.65*cm, PAGE_W, 0.65*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 7)
    canvas.drawString(MARGIN, PAGE_H - 0.45*cm, "ACUTE & CHRONIC URINARY RETENTION  —  Final Year MBBS Exam Notes")
    canvas.setFont("Helvetica", 7)
    canvas.drawRightString(PAGE_W - MARGIN, PAGE_H - 0.45*cm, "Bailey & Love | Oxford Handbook of Urology | EAU Guidelines")
    canvas.setFillColor(LIGHT_GREY)
    canvas.rect(0, 0, PAGE_W, 0.9*cm, fill=1, stroke=0)
    canvas.setFillColor(MID_GREY)
    canvas.setFont("Helvetica", 6.5)
    canvas.drawString(MARGIN, 0.32*cm,
        "References: Bailey & Love's Short Practice of Surgery 27e • Oxford Handbook of Urology • EAU Guidelines 2023 • "
        "Campbell-Walsh-Wein Urology • Mundy Textbook of Urology")
    canvas.drawRightString(PAGE_W - MARGIN, 0.32*cm, f"Page {doc.page}")
    canvas.restoreState()

# ── Cover page ────────────────────────────────────────────────────────────────
def cover():
    E = []
    d = [[Paragraph("ACUTE &amp; CHRONIC<br/>URINARY RETENTION", sty["cover_t"])]]
    t = Table(d, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), DARK_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 32),
        ("BOTTOMPADDING", (0,0), (-1,-1), 14),
        ("LEFTPADDING",   (0,0), (-1,-1), 20),
    ]))
    E.append(t)
    sub_d = [[Paragraph("Final Year MBBS Exam Notes — Surgery &amp; Urology", sty["cover_s"])]]
    sub_t = Table(sub_d, colWidths=[W])
    sub_t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), MED_BLUE),
        ("TOPPADDING",    (0,0), (-1,-1), 10),
        ("BOTTOMPADDING", (0,0), (-1,-1), 10),
    ]))
    E.append(sub_t)
    E.append(Spacer(1, 16))

    sections = [
        (DARK_BLUE,   "1", "Definitions — AUR vs CUR comparison table"),
        (MED_BLUE,    "2", "Aetiology — Obstructive, Neurogenic, Pharmacological"),
        (TEAL,        "3", "Pathophysiology — BOO, High vs Low Pressure"),
        (PURPLE,      "4", "Clinical Features — AUR Emergency Presentation"),
        (colors.HexColor("#1A7A6E"), "5", "Investigations — Bladder scan, PSA, Urodynamics"),
        (ORANGE,      "6", "Management — Emergency Algorithm, TWOC, Surgical Options"),
        (colors.HexColor("#1E8449"), "7", "Complications — Post-TURP, Obstructive Diuresis"),
        (colors.HexColor("#922B21"), "8", "30-Point High-Yield Exam Summary Table"),
    ]
    for col, num, name in sections:
        rd = [[
            Paragraph(f"<b>{num}</b>", sty["num_lbl"]),
            Paragraph(f"<b>{name}</b>", ParagraphStyle("sn", fontSize=10.5, textColor=WHITE, leading=15)),
        ]]
        rt = Table(rd, colWidths=[1.2*cm, W - 1.2*cm - 0.15*cm])
        rt.setStyle(TableStyle([
            ("BACKGROUND",    (0,0), (-1,-1), col),
            ("TOPPADDING",    (0,0), (-1,-1), 8),
            ("BOTTOMPADDING", (0,0), (-1,-1), 8),
            ("LEFTPADDING",   (0,0), (-1,-1), 10),
            ("VALIGN",        (0,0), (-1,-1), "MIDDLE"),
        ]))
        E.append(rt)
        E.append(Spacer(1, 4))

    E.append(Spacer(1, 14))
    ref_d = [[Paragraph(
        "<b>References:</b> Bailey &amp; Love's Short Practice of Surgery 27e  •  Oxford Handbook of Urology  •  "
        "EAU Guidelines 2023  •  Campbell-Walsh-Wein Urology 12e  •  Mundy's Textbook of Urology  •  "
        "NICE Guidelines NG118 (Lower Urinary Tract Symptoms)",
        sty["caption"])]]
    ref_t = Table(ref_d, colWidths=[W])
    ref_t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0), (-1,-1), LIGHT_GREY),
        ("BOX",           (0,0), (-1,-1), 0.5, MID_GREY),
        ("TOPPADDING",    (0,0), (-1,-1), 7),
        ("BOTTOMPADDING", (0,0), (-1,-1), 7),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
    ]))
    E.append(ref_t)
    E.append(PageBreak())
    return E

# ── Main content ──────────────────────────────────────────────────────────────
def content():
    E = []

    # ── SECTION 1: Definitions ────────────────────────────────────────────────
    E += sec_hdr("1. Definitions", color=DARK_BLUE)
    E += colored_box([
        "AUR (Acute Urinary Retention): Sudden, PAINFUL inability to void voluntarily despite a full bladder. EMERGENCY.",
        "CUR (Chronic Urinary Retention): Painless, persistent incomplete emptying. Post-void residual (PVR) >300 mL. May cause overflow incontinence.",
    ], "CORE DEFINITIONS", LIGHT_BLUE, DARK_BLUE)

    E += h2("AUR vs CUR — Comparison Table")
    E += mk_table(
        ["Feature", "AUR", "CUR"],
        [
            ["Onset",        "Sudden",                           "Insidious"],
            ["Pain",         "Severe suprapubic pain",           "Usually painless"],
            ["Bladder",      "Distended, tender",                "Large, non-tender"],
            ["PVR",          "Total (no voiding)",               ">300 mL"],
            ["Complications","AKI, urosepsis",                   "CKD, bilateral hydronephrosis, recurrent UTI"],
            ["Urgency",      "EMERGENCY",                        "Urgent/elective"],
        ],
        col_widths=[3.8*cm, (W-3.8*cm)/2, (W-3.8*cm)/2]
    )
    E += warn("AUR is painful — this distinguishes it from CUR. A patient with painless urinary retention has CUR until proven otherwise. Overflow incontinence (constant dribbling) may complicate both but is classic in CUR.")
    E += sp()

    # ── SECTION 2: Aetiology ──────────────────────────────────────────────────
    E += sec_hdr("2. Aetiology", color=MED_BLUE)

    E += h2("A. Obstructive Causes")
    E += bul([
        "<b>BPH</b> (most common in men >50 — 10% of men in 70s, 33% in 80s)",
        "Urethral stricture (post-trauma / instrumentation / infection)",
        "Prostate carcinoma",
        "Bladder neck obstruction",
        "Bladder stone at neck",
        "Clot retention (haematuria) — requires 3-way catheter + CBI",
        "Phimosis / paraphimosis / meatal stenosis",
        "Pelvic organ prolapse (cystocele, uterine prolapse — women)",
        "Constipation / faecal impaction",
        "Pelvic mass (fibroids, ovarian cyst, gravid uterus)",
    ])

    E += h2("B. Neurogenic Causes")
    E += bul([
        "Spinal cord injury / compression",
        "<b>Cauda equina syndrome</b> — AUR + saddle anaesthesia + bilateral leg weakness + loss of anal tone → SURGICAL EMERGENCY",
        "Multiple sclerosis",
        "Parkinson's disease",
        "Diabetic autonomic neuropathy",
        "Post-operative (spinal/epidural anaesthesia, anorectal/hernia surgery)",
        "Fowler syndrome (young women — large acontractile bladder, no neurological cause)",
    ])
    E += warn("Cauda equina syndrome = AUR + saddle anaesthesia + bilateral leg weakness + reduced anal tone. This is a surgical emergency — MRI spine immediately and urgent neurosurgery referral.")

    E += h2("C. Pharmacological (Drug-Induced AUR — Exam List)")
    E += mk_table(
        ["Drug Class", "Examples", "Mechanism"],
        [
            ["Anticholinergics",         "Oxybutynin, TCAs (amitriptyline), antihistamines (chlorphenamine), antipsychotics", "Block muscarinic receptors → detrusor inhibition"],
            ["Opioids/Narcotics",         "Morphine, codeine, tramadol", "Central & peripheral effects; increase urethral tone"],
            ["Alpha-adrenergic agonists", "Pseudoephedrine, phenylephrine, decongestants", "Increase urethral smooth muscle tone"],
            ["NSAIDs",                    "Ibuprofen, diclofenac", "Reduce prostaglandin-mediated detrusor contraction"],
            ["Calcium channel blockers",  "Nifedipine, amlodipine", "Reduce detrusor contractility"],
            ["Alcohol (acute)",           "Ethanol", "Diuresis + detrusor inhibition"],
        ],
        col_widths=[3.5*cm, 5.5*cm, W-9*cm]
    )

    E += h2("D. Other Causes")
    E += bul([
        "Acute prostatitis / prostatic abscess",
        "Post-partum urinary retention",
        "Psychogenic / anxiety",
        "Fowler syndrome",
    ])
    E += sp()

    E += h2("Two Types of AUR")
    E += mk_table(
        ["Type", "Definition", "Surgical Need"],
        [
            ["Spontaneous AUR", "Natural history of BPH progression; no precipitant identified", "~75% ultimately require surgery"],
            ["Precipitated AUR", "Triggered by identifiable event: anaesthesia, drugs, instrumentation, constipation, UTI", "Only ~26% require surgery — remove precipitant"],
        ],
        col_widths=[3.5*cm, 7*cm, W-10.5*cm]
    )
    E += tip("Spontaneous AUR has a 56–64% recurrence risk within 1 week without treatment and 75% ultimately need surgery. Precipitated AUR has a much better prognosis — identify and remove the precipitant.")

    E += h2("AUR Risk Factors in Men (BPH)")
    E += mk_table(
        ["Risk Factor", "Threshold"],
        [
            ["Age",              ">70 years"],
            ["Prostate volume",  ">30 mL"],
            ["PSA",              ">1.4 ng/mL"],
            ["Peak flow rate",   "<12 mL/sec"],
            ["IPSS score",       ">7"],
            ["Previous AUR",     "Any previous episode"],
        ],
        col_widths=[5*cm, W-5*cm]
    )
    E += sp()

    # ── SECTION 3: Pathophysiology ────────────────────────────────────────────
    E += sec_hdr("3. Pathophysiology", color=TEAL)
    E += body("Normal voiding requires coordinated <b>detrusor contraction</b> (parasympathetic — M3 muscarinic) + <b>urethral sphincter relaxation</b>, orchestrated by the pontine micturition centre.")
    E += sp(4)
    E += mk_table(
        ["Mechanism", "Details"],
        [
            ["BOO → AUR",           "Bladder outlet obstruction exceeds detrusor contractility, OR detrusor contractility is lost → acute inability to empty"],
            ["Rising bladder pressure", "→ ureteric obstruction → hydronephrosis → post-renal AKI (if untreated)"],
            ["CUR pathology",        "Chronic distension → detrusor fibrosis and irreversible acontractile bladder"],
            ["Overflow incontinence","Intravesical pressure equals urethral resistance → constant dribbling ('water over a dam')"],
            ["High-pressure CUR",    "Upper tract dilatation + bilateral hydronephrosis + renal impairment → SURGICAL URGENCY"],
            ["Low-pressure CUR",     "Large compliant bladder, no upper tract dilatation → less urgent; elective management"],
        ],
        col_widths=[4.5*cm, W-4.5*cm]
    )
    E += warn("High-pressure CUR = bilateral hydronephrosis + renal impairment = URGENT catheterisation required. Low-pressure CUR = large compliant bladder, normal upper tracts = can be managed electively.")
    E += sp()

    # ── SECTION 4: Clinical Features ──────────────────────────────────────────
    E += sec_hdr("4. Clinical Features", color=PURPLE)

    E += h2("A. AUR — Presentation")
    E += colored_box([
        "Sudden complete inability to void despite urge",
        "Severe suprapubic pain and distress (PAINFUL — differentiates from CUR)",
        "Suprapubic swelling (palpable and percussable — dull to percussion)",
        "Typically >300–500 mL in bladder at presentation",
        "Autonomic features: tachycardia, hypertension, diaphoresis",
        "May dribble small amounts (overflow — DISTINGUISHES from anuria)",
    ], "AUR EMERGENCY PRESENTATION", LIGHT_RED, RED)

    E += h2("B. CUR — Presentation")
    E += bul([
        "Often <b>insidious and asymptomatic</b> — found incidentally",
        "Hesitancy, poor stream, straining (voiding LUTS)",
        "Overflow incontinence: constant dribbling of urine",
        "Nocturia and urinary frequency (storage LUTS)",
        "Recurrent UTIs",
        "Painless palpable bladder (large, non-tender, percussable)",
        "Signs of renal failure if high-pressure: hypertension, oedema, uraemia, pallor",
    ])

    E += h2("C. Examination Findings")
    E += mk_table(
        ["Finding", "Significance"],
        [
            ["Suprapubic dullness to percussion",        "Confirms full bladder"],
            ["DRE — smooth, enlarged prostate",          "BPH"],
            ["DRE — irregular, hard, nodular prostate",  "Prostate carcinoma"],
            ["DRE — rectal mass",                        "Pelvic malignancy, faecal impaction"],
            ["Saddle anaesthesia + reduced anal tone",    "Cauda equina syndrome — EMERGENCY"],
            ["Phimosis / meatal stenosis",               "Obstructive cause in males"],
            ["Signs of uraemia (oedema, hypertension)",  "High-pressure CUR with renal impairment"],
        ],
        col_widths=[5.5*cm, W-5.5*cm]
    )
    E += note("Always examine the external genitalia in male patients with AUR. Phimosis, paraphimosis, and meatal stenosis are correctable obstructive causes that must not be missed.")
    E += sp()

    # ── SECTION 5: Investigations ──────────────────────────────────────────────
    E += sec_hdr("5. Investigations", color=colors.HexColor("#1A7A6E"))

    E += h2("Bedside")
    E += bul([
        "<b>Bladder scanner (USS)</b> — confirms retention and measures volume. >300 mL = retention. ESSENTIAL before catheterisation.",
        "Urine dipstick + MSU (culture) — infection screen",
    ])
    E += warn("PSA MUST be checked BEFORE catheterisation. Urethral catheterisation raises PSA non-specifically, making subsequent PSA interpretation unreliable.")

    E += h2("Blood Tests")
    E += mk_table(
        ["Test", "Why"],
        [
            ["U&E + Creatinine",        "Renal function — is there AKI? (post-renal)"],
            ["FBC",                     "Infection (raised WBC), anaemia (CKD, haematuria)"],
            ["PSA",                     "Before catheterisation. >4 ng/mL suspicious for malignancy. 5-ARIs reduce PSA by 50%."],
            ["Clotting",                "If haematuria or clot retention present"],
            ["Blood cultures",          "If febrile / septic (urosepsis)"],
            ["Blood glucose",           "Diabetes (autonomic neuropathy as cause)"],
        ],
        col_widths=[4*cm, W-4*cm]
    )

    E += h2("Imaging")
    E += bul([
        "KUB X-ray — calculi, constipation/faecal impaction",
        "USS renal tract — hydronephrosis, prostate size, PVR (high vs low pressure CUR)",
        "CT KUB — calculi, pelvic masses, lymph nodes",
        "MRI spine — suspected cord compression, cauda equina syndrome",
    ])

    E += h2("Urodynamics / Urological")
    E += mk_table(
        ["Test", "Significance"],
        [
            ["Uroflowmetry",      "Peak flow <10 mL/sec = significant obstruction; 10–15 borderline; >15 normal"],
            ["PVR measurement",   ">300 mL = CUR diagnosis confirmed"],
            ["Pressure-flow studies", "Distinguishes BOO (high pressure + low flow) from detrusor underactivity (low pressure + low flow)"],
            ["Cystoscopy",        "Direct visualisation: stricture, bladder neck, prostate, tumour, calculi"],
            ["IPSS questionnaire","0–7 mild; 8–19 moderate; ≥20 severe LUTS"],
        ],
        col_widths=[4.5*cm, W-4.5*cm]
    )
    E += sp()

    # ── SECTION 6: Management ──────────────────────────────────────────────────
    E += sec_hdr("6. Management", color=GREEN)

    # --- AUR Emergency Algorithm ---
    E += h2("AUR Emergency Management Algorithm")
    E += mk_table(
        ["Phase", "Action", "Key Points"],
        [
            ["STEP 1\n0–30 min\nConfirm + Stabilise",
             "Bladder scan (confirm >300 mL). IV access. Bloods: U&E/Cr, FBC, PSA, clotting. Analgesia: IV morphine 0.1 mg/kg + IV paracetamol 1 g.",
             "PSA BEFORE catheter! Avoid NSAIDs if AKI present."],

            ["STEP 2\nUrethral Catheterisation\n(FIRST-LINE)",
             "14–16 Fr Foley catheter. BPH → 16–18 Fr COUDE catheter (tip at 12 o'clock). Stricture → 12–14 Fr straight. Record: time, volume, colour of urine.",
             "COUDE tip at 12 o'clock for BPH. Larger catheter (18–20 Fr) better for BPH — less flexible, won't curl. Smaller (12–14 Fr) for stricture."],

            ["STEP 3\nUrethral catheter FAILS",
             "DO NOT FORCE. Urgent urology. Options: (a) Coude under LA gel, (b) Cystoscopy + guidewire + dilatation, (c) Suprapubic catheter (SPC) — 2 fingerbreadths above pubic symphysis under USS guidance.",
             "SPC contraindications: previous lower midline surgery, bladder tumour, unconfirmed bladder fullness, bleeding diathesis."],

            ["STEP 4\nPost-catheterisation monitoring",
             "Monitor hourly urine output. Post-obstructive diuresis if UO >200 mL/hr for >2 hours → replace 50% hourly output with IV 0.9% NaCl.",
             "Drain completely (no evidence for staged drainage). Post-obstructive diuresis risk: hypovolaemia, electrolyte disturbance."],

            ["STEP 5\nStart alpha-blocker",
             "Tamsulosin 400 mcg OD — start 24–48 hours BEFORE TWOC.",
             "Give for 24–72 hours before catheter removal."],

            ["STEP 6\nTWOC at 48–72 hours",
             "Remove catheter in morning. Patient voids. Measure: voided volume + PVR (bladder scan within 15 min). SUCCESS = void >150 mL + PVR <200 mL. FAILURE = unable to void OR PVR >200 mL → re-catheterise.",
             "TWOC success rate: ~60–70% with alpha-blocker vs ~50% without."],

            ["STEP 7\nFailed TWOC",
             "Option A: Re-catheterise + 2nd TWOC in 3–5 days (success ~30%). Option B: Proceed to definitive surgical treatment.",
             "Spontaneous AUR → 75% need surgery ultimately."],
        ],
        col_widths=[3*cm, 7.5*cm, W-10.5*cm],
        hdr_color=colors.HexColor("#1E8449")
    )
    E += tip("TWOC = Trial Without Catheter. Always give tamsulosin 24–48h before TWOC. Success criteria: voided volume >150 mL AND PVR <200 mL on bladder scan within 15 minutes.")

    # --- Definitive Surgical Options ---
    E += h2("Definitive Surgical Options")
    E += mk_table(
        ["Procedure", "Indication", "Notes"],
        [
            ["TURP (Gold Standard)",          "BPH, prostate <100 g",           "Resect prostatic tissue via scope; risks: retrograde ejaculation (90%), TURP syndrome (now rare), bleeding"],
            ["HoLEP",                         "Large prostate >80 g",            "Laser enucleation; lower bleeding; faster recovery; steep learning curve"],
            ["Open prostatectomy (Millin's)", "Prostate >100 g",                 "Retropubic or transvesical; for very large prostates"],
            ["TUIP",                          "Small prostate <30 g",            "Incision only; preserves ejaculation better than TURP"],
            ["UroLift",                       "Small–moderate BPH",              "Mechanical lift; preserves sexual function; no resection"],
            ["DVIU",                          "Short urethral stricture <1.5 cm","Direct vision urethrotomy; high recurrence rate"],
            ["Urethroplasty",                 "Long/recurrent stricture",         "Gold standard for complex strictures; anastomotic or augmentation"],
            ["Sacral nerve modulation",       "Neurogenic bladder / detrusor underactivity", "Implanted electrode; stimulates S3 root"],
        ],
        col_widths=[3.5*cm, 3.8*cm, W-7.3*cm]
    )
    E += warn("TURP most common late complication = retrograde ejaculation (~90%). TURP syndrome = dilutional hyponatraemia + fluid overload from glycine irrigation (now rare with bipolar/saline TURP).")

    # --- Pharmacological Management ---
    E += h2("Pharmacological Management")
    E += mk_table(
        ["Drug/Class", "Mechanism", "Dose", "Key Side Effects", "Notes"],
        [
            ["Alpha-blockers\n(tamsulosin, alfuzosin, doxazosin)",
             "Relax smooth muscle of prostate/bladder neck/urethra",
             "Tamsulosin 400 mcg OD; Alfuzosin 10 mg OD; Doxazosin 4–8 mg OD",
             "Orthostatic hypotension (less with tamsulosin), retrograde ejaculation, dizziness, nasal congestion",
             "Onset days–weeks. Tamsulosin → IFIS (warn ophthalmologist before cataract surgery)."],

            ["5-Alpha-reductase inhibitors\n(finasteride, dutasteride)",
             "Block testosterone → DHT conversion → reduce prostate volume 20–30%",
             "Finasteride 5 mg OD; Dutasteride 0.5 mg OD",
             "Erectile dysfunction, decreased libido, ejaculatory dysfunction, gynaecomastia",
             "Onset 3–6 months. Reduce AUR risk 50%. Reduce PSA 50% — DOUBLE when interpreting. TERATOGENIC — women must not handle crushed tablets."],

            ["Combination\n(alpha-blocker + 5-ARI)",
             "Combined mechanism",
             "Both drugs as above",
             "Additive side effects",
             "CombAT trial: dutasteride + tamsulosin superior to monotherapy for large prostates. Use if prostate >30 mL + high AUR risk."],

            ["PDE-5 inhibitors\n(tadalafil)",
             "Relax smooth muscle of bladder/prostate",
             "Tadalafil 5 mg OD",
             "Headache, flushing, hypotension with nitrates",
             "Licensed for LUTS/BPH ± erectile dysfunction."],

            ["Antibiotics",
             "Treat infection",
             "IV Ceftriaxone or Ciprofloxacin",
             "Drug-specific",
             "If acute prostatitis or UTI causing AUR. Avoid TWOC until infection treated."],
        ],
        col_widths=[3.2*cm, 3*cm, 3*cm, 4*cm, W-13.2*cm]
    )
    E += warn("5-ARIs reduce PSA by approximately 50%. If a patient is on finasteride or dutasteride and their PSA is 2 ng/mL, the 'true' value is approximately 4 ng/mL. Failure to account for this will miss prostate cancer.")

    # --- Non-Pharmacological ---
    E += h2("Non-Pharmacological Management")
    E += bul([
        "Fluid management: avoid excessive loading; spread fluid intake through the day",
        "Avoid constipation: high-fibre diet, regular laxatives",
        "Review and STOP offending medications (anticholinergics, opioids — taper if possible)",
        "Voiding techniques: double voiding, timed voiding; Credé manoeuvre (manual suprapubic pressure — neurogenic only)",
        "Pelvic floor exercises (stress incontinence post-TURP)",
        "Warm bath/shower (relax sphincter — may help early retention)",
        "Bladder training",
        "<b>Clean Intermittent Self-Catheterisation (CISC)</b> — GOLD STANDARD for neurogenic bladder long-term; every 4–6 hours; reduces UTI risk vs indwelling catheter; maintains bladder capacity",
    ])

    # --- CUR Management ---
    E += h2("CUR Management")
    E += colored_box([
        "Assess type: HIGH-PRESSURE (bilateral hydronephrosis + renal impairment) vs LOW-PRESSURE (large compliant bladder, no upper tract dilatation)",
        "HIGH-PRESSURE CUR: urgent catheterisation. Drain slowly initially (500 mL/hour) to prevent rapid decompression haematuria. Monitor renal recovery and post-obstructive diuresis carefully.",
        "LOW-PRESSURE CUR: elective management. Treat underlying cause. CISC preferred for long-term management.",
        "SPC if urethral catheter not possible. Surgical correction of BOO when clinically stable.",
    ], "CUR MANAGEMENT APPROACH", LIGHT_TEAL, TEAL)
    E += sp()

    # ── SECTION 7: Complications ───────────────────────────────────────────────
    E += sec_hdr("7. Complications", color=colors.HexColor("#922B21"))

    E += h2("Complications of AUR")
    E += mk_table(
        ["Complication", "Details"],
        [
            ["Post-renal AKI",            "Rising intravesical pressure → ureteric obstruction → hydronephrosis → renal failure"],
            ["Post-obstructive diuresis", "Polyuria after relief of obstruction (UO >200 mL/hr). Risk: hypovolaemia, electrolyte disturbance. Replace 50% of hourly output IV."],
            ["Decompression haematuria",  "Rapid decompression of distended bladder → bladder mucosal bleeding. Drain slowly in CUR."],
            ["UTI / urosepsis",           "Stagnant urine + catheterisation = infection risk. Treat aggressively."],
            ["Autonomic dysreflexia",     "SCI patients (T6 or above): bladder distension → massive sympathetic discharge → severe hypertension, bradycardia, sweating, headache. EMERGENCY — drain bladder immediately."],
        ],
        col_widths=[4.5*cm, W-4.5*cm]
    )
    E += warn("Autonomic dysreflexia in spinal cord injury (T6+) is a hypertensive emergency. AUR is the most common trigger. Treatment: sit patient upright, drain bladder immediately.")

    E += h2("Complications of CUR")
    E += bul([
        "Recurrent UTIs (stagnant urine)",
        "Bladder stones (struvite/infection stones from stasis)",
        "Vesicoureteric reflux → bilateral hydroureteronephrosis → CKD/ESRD",
        "Bladder diverticula",
        "Detrusor decompensation (irreversible atonic bladder)",
        "Overflow incontinence (paradoxical incontinence)",
    ])

    E += h2("Post-TURP Complications — High-Yield")
    E += mk_table(
        ["Timing", "Complication", "Notes"],
        [
            ["Immediate",  "Haemorrhage",                    "Common — irrigate with CBI; may need return to theatre"],
            ["Immediate",  "Clot retention",                  "3-way Foley + CBI + bladder washout"],
            ["Early",      "UTI",                             "Pre-operative MSSU and antibiotic prophylaxis"],
            ["Early",      "DVT/PE",                         "Anticoagulation prophylaxis + stockings"],
            ["Late",       "Retrograde ejaculation (90%)",    "MOST COMMON late complication — semen goes into bladder; must counsel pre-operatively"],
            ["Late",       "Urethral stricture",             "From instrumentation; treat with DVIU or urethroplasty"],
            ["Late",       "Bladder neck stenosis",          "From scarring; treat with incision"],
            ["Late",       "Incontinence (<1%)",             "Usually stress incontinence; usually resolves"],
            ["Late",       "Erectile dysfunction (rare)",    "Generally preserved in TURP"],
            ["Late",       "Re-operation",                   "10–15% at 10 years"],
            ["Special",    "TURP syndrome",                  "Dilutional hyponatraemia + fluid overload from glycine irrigation. Now RARE with bipolar/saline TURP. Treat with IV hypertonic saline + furosemide."],
        ],
        col_widths=[2.5*cm, 4.5*cm, W-7*cm]
    )
    E += note("Always counsel patients about retrograde ejaculation before TURP (90% rate). Also counsel about the risk of urethral stricture (~3%) and the need for re-operation at 10 years (~10–15%).")
    E += sp()

    # ── SECTION 8: Exam Summary ────────────────────────────────────────────────
    E += sec_hdr("8. High-Yield Exam Summary — 30 Key Points", color=DARK_BLUE)
    E += mk_table(
        ["#", "Key Exam Point", "Answer / Fact"],
        [
            ["1",  "AUR vs CUR — most distinguishing feature",  "AUR = PAINFUL; CUR = usually PAINLESS"],
            ["2",  "Most common cause AUR in men",               "BPH (10% of men in 70s, 33% in 80s)"],
            ["3",  "Most common cause AUR in women",             "Neurogenic / Fowler syndrome"],
            ["4",  "Drug-induced AUR causes",                    "Anticholinergics, opioids, alpha-agonists, TCAs, antihistamines"],
            ["5",  "Cauda equina syndrome presentation",         "AUR + saddle anaesthesia + bilateral leg weakness + reduced anal tone → SURGICAL EMERGENCY"],
            ["6",  "Diagnostic confirmation",                    "Bladder scanner: confirmed if volume >300 mL"],
            ["7",  "First-line treatment AUR",                   "Urethral catheterisation (14–16 Fr Foley)"],
            ["8",  "Coude catheter — key point",                 "Used for BPH; tip at 12 o'clock; 18–20 Fr (larger = less flexible = won't curl in prostate)"],
            ["9",  "SPC insertion point",                        "2 fingerbreadths above pubic symphysis; USS guidance essential"],
            ["10", "PSA timing",                                  "BEFORE catheterisation (catheter raises PSA non-specifically)"],
            ["11", "Two types of AUR",                           "Spontaneous (75% need surgery) vs Precipitated (26% need surgery)"],
            ["12", "Alpha-blocker + TWOC",                       "Tamsulosin 400 mcg OD given 48 h before TWOC improves success to 60–70%"],
            ["13", "TWOC success criteria",                      "Voided volume >150 mL AND PVR <200 mL on bladder scan within 15 min"],
            ["14", "5-ARIs onset and effect",                    "Take 3–6 months to work; reduce AUR risk by 50%; not useful acutely"],
            ["15", "5-ARIs and PSA",                             "Reduce PSA by 50% — ALWAYS double PSA when interpreting on 5-ARI"],
            ["16", "Tamsulosin — special warning",               "IFIS (Intraoperative Floppy Iris Syndrome) — warn ophthalmologist before cataract surgery"],
            ["17", "Post-obstructive diuresis treatment",        "Replace 50% hourly output with IV 0.9% NaCl if UO >200 mL/hr for >2 hours"],
            ["18", "High-pressure CUR definition",               "Bilateral hydronephrosis + renal impairment → URGENT management"],
            ["19", "TURP gold standard",                         "BPH prostate <100 g; most common late complication = retrograde ejaculation (90%)"],
            ["20", "TURP syndrome",                              "Dilutional hyponatraemia + fluid overload from glycine; now rare with bipolar/saline TURP"],
            ["21", "HoLEP indication",                           "Large prostate >80–100 mL; lower bleeding; steep learning curve"],
            ["22", "CISC role",                                   "Gold standard for neurogenic bladder long-term; every 4–6 hours; lower UTI risk than indwelling catheter"],
            ["23", "Clot retention management",                  "3-way Foley catheter + continuous bladder irrigation (CBI) + bladder washout"],
            ["24", "Stricture management",                       "DVIU for short strictures (<1.5 cm); urethroplasty for long/recurrent strictures"],
            ["25", "Acute prostatitis + AUR",                    "IV antibiotics first; avoid TWOC until infection treated"],
            ["26", "Spontaneous AUR recurrence",                 "56–64% recurrence within 1 week without treatment; 75% ultimately need surgery"],
            ["27", "5-ARIs teratogenicity",                      "Finasteride/dutasteride TERATOGENIC — women must NOT handle crushed tablets"],
            ["28", "Autonomic dysreflexia",                      "SCI (T6+) + AUR = hypertensive emergency; drain bladder immediately; sit patient upright"],
            ["29", "CombAT trial",                               "Dutasteride + tamsulosin superior to monotherapy for large prostates (>30 mL) + high AUR risk"],
            ["30", "Overflow incontinence in CUR",               "Paradoxical/overflow incontinence — intravesical pressure equals urethral resistance → constant dribbling"],
        ],
        col_widths=[0.7*cm, 6.5*cm, W-7.2*cm],
        hdr_color=DARK_BLUE
    )
    E += sp(8)

    E += h2("References")
    E += bul([
        "Bailey & Love's Short Practice of Surgery, 27th Edition",
        "Oxford Handbook of Urology, 4th Edition",
        "EAU Guidelines on Non-neurogenic Male LUTS, 2023",
        "Campbell-Walsh-Wein Urology, 12th Edition",
        "NICE Clinical Guideline NG118 — Lower Urinary Tract Symptoms in Men",
        "Mundy's Textbook of Urology",
        "Tanagho & McAninch Smith's General Urology",
    ])
    return E

# ── Build ─────────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=MARGIN, rightMargin=MARGIN,
    topMargin=MARGIN + 0.65*cm,
    bottomMargin=MARGIN + 0.9*cm,
    title="Acute & Chronic Urinary Retention — Final Year MBBS Exam Notes",
    author="Orris Medical AI",
    subject="AUR, CUR, BPH, Catheterisation, TURP, Urology",
)

story = cover() + content()
doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print(f"PDF created: {OUTPUT}")

Ready ?

Yes! Ready. Let me generate both PDFs now — running them in parallel.
Running Command

mkdir -p /home/daytona/workspace/aur-cur-pdf /home/daytona/workspace/epilepsy-pdf && python3 -c "from reportlab.lib.pagesizes import A4; print('OK')"

Writing File

~/aur-cur-pdf/gen.py


from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, PageBreak, KeepTogether
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY

OUT = "/home/daytona/workspace/aur-cur-pdf/AUR_CUR_Final_Year_Notes.pdf"
PW, PH = A4
M = 1.8*cm
W = PW - 2*M

DARK_BLUE = colors.HexColor("#1A3A5C")
MED_BLUE  = colors.HexColor("#2E6DA4")
LT_BLUE   = colors.HexColor("#D6E8F7")
TEAL      = colors.HexColor("#1A7A6E")
LT_TEAL   = colors.HexColor("#D0EFEB")
RED       = colors.HexColor("#C0392B")
LT_RED    = colors.HexColor("#FADBD8")
ORANGE    = colors.HexColor("#E67E22")
LT_ORANGE = colors.HexColor("#FDEBD0")
PURPLE    = colors.HexColor("#6C3483")
LT_PURPLE = colors.HexColor("#E8DAEF")
GREEN     = colors.HexColor("#1E8449")
LT_GREEN  = colors.HexColor("#D5F5E3")
LT_GREY   = colors.HexColor("#F2F4F7")
MID_GREY  = colors.HexColor("#95A5A6")
WHITE     = colors.white

def S(n, **kw): return ParagraphStyle(n, **kw)
sH1 = S("h1", fontSize=15, textColor=WHITE, leading=20, fontName="Helvetica-Bold")
sH2 = S("h2", fontSize=11.5, textColor=DARK_BLUE, leading=16, fontName="Helvetica-Bold", spaceBefore=8, spaceAfter=2)
sH3 = S("h3", fontSize=10, textColor=TEAL, leading=14, fontName="Helvetica-Bold", spaceBefore=5, spaceAfter=2)
sBo = S("bo", fontSize=9, leading=13, spaceAfter=3, alignment=TA_JUSTIFY)
sBu = S("bu", fontSize=9, leading=13, leftIndent=14, spaceAfter=2)
sTH = S("th", fontSize=8.5, textColor=WHITE, leading=12, alignment=TA_CENTER, fontName="Helvetica-Bold")
sTD = S("td", fontSize=8.5, leading=12, alignment=TA_LEFT)
sWN = S("wn", fontSize=8.5, leading=13, textColor=RED, fontName="Helvetica-Bold")
sTP = S("tp", fontSize=8.5, leading=13, textColor=TEAL, fontName="Helvetica-Bold")
sNT = S("nt", fontSize=8.5, leading=13, textColor=PURPLE, fontName="Helvetica-Bold")
sCA = S("ca", fontSize=7.5, textColor=MID_GREY, alignment=TA_CENTER)
sCT = S("ct", fontSize=32, textColor=WHITE, leading=40, alignment=TA_CENTER, fontName="Helvetica-Bold")
sCS = S("cs", fontSize=12, textColor=colors.HexColor("#AED6F1"), alignment=TA_CENTER)
sNL = S("nl", fontSize=16, textColor=WHITE, alignment=TA_CENTER, fontName="Helvetica-Bold")

def hdr(canvas, doc):
    canvas.saveState()
    canvas.setFillColor(DARK_BLUE)
    canvas.rect(0, PH-0.65*cm, PW, 0.65*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE); canvas.setFont("Helvetica-Bold",7)
    canvas.drawString(M, PH-0.45*cm, "ACUTE & CHRONIC URINARY RETENTION — Final Year MBBS Exam Notes")
    canvas.setFont("Helvetica",7)
    canvas.drawRightString(PW-M, PH-0.45*cm, "Bailey & Love | Campbell Walsh Urology | Oxford Handbook Surgery")
    canvas.setFillColor(LT_GREY)
    canvas.rect(0,0,PW,0.9*cm,fill=1,stroke=0)
    canvas.setFillColor(MID_GREY); canvas.setFont("Helvetica",6.5)
    canvas.drawString(M,0.32*cm,"Refs: Bailey & Love's Surgery • Campbell Walsh Wein Urology • Schwartz's Surgery • Smith & Tanagho's General Urology • Oxford Handbook Surgery")
    canvas.drawRightString(PW-M,0.32*cm,f"Page {doc.page}")
    canvas.restoreState()

def sec(title, col=DARK_BLUE):
    t = Table([[Paragraph(f"<b>{title}</b>", sH1)]], colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),col),("TOPPADDING",(0,0),(-1,-1),9),("BOTTOMPADDING",(0,0),(-1,-1),9),("LEFTPADDING",(0,0),(-1,-1),12)]))
    return [t, Spacer(1,5)]

def h2(txt): return [Paragraph(f"<b>{txt}</b>",sH2), HRFlowable(width="100%",thickness=1.1,color=MED_BLUE,spaceAfter=3)]
def h3(txt): return [Paragraph(f"<b>{txt}</b>",sH3)]
def bo(txt): return [Paragraph(txt,sBo)]
def bu(items): return [Paragraph(f"• {i}",sBu) for i in items]
def sp(h=6): return [Spacer(1,h)]

def box(txt, label, bg, bdr, sty):
    t = Table([[Paragraph(f"<b>{label}:</b> {txt}", sty)]], colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),bg),("BOX",(0,0),(-1,-1),1,bdr),("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),("LEFTPADDING",(0,0),(-1,-1),8),("RIGHTPADDING",(0,0),(-1,-1),8)]))
    return [t, Spacer(1,5)]

def warn(txt): return box(txt,"⚠ EXAM TRAP",LT_RED,RED,sWN)
def tip(txt):  return box(txt,"★ HIGH-YIELD",LT_TEAL,TEAL,sTP)
def note(txt): return box(txt,"◆ CLINICAL PEARL",LT_ORANGE,ORANGE,sNT)

def mkt(headers, rows, cw=None, hc=DARK_BLUE):
    if cw is None: cw=[W/len(headers)]*len(headers)
    data=[[Paragraph(f"<b>{h}</b>",sTH) for h in headers]]+[[Paragraph(str(c),sTD) for c in r] for r in rows]
    t=Table(data,colWidths=cw,repeatRows=1)
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,0),hc),("ROWBACKGROUNDS",(0,1),(-1,-1),[WHITE,LT_GREY]),("GRID",(0,0),(-1,-1),0.4,MID_GREY),("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),("LEFTPADDING",(0,0),(-1,-1),5),("RIGHTPADDING",(0,0),(-1,-1),5),("VALIGN",(0,0),(-1,-1),"TOP")]))
    return [t, Spacer(1,7)]

def kbox(items, title, bg, bdr):
    ps=[Paragraph(f"<b>{title}</b>",S("kt",fontSize=10,textColor=bdr,fontName="Helvetica-Bold",spaceAfter=3))]
    for i in items: ps.append(Paragraph(f"◆  {i}",S("ki",fontSize=9,leading=13)))
    t=Table([[ps]],colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),bg),("BOX",(0,0),(-1,-1),1.2,bdr),("TOPPADDING",(0,0),(-1,-1),8),("BOTTOMPADDING",(0,0),(-1,-1),8),("LEFTPADDING",(0,0),(-1,-1),10),("RIGHTPADDING",(0,0),(-1,-1),10)]))
    return [t, Spacer(1,6)]

# ── COVER ─────────────────────────────────────────────────────────────────────
def cover():
    E=[]
    t=Table([[Paragraph("ACUTE & CHRONIC<br/>URINARY RETENTION",sCT)]],colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),DARK_BLUE),("TOPPADDING",(0,0),(-1,-1),30),("BOTTOMPADDING",(0,0),(-1,-1),10)]))
    E.append(t)
    s=Table([[Paragraph("Final Year MBBS Exam Notes — Surgery & Urology",sCS)]],colWidths=[W])
    s.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),MED_BLUE),("TOPPADDING",(0,0),(-1,-1),10),("BOTTOMPADDING",(0,0),(-1,-1),10)]))
    E.append(s); E.append(Spacer(1,16))
    secs=[(DARK_BLUE,"1","Definitions — AUR vs CUR"),(MED_BLUE,"2","Aetiology & Risk Factors"),(TEAL,"3","Pathophysiology"),(colors.HexColor("#E67E22"),"4","Clinical Features & Examination"),(colors.HexColor("#1E8449"),"5","Investigations"),(colors.HexColor("#922B21"),"6","Management — Emergency Algorithm + Pharmacology + Non-Pharmacological"),(colors.HexColor("#6C3483"),"7","Complications (AUR, CUR, Post-TURP)"),(colors.HexColor("#1A3A5C"),"8","High-Yield Exam Summary (30 Points)")]
    for col,num,name in secs:
        r=Table([[Paragraph(f"<b>{num}</b>",sNL),Paragraph(f"<b>{name}</b>",S("sn",fontSize=10.5,textColor=WHITE,leading=15))]],colWidths=[1.1*cm,W-1.1*cm-0.1*cm])
        r.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),col),("TOPPADDING",(0,0),(-1,-1),8),("BOTTOMPADDING",(0,0),(-1,-1),8),("LEFTPADDING",(0,0),(-1,-1),8),("VALIGN",(0,0),(-1,-1),"MIDDLE")]))
        E.append(r); E.append(Spacer(1,4))
    E.append(Spacer(1,14))
    ref=Table([[Paragraph("References: Bailey & Love's Principles of Surgery • Campbell Walsh Wein Urology • Schwartz's Principles of Surgery • Smith & Tanagho's General Urology • Oxford Handbook of Surgery • EAU Guidelines on LUTS/BPH",sCA)]],colWidths=[W])
    ref.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),LT_GREY),("BOX",(0,0),(-1,-1),0.5,MID_GREY),("TOPPADDING",(0,0),(-1,-1),7),("BOTTOMPADDING",(0,0),(-1,-1),7),("LEFTPADDING",(0,0),(-1,-1),8)]))
    E.append(ref); E.append(PageBreak())
    return E

def content():
    E=[]
    # S1
    E+=sec("1. Definitions — AUR vs CUR")
    E+=kbox(["AUR = Sudden, PAINFUL inability to void voluntarily despite a full bladder. A urological EMERGENCY.",
             "CUR = Painless, persistent incomplete bladder emptying. Post-void residual (PVR) >300 mL. May present with overflow incontinence.",
             "Key distinction: AUR is PAINFUL; CUR is usually PAINLESS — a classic exam question."],"DEFINITIONS",LT_BLUE,DARK_BLUE)
    E+=mkt(["Feature","AUR","CUR"],
           [["Onset","Sudden","Insidious"],["Pain","Severe suprapubic (hallmark)","Usually PAINLESS"],["Bladder","Distended, tender, palpable","Large, non-tender, palpable"],["Voiding","Complete inability","Incomplete — residual urine >300 mL"],["PVR","Total (no voiding at all)","Persistently >300 mL"],["Overflow incontinence","May have small dribbles","Constant dribbling — 'water over a dam'"],["Renal complication","Post-renal AKI (if untreated)","CKD, bilateral hydronephrosis (high-pressure)"],["Urgency of treatment","EMERGENCY — catheterise now","Urgent (high-pressure) or elective (low-pressure)"]],
           cw=[3.5*cm,5.5*cm,W-9*cm])
    E+=sp()
    # S2
    E+=sec("2. Aetiology & Risk Factors",col=MED_BLUE)
    E+=h2("AUR — Obstructive Causes (Most Common)")
    E+=mkt(["Cause","Details"],
           [["BPH (Benign Prostatic Hyperplasia)","MOST COMMON cause in men >50. Affects 10% of men in their 70s, 33% of men in their 80s. Prostate enlarges → compresses urethra → BOO → AUR"],["Urethral stricture","Post-gonorrhoeal infection, instrumentation, trauma, lichen sclerosus. Resistance felt near meatus (distal strictures common)"],["Prostatic carcinoma","May obstruct urethra directly or by involvement of bladder neck"],["Bladder neck obstruction","Primary (idiopathic) or secondary (post-surgery, inflammation)"],["Bladder stone at neck","Stone impacts at bladder neck or urethra → complete obstruction"],["Clot retention","Haematuria → clot formation → urethral blockage. Requires 3-way catheter + CBI"],["Phimosis / Paraphimosis / Meatal stenosis","Obstructs external urethral meatus"],["Pelvic organ prolapse (women)","Cystocele, uterine prolapse → kinks or compresses urethra"],["Constipation / Faecal impaction","Extrinsic compression of urethra — very common in hospitalised elderly"],["Pelvic mass","Uterine fibroids, ovarian cyst, gravid uterus, pelvic haematoma"]],
           cw=[4.5*cm,W-4.5*cm])
    E+=h2("AUR — Neurogenic Causes")
    E+=mkt(["Cause","Details"],
           [["Cauda equina syndrome","SURGICAL EMERGENCY — AUR + saddle anaesthesia (S3-S5) + bilateral leg weakness/numbness + absent anal tone. MRI spine urgently. Neurosurgical referral within hours"],["Spinal cord injury / acute cord compression","AUR from detrusor areflexia. Check saddle sensation + anal tone"],["Multiple sclerosis","Both detrusor overactivity and underactivity possible depending on lesion level"],["Parkinson's disease","Detrusor overactivity + impaired sphincter coordination"],["Diabetic autonomic neuropathy","Sensory neuropathy → bladder overdistension → detrusor decompensation → CUR → AUR"],["Post-operative","Common after spinal/epidural anaesthesia, anorectal surgery (anal pain → reflex sphincter spasm), hernia repair. Usually resolves within 24-48h"],["Fowler syndrome","Young women: large acontractile bladder + no neurological cause. Urethral sphincter overactivity. Often presents with CUR/AUR without prior LUTS"]],
           cw=[4.5*cm,W-4.5*cm])
    E+=h2("AUR — Drug-Induced (Pharmacological Causes)")
    E+=mkt(["Drug Class","Examples","Mechanism"],
           [["Anticholinergics","Oxybutynin, TCAs (amitriptyline, imipramine), antihistamines (chlorphenamine), antipsychotics (clozapine, haloperidol), hyoscine","Block muscarinic receptors → reduce detrusor contractility"],["Opioids / Narcotics","Morphine, codeine, tramadol","Increase urethral tone + decrease detrusor contractility + reduce bladder sensation"],["Alpha-adrenergic agonists","Pseudoephedrine, phenylephrine (decongestants), midodrine","Increase smooth muscle tone of bladder neck and urethra"],["NSAIDs","Ibuprofen, diclofenac","Decrease prostaglandin-mediated detrusor contractions"],["Calcium channel blockers","Nifedipine, amlodipine","Reduce smooth muscle contractility of detrusor"],["Alcohol (acute)","—","Increases urine production + anticholinergic-like effects on bladder"]],
           cw=[3.5*cm,4.5*cm,W-8*cm])
    E+=warn("Drug history is ESSENTIAL in every patient presenting with AUR. Stopping/reducing the offending drug may resolve the retention without surgical intervention.")
    E+=h2("Two Types of AUR — Important Prognostic Distinction")
    E+=mkt(["Type","Definition","Surgery Rate","Recurrence"],
           [["Spontaneous AUR","Natural history of BPH — no precipitating event","~75% ultimately need surgery","56-64% have recurrent AUR within 1 week if untreated"],["Precipitated AUR","Triggered by identifiable event: anaesthesia, drugs, instrumentation, infection, constipation","Only ~26% need surgery","Lower — treat the trigger → voiding often resumes"]],
           cw=[3*cm,6.5*cm,3*cm,W-12.5*cm])
    E+=h2("Risk Factors for AUR in Men (Exam)")
    E+=mkt(["Risk Factor","Threshold / Detail"],
           [["Age",">70 years"],["Prostate volume",">30 mL (by transrectal USS or MRI)"],["Serum PSA",">1.4 ng/mL"],["Peak urinary flow rate","<12 mL/sec (uroflowmetry)"],["IPSS score",">7 (moderate-severe LUTS)"],["Previous episode of AUR","Recurrence risk 56-64% within 1 week of first episode"]],
           cw=[5*cm,W-5*cm])
    E+=sp()
    # S3
    E+=sec("3. Pathophysiology",col=TEAL)
    E+=h2("Normal Micturition")
    E+=bu(["Detrusor contracts + external urethral sphincter relaxes — coordinated by pontine micturition centre (PMC)","Cortex provides voluntary inhibition of voiding","Parasympathetic (S2-S4): detrusor contraction (muscarinic M3 receptors)","Sympathetic (T10-L2): bladder neck/urethra contraction (alpha-1 receptors); detrusor relaxation (beta-3 receptors)"])
    E+=h2("AUR Mechanism")
    E+=bu(["Bladder outlet obstruction (BOO) exceeds detrusor contractility, OR detrusor contractility is lost completely","Bladder fills beyond functional capacity → intravesical pressure rises","Back-pressure transmitted to ureters → hydroureteronephrosis → post-renal AKI","Prolonged over-distension damages detrusor muscle (myogenic damage)"])
    E+=h2("CUR Mechanism & High vs Low Pressure")
    E+=bu(["Chronic under-emptying → bladder distension → detrusor hypertrophy initially, then fibrosis → acontractile bladder","Overflow incontinence: intravesical pressure eventually equals urethral resistance → constant dribbling"])
    E+=mkt(["Type","Features","Upper Tract","Management Urgency"],
           [["High-pressure CUR","High intravesical pressure transmitted to upper tract","Bilateral hydroureteronephrosis + renal impairment (elevated creatinine)","URGENT — catheterise promptly; monitor renal recovery"],["Low-pressure CUR","Large, highly compliant bladder; pressure not transmitted","No upper tract dilatation; normal renal function","Less urgent — investigate and manage electively"]],
           cw=[3*cm,5*cm,4.5*cm,W-12.5*cm])
    E+=sp()
    # S4
    E+=sec("4. Clinical Features & Examination",col=ORANGE)
    E+=h2("AUR — Clinical Presentation")
    E+=bu(["Sudden COMPLETE inability to void (this distinguishes AUR from oliguria/anuria — patient tries to void but cannot)","Severe lower abdominal/suprapubic pain and distress","Intense urge to void","Suprapubic swelling — tense, palpable, tender bladder","Typical bladder volume at presentation: >300–500 mL","Tachycardia, hypertension, diaphoresis (pain response)","May have dribbling of small amounts (overflow) — does NOT mean bladder is emptying","Haematuria if clot retention"])
    E+=h2("CUR — Clinical Presentation")
    E+=bu(["Often asymptomatic or slow onset of symptoms","Voiding LUTS: hesitancy, poor stream, straining to void, terminal dribbling, sense of incomplete emptying","Storage LUTS: frequency, nocturia, urgency (from small functional capacity)","Overflow incontinence: constant or positional dribbling (paradoxical incontinence)","Recurrent UTIs (stagnant urine — culture medium for bacteria)","Painless distended palpable bladder","Signs of renal failure (high-pressure CUR): hypertension, peripheral oedema, pallor, uraemic symptoms (nausea, confusion, pruritus)"])
    E+=h2("Examination — Key Findings")
    E+=mkt(["Finding","Significance"],
           [["Suprapubic dullness to percussion","Full bladder — dull over suprapubic area (contrast: tympanic if bowel)"],["Palpable suprapubic mass","Distended bladder — may reach umbilicus in severe cases"],["DRE — smooth enlarged prostate","BPH (benign, rubbery, smooth, symmetrical)"],["DRE — hard/irregular prostate","Prostatic carcinoma — refer for biopsy"],["DRE — tender, boggy prostate","Acute prostatitis — do NOT attempt prostatic massage; antibiotics first"],["Rectal mass / faecal impaction","Extrinsic compression causing retention"],["Saddle anaesthesia (S3-S5 dermatome) + absent anal tone","Cauda equina syndrome — NEUROSURGICAL EMERGENCY"],["Phimosis / paraphimosis","Obstructive cause at meatus"],["Neurological examination","MS, Parkinson's, diabetic neuropathy as cause"]],
           cw=[5*cm,W-5*cm])
    E+=warn("Always check saddle sensation and anal tone in any patient with AUR — missing cauda equina syndrome is a medico-legal emergency.")
    E+=sp()
    # S5
    E+=sec("5. Investigations",col=GREEN)
    E+=h2("Bedside")
    E+=bu(["Bladder ultrasound scanner — confirms retention, measures volume (>150 mL significant; >300 mL = retention). Quick, non-invasive, first-line","Urine dipstick — infection (nitrites/leucocytes), haematuria","MSU for culture and sensitivity — guide antibiotic choice"])
    E+=h2("Blood Tests")
    E+=mkt(["Test","Why / What to Look For"],
           [["U&E + Creatinine","Renal function — post-renal AKI in AUR; CKD in high-pressure CUR; guides fluid management and catheter drainage rate"],["FBC","Infection (raised WCC), anaemia (CKD, malignancy)"],["PSA (Prostate Specific Antigen)","CHECK BEFORE CATHETERISATION — urethral catheterisation elevates PSA for 4-6 weeks (falsely high). If catheter already in situ — wait 4-6 weeks before measuring PSA"],["Clotting screen (PT/APTT/platelets)","If haematuria/clot retention — guide management"],["Blood glucose","Diabetic autonomic neuropathy as cause of AUR/CUR"],["Blood cultures","If pyrexia — urosepsis may accompany urinary retention"]],
           cw=[4*cm,W-4*cm])
    E+=warn("PSA must be measured BEFORE inserting urethral catheter. Catheterisation falsely elevates PSA for up to 6 weeks — this is a VERY commonly tested exam point.")
    E+=h2("Imaging")
    E+=mkt(["Investigation","Indication / Findings"],
           [["Bladder scanner (portable USS)","First-line — confirm retention, measure volume, check PVR after TWOC"],["USS renal tract (kidneys, ureters, bladder)","Hydronephrosis (high-pressure CUR), bladder wall thickness, prostate volume, PVR, bladder diverticula, stones"],["KUB X-ray","Calculi, constipation/faecal loading (extrinsic compression)"],["CT KUB (non-contrast)","Calculi, pelvic masses; more sensitive than plain X-ray"],["CT abdomen/pelvis (contrast)","Pelvic malignancy, advanced prostate cancer staging"],["MRI spine","If cauda equina syndrome suspected — urgent (within 4 hours)"],["MRI pelvis","Prostate cancer staging, pelvic mass characterisation"]],
           cw=[4.5*cm,W-4.5*cm])
    E+=h2("Urodynamic Studies (for CUR/Neurogenic)")
    E+=mkt(["Test","Normal / Significance"],
           [["Uroflowmetry (free flow rate)","Peak flow <10 mL/sec = significant BOO or poor detrusor; <15 mL/sec = borderline"],["Post-void residual (PVR)","<50 mL = normal; 50-100 mL = borderline; >100 mL = significant; >300 mL = CUR"],["Pressure-flow studies (PFS)","Gold standard to distinguish BOO (high pressure, low flow) from detrusor underactivity (low pressure, low flow)"],["Flexible cystoscopy","Urethral stricture (visualise), bladder tumour, stone, mucosal assessment"],["IPSS questionnaire","International Prostate Symptom Score: 0-7 mild, 8-19 moderate, ≥20 severe"]],
           cw=[4.5*cm,W-4.5*cm])
    E+=sp()
    # S6
    E+=sec("6. Management",col=RED)
    E+=h2("AUR — Emergency Management Algorithm")
    E+=mkt(["Step","Phase","Action","Key Points"],
           [["1","0–30 min\nConfirm & Stabilise","• Confirm AUR: history + examination + bladder scanner (>300 mL)\n• IV access; continuous monitoring\n• Bloods: U&E, Cr, FBC, PSA, clotting, blood cultures if septic\n• Analgesia: IV morphine 0.1 mg/kg + IV paracetamol 1 g\n• IV fluids if haemodynamically unstable","Check PSA BEFORE catheter!\nAvoid NSAIDs if renal impairment (AKI common in AUR)"],
            ["2","Urethral\nCatheterisation\n(FIRST-LINE)","• Standard: 14–16Fr Foley catheter (most patients)\n• BPH: 16–18Fr COUDÉ (curved-tip) catheter — tip held at 12 o'clock position\n• Urethral stricture: 12–14Fr straight catheter; gentle insertion\n• Insert with sterile technique, adequate LA gel (instillagel)\n• Record: time inserted, volume drained, colour of urine","COUDÉ tip at 12 o'clock for BPH\nUse LARGER catheter for BPH (18-20Fr) — less flexible, pushes into bladder rather than curling in prostatic urethra\nUse SMALLER catheter (12-14Fr) for stricture"],
            ["3","Urethral catheter\nFAILS","• DO NOT FORCE — risk of false passage, urethral perforation\n• Call urology urgently\n• Options:\n  (a) Coudé catheter with lidocaine gel under guidance\n  (b) Flexible cystoscopy + hydrophilic guidewire + urethral dilatation + Council-tip catheter\n  (c) Suprapubic catheter (SPC) — 2 fingerbreadths above pubic symphysis","SPC contraindications:\n• Previous lower midline laparotomy scar\n• Bladder tumour (seeding risk)\n• Unconfirmed bladder fullness (USS first)\n• Bleeding diathesis\nAlways use USS guidance for SPC"],
            ["4","Post-catheterisation\nMonitoring","• Monitor hourly urine output for 2–4 hours\n• POST-OBSTRUCTIVE DIURESIS: if UO >200 mL/hr for >2 consecutive hours\n  → Replace 50% of hourly output with IV 0.9% NaCl\n  → Monitor electrolytes (Na, K) every 4–6 hours\n• Drain bladder completely (no evidence for staged 500 mL drainage)\n• Treat haematuria: if clot retention → 3-way Foley + continuous bladder irrigation (CBI) — saline by gravity only (not pressure)","Post-obstructive diuresis risk:\n• Hypovolaemia\n• Hyponatraemia / hypokalaemia\n• Hypomagnesaemia\nDo NOT restrict replacement — monitor and replace proportionally"],
            ["5","Start alpha-blocker\n(24–48 hrs pre-TWOC)","• Tamsulosin 400 mcg OD (most evidence, most selective)\n• OR Alfuzosin 10 mg OD\n• Start 24–48 hours before planned TWOC\n• Mechanism: relax smooth muscle of prostate, bladder neck, urethra → reduce outlet resistance","Alpha-blockers improve TWOC success rate from ~50% → ~60–70%\nEffect within hours to days"],
            ["6","TWOC\n(Trial Without Catheter)\n@48–72 hours","• Remove catheter in MORNING (better daytime voiding)\n• Patient attempts to void naturally\n• Within 15 minutes: bladder scan (measure PVR)\n• SUCCESS: voided volume >150 mL AND PVR <200 mL\n• FAILURE: unable to void OR PVR >200 mL → re-catheterise","TWOC success rate:\n~60–70% with alpha-blocker\n~50% without alpha-blocker\n~30% if second TWOC after first failure"],
            ["7","After failed TWOC","• Option A: Re-catheterise + 2nd TWOC in 3–5 days (success ~30%)\n• Option B: Long-term catheter (urethral or SPC) + definitive treatment planning\n• Option C (preferred for neurogenic): Clean Intermittent Self-Catheterisation (CISC) every 4–6 hours\n• Refer urology for definitive surgical management","Spontaneous AUR: 75% ultimately need surgery\nPrecipitated AUR: 26% need surgery\nAlways plan definitive treatment after first episode of spontaneous AUR"]],
           cw=[0.8*cm,2.5*cm,8.5*cm,W-11.8*cm])
    E+=warn("Never use a urethral catheter in suspected urethral trauma (straddle injury, pelvic fracture with blood at urethral meatus, perineal haematoma, inability to void post-trauma) → suprapubic catheter or urology/urosurgery immediately.")
    E+=sp(4)
    E+=h2("Definitive Surgical Management — Options")
    E+=mkt(["Procedure","Indication","Key Points / Complications"],
           [["TURP (Trans-Urethral Resection of Prostate)","BPH — GOLD STANDARD; prostate <80–100 g","Resect prostatic tissue endoscopically; retrograde ejaculation 90% (most common late complication); TURP syndrome (dilutional hyponatraemia from glycine irrigation — now rare with bipolar/saline TURP); incontinence <1%; erectile dysfunction rare"],["HoLEP (Holmium Laser Enucleation)","Large prostate >80–100 g","Lower bleeding risk than TURP; faster recovery; steep learning curve; morcellator needed"],["Open prostatectomy (Millin's retropubic / transvesical)","Very large prostate >100 g","More invasive; higher morbidity; lower risk of retrograde ejaculation than TURP"],["TUIP (Trans-Urethral Incision of Prostate)","Small prostate <30 g, no median lobe","Incision only; better preservation of antegrade ejaculation than TURP"],["UroLift (Prostatic Urethral Lift)","Small-moderate BPH, no median lobe, sexual function priority","Mechanical retraction; preserves sexual function completely; day case; not for large prostates"],["DVIU (Direct Vision Internal Urethrotomy)","Short urethral stricture <1–1.5 cm","High recurrence rate; may need repeating or urethroplasty"],["Urethroplasty","Long/complex/recurrent urethral stricture","Gold standard for definitive stricture repair; anastomotic or buccal mucosal graft augmentation"],["Sacral Nerve Modulation (SNM/Interstim)","Detrusor underactivity, neurogenic bladder, OAB refractory","Implanted electrode stimulates S3 root; reversible"]],
           cw=[3.5*cm,3.5*cm,W-7*cm])
    E+=sp(4)
    E+=h2("Pharmacological Management — Full Drug Table")
    E+=mkt(["Drug/Class","MOA","Dose","Side Effects","Notes"],
           [["Alpha-blockers\n(Tamsulosin — first-line)","Block α1A/α1D receptors → relax smooth muscle of prostate, bladder neck, urethra → reduce outlet resistance","Tamsulosin 400 mcg OD\nAlfuzosin 10 mg OD\nDoxazosin 4–8 mg OD\nSilodosin 8 mg OD","Orthostatic hypotension (less with tamsulosin due to selectivity), retrograde ejaculation, dizziness, nasal congestion, asthenia","Onset: days to weeks (use 48h before TWOC)\nTamsulosin → IFIS (Intraoperative Floppy Iris Syndrome) — warn ophthalmologist before cataract surgery"],["5-Alpha-Reductase Inhibitors\n(Finasteride/Dutasteride)","Block conversion of testosterone → DHT → reduce prostate volume by 20–30%","Finasteride 5 mg OD\nDutasteride 0.5 mg OD","Erectile dysfunction, decreased libido, ejaculatory dysfunction, gynaecomastia, depression","Onset: 3–6 months (NOT useful acutely for AUR)\nReduce AUR risk 50%, surgery risk 55% long-term\nReduce PSA by ~50% — DOUBLE PSA when interpreting result\nTERATOGENIC (Pregnancy Category X) — women must NOT handle crushed tablets"],["Combination therapy\n(Alpha-blocker + 5-ARI)","Both above","As above for each","Additive side effects","CombAT trial: dutasteride + tamsulosin superior to monotherapy\nUse if prostate >30 mL + elevated PSA + high AUR risk"],["PDE-5 Inhibitors\n(Tadalafil)","Inhibit PDE5 → ↑cGMP → smooth muscle relaxation in prostate and bladder neck","Tadalafil 5 mg OD","Headache, flushing, hypotension (with nitrates — absolute CI), myalgia","Licensed for LUTS/BPH ± erectile dysfunction\nUseful if patient has concurrent ED"],["Antibiotics\n(Acute prostatitis / UTI)","Target causative organisms — usually Gram-negative rods (E. coli) in community","Ciprofloxacin 500 mg BD oral (mild)\nIV Ceftriaxone 1–2 g OD (severe/septic)\nCourse: 2–4 weeks for prostatitis","Per specific drug class","Culture urine + blood before starting\nAvoid urethral catheterisation in acute prostatitis if possible (suprapubic preferred if retention)"],["Analgesia for AUR","Multimodal","IV Morphine 0.1 mg/kg\nIV Paracetamol 1 g QDS\nOral analgesics once settled","Respiratory depression (opioids), hepatotoxicity (paracetamol overdose)","AVOID NSAIDs if renal impairment (AKI in AUR) or elderly with borderline renal function"]],
           cw=[3*cm,3.5*cm,3*cm,3.5*cm,W-13*cm])
    E+=sp(4)
    E+=h2("Non-Pharmacological Management")
    E+=h3("Conservative Measures")
    E+=bu(["Review and STOP offending medications (anticholinergics, opioids — taper if appropriate, replace with alternatives)",
           "Treat constipation: high-fibre diet, adequate hydration, laxatives (lactulose, senna) — removes extrinsic pressure on urethra",
           "Fluid management: avoid excessive fluid loading (worsens distension); spread fluid intake through the day",
           "Warm bath/shower or warm perineal compress — may relax external urethral sphincter",
           "Running tap water / sound of water (conditioned voiding reflex — may help psychogenic/post-operative retention)",
           "Upright posture for voiding (men should stand; women — sit forward with feet elevated)",
           "Privacy: post-operative retention often resolves with adequate privacy and upright positioning"])
    E+=h3("Catheterisation Options")
    E+=mkt(["Type","Indication","Advantages","Disadvantages"],
           [["Urethral Foley catheter","First-line for AUR; short-term","Quick, familiar, widely available","UTI risk with long-term use; discomfort; urethral trauma risk"],["Coudé (angled-tip) catheter","BPH — negotiates angulated prostatic urethra","Better success in BPH than standard Foley","Same risks; must keep tip at 12 o'clock"],["Suprapubic catheter (SPC)","Failed urethral catheterisation; long-term bladder drainage","Better patient comfort long-term; lower UTI rate; preserves urethra","Procedural risks: bowel injury, haematoma, false tract; requires full bladder"],["Clean Intermittent Self-Catheterisation (CISC)","Neurogenic bladder; chronic retention; non-surgical patients; post-TURP","GOLD STANDARD for long-term management of neurogenic bladder; lowest UTI rate; maintains bladder capacity and sensation; avoids indwelling catheter","Requires patient education, manual dexterity, motivation; every 4–6 hours"]],
           cw=[3*cm,4*cm,4*cm,W-11*cm])
    E+=tip("CISC (Clean Intermittent Self-Catheterisation) is the gold standard for long-term management of neurogenic bladder — lower UTI rate than indwelling catheter and maintains bladder capacity. Patient education is key.")
    E+=h3("CUR — Specific Management")
    E+=bu(["Assess type: HIGH-PRESSURE (bilateral hydronephrosis + raised creatinine) vs LOW-PRESSURE (large compliant bladder, normal renal function)",
           "HIGH-PRESSURE CUR: Urgent catheterisation (urethral or SPC). Drain more slowly initially (500 mL/hour) to prevent rapid decompression haematuria. Monitor renal function — may recover significantly after decompression.",
           "LOW-PRESSURE CUR: Elective investigation. CISC preferred if surgical risk high. Treat underlying cause.",
           "Monitor post-obstructive diuresis closely — may be more marked and prolonged than in AUR",
           "Treat underlying cause: TURP/HoLEP for BPH, urethroplasty for stricture, CISC for neurogenic, hormonal/radiation treatment for prostate carcinoma"])
    E+=sp()
    # S7
    E+=sec("7. Complications",col=PURPLE)
    E+=h2("AUR Complications")
    E+=mkt(["Complication","Details"],
           [["Post-renal Acute Kidney Injury (AKI)","Raised creatinine/urea from back-pressure to kidneys. Resolves with decompression in most cases — monitor renal function post-catheterisation"],["Post-obstructive diuresis","Polyuria after decompression (UO >200 mL/hr). Risk: hypovolaemia, electrolyte disturbance (hyponatraemia, hypokalaemia, hypomagnesaemia). Replace 50% hourly output with 0.9% NaCl"],["Decompression haematuria","Bleeding from decompressed bladder mucosa and venous engorgement — usually self-limiting. If severe → CBI"],["UTI / Urosepsis","Stagnant urine + instrumentation → infection. Most serious: Gram-negative septicaemia. Blood + urine cultures; IV antibiotics"],["Bladder rupture","Extremely rare — spontaneous in massively over-distended bladder. CT cystogram to diagnose"],["Autonomic dysreflexia","In spinal cord injury (above T6) — AUR triggers massive sympathetic response: severe hypertension, bradycardia, headache, sweating, flushing. EMERGENCY → drain bladder immediately, sit patient upright, antihypertensives (nifedipine SL or GTN spray)"]],
           cw=[4*cm,W-4*cm])
    E+=h2("CUR Complications")
    E+=mkt(["Complication","Details"],
           [["Recurrent UTIs","Stagnant urine = culture medium. Treat each episode; CISC reduces risk"],["Bladder stones","Infection stones (struvite/magnesium ammonium phosphate) from urease-producing organisms (Proteus, Klebsiella). Also calcium oxalate. Require cystolitholapaxy"],["Vesicoureteric reflux → bilateral hydroureteronephrosis","Chronically raised intravesical pressure overcomes VUJ → upper tract dilatation → CKD → ESRD"],["Bladder diverticula","Saccular outpouchings through bladder wall at points of weakness — cause incomplete emptying, stasis, infection, stone"],["Detrusor decompensation","Irreversible atonic acontractile bladder from prolonged over-distension — patient may become catheter-dependent permanently"],["Overflow incontinence","Constant dribbling — socially debilitating; responds to treatment of underlying retention"]],
           cw=[4*cm,W-4*cm])
    E+=h2("Post-TURP Complications (High-Yield)")
    E+=mkt(["Timing","Complication","Notes"],
           [["Immediate","Primary haemorrhage","Requires return to theatre for haemostasis; clot retention → CBI"],["Immediate","Clot retention","3-way catheter + CBI; avoid high-pressure irrigation (bladder rupture risk)"],["Early (0–30 days)","UTI","Commonest early complication; prophylactic antibiotics at induction"],["Early","DVT / PE","Standard VTE prophylaxis"],["Late","Retrograde ejaculation","MOST COMMON late complication: ~90% of patients. Retrograde flow of semen into bladder during orgasm. Fertility implications — warn before surgery"],["Late","Urethral / bladder neck stricture","10–15% at 5–10 years; present with recurrent LUTS; treat with DVIU or dilatation"],["Late","Urinary incontinence","<1%; stress incontinence if external sphincter damaged"],["Late","Erectile dysfunction","<5%; rare with standard TURP; higher with open prostatectomy"],["Late","Re-operation","10–15% require second procedure at 10 years"],["Specific","TURP syndrome","Dilutional hyponatraemia + fluid overload from absorption of hypotonic glycine irrigation fluid. Presents: confusion, visual disturbance, bradycardia, seizures, coma. Treat: restrict fluids, IV hypertonic saline if severe (Na <120 mEq/L), furosemide. Now rare with bipolar TURP (saline irrigation) or laser procedures"]],
           cw=[2.5*cm,4*cm,W-6.5*cm])
    E+=warn("TURP syndrome = dilutional hyponatraemia from glycine irrigation absorption. Presents with confusion, visual disturbance, bradycardia. Now rare with bipolar/saline TURP. Treat with hypertonic saline if Na <120 mEq/L.")
    E+=sp()
    # S8
    E+=sec("8. High-Yield Exam Summary",col=DARK_BLUE)
    E+=mkt(["#","Key Exam Point","Answer / Fact"],
           [["1","AUR vs CUR — key difference","AUR = PAINFUL; CUR = usually PAINLESS"],["2","Most common cause AUR in men","BPH (10% men in 70s, 33% in 80s)"],["3","Most common cause AUR in women","Neurogenic (Fowler syndrome in young; MS, DM neuropathy in others)"],["4","Drug causes of AUR","Anticholinergics, opioids, alpha-agonists, TCAs, antihistamines, antipsychotics"],["5","AUR + saddle anaesthesia + bilateral leg weakness","CAUDA EQUINA SYNDROME — neurosurgical emergency — MRI spine urgently"],["6","First-line treatment AUR","Urethral catheterisation"],["7","Catheter for BPH","Coudé 16-18Fr — tip at 12 o'clock position"],["8","PSA and catheterisation","Check PSA BEFORE catheterisation — catheter elevates PSA for 4-6 weeks"],["9","Spontaneous vs Precipitated AUR surgery rates","Spontaneous: 75% need surgery; Precipitated: only 26%"],["10","TWOC pre-treatment","Tamsulosin 400 mcg OD starting 24-48h before TWOC"],["11","TWOC success criteria","Void >150 mL + PVR <200 mL"],["12","TWOC success rate","~60-70% with alpha-blocker; ~50% without"],["13","Post-obstructive diuresis management","Replace 50% hourly urine output with IV 0.9% NaCl if UO >200 mL/hr"],["14","5-ARIs and PSA","Reduce PSA by ~50% — always DOUBLE PSA value when interpreting if on finasteride/dutasteride"],["15","5-ARIs onset","3-6 months — NOT useful acutely for AUR episode"],["16","Tamsulosin and eye surgery","IFIS (Intraoperative Floppy Iris Syndrome) — warn ophthalmologist before cataract surgery"],["17","High-pressure CUR","Bilateral hydronephrosis + renal impairment → urgent catheterisation"],["18","TURP gold standard for","BPH (prostate <100 g)"],["19","Most common late complication TURP","Retrograde ejaculation (~90%)"],["20","TURP syndrome treatment","Hypertonic saline IV if Na <120; furosemide; restrict fluids"],["21","HoLEP indication","Large prostate >80-100 g"],["22","CISC — best for","Neurogenic bladder / non-surgical CUR — gold standard long-term"],["23","Clot retention management","3-way Foley catheter + continuous bladder irrigation (CBI) — gravity only"],["24","DVIU vs urethroplasty","DVIU = short stricture <1.5 cm; urethroplasty = long/complex/recurrent"],["25","Acute prostatitis + AUR","IV antibiotics (ciprofloxacin/ceftriaxone) FIRST; avoid urethral catheter if possible (use SPC)"],["26","Recurrence after 1st AUR without treatment","56-64% within 1 week"],["27","5-ARI teratogenicity","Women must NOT handle crushed finasteride/dutasteride tablets"],["28","Autonomic dysreflexia","SCI + AUR → hypertensive emergency → drain bladder immediately + sit upright + sublingual nifedipine"],["29","CombAT trial","Dutasteride + tamsulosin superior to monotherapy for large prostates (AUR prevention + symptom relief)"],["30","Overflow incontinence in CUR","Paradoxical incontinence — intravesical pressure = urethral resistance → constant dribbling"]],
           cw=[0.7*cm,6.5*cm,W-7.2*cm])
    return E

doc=SimpleDocTemplate(OUT,pagesize=A4,leftMargin=M,rightMargin=M,topMargin=M+0.65*cm,bottomMargin=M+0.9*cm,title="AUR & CUR — Final Year MBBS Exam Notes")
doc.build(cover()+content(), onFirstPage=hdr, onLaterPages=hdr)
print(f"DONE: {OUT}")
Running Command

cd /home/daytona/workspace/aur-cur-pdf && python3 gen.py 2>&1

AUR/CUR PDF done. Now generating the expanded Epilepsy v2.
Writing File

~/epilepsy-pdf/gen_v2.py


from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, HRFlowable, PageBreak
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY

OUT = "/home/daytona/workspace/epilepsy-pdf/Epilepsy_Final_Year_Notes_v2.pdf"
PW, PH = A4
M = 1.8*cm
W = PW - 2*M

DARK_BLUE=colors.HexColor("#1A3A5C"); MED_BLUE=colors.HexColor("#2E6DA4"); LT_BLUE=colors.HexColor("#D6E8F7")
TEAL=colors.HexColor("#1A7A6E"); LT_TEAL=colors.HexColor("#D0EFEB"); RED=colors.HexColor("#C0392B"); LT_RED=colors.HexColor("#FADBD8")
ORANGE=colors.HexColor("#E67E22"); LT_ORANGE=colors.HexColor("#FDEBD0"); PURPLE=colors.HexColor("#6C3483"); LT_PURPLE=colors.HexColor("#E8DAEF")
GREEN=colors.HexColor("#1E8449"); LT_GREEN=colors.HexColor("#D5F5E3"); LT_GREY=colors.HexColor("#F2F4F7"); MID_GREY=colors.HexColor("#95A5A6")
WHITE=colors.white; GOLD=colors.HexColor("#D4AC0D"); LT_GOLD=colors.HexColor("#FEF9E7")

def S(n,**kw): return ParagraphStyle(n,**kw)
sH1=S("h1",fontSize=15,textColor=WHITE,leading=20,fontName="Helvetica-Bold")
sH2=S("h2",fontSize=11.5,textColor=DARK_BLUE,leading=16,fontName="Helvetica-Bold",spaceBefore=8,spaceAfter=2)
sH3=S("h3",fontSize=10,textColor=TEAL,leading=14,fontName="Helvetica-Bold",spaceBefore=5,spaceAfter=2)
sBo=S("bo",fontSize=9,leading=13,spaceAfter=3,alignment=TA_JUSTIFY)
sBu=S("bu",fontSize=9,leading=13,leftIndent=14,spaceAfter=2)
sTH=S("th",fontSize=8.5,textColor=WHITE,leading=12,alignment=TA_CENTER,fontName="Helvetica-Bold")
sTD=S("td",fontSize=8.5,leading=12,alignment=TA_LEFT)
sWN=S("wn",fontSize=8.5,leading=13,textColor=RED,fontName="Helvetica-Bold")
sTP=S("tp",fontSize=8.5,leading=13,textColor=TEAL,fontName="Helvetica-Bold")
sNT=S("nt",fontSize=8.5,leading=13,textColor=PURPLE,fontName="Helvetica-Bold")
sON=S("on",fontSize=8.5,leading=13,textColor=ORANGE,fontName="Helvetica-Bold")
sCA=S("ca",fontSize=7.5,textColor=MID_GREY,alignment=TA_CENTER)
sCT=S("ct",fontSize=28,textColor=WHITE,leading=36,alignment=TA_CENTER,fontName="Helvetica-Bold")
sCS=S("cs",fontSize=12,textColor=colors.HexColor("#AED6F1"),alignment=TA_CENTER)
sNL=S("nl",fontSize=15,textColor=WHITE,alignment=TA_CENTER,fontName="Helvetica-Bold")

def hdr(canvas,doc):
    canvas.saveState()
    canvas.setFillColor(DARK_BLUE); canvas.rect(0,PH-0.65*cm,PW,0.65*cm,fill=1,stroke=0)
    canvas.setFillColor(WHITE); canvas.setFont("Helvetica-Bold",7)
    canvas.drawString(M,PH-0.45*cm,"EPILEPSY — Final Year MBBS Exam Notes (Expanded Edition)")
    canvas.setFont("Helvetica",7)
    canvas.drawRightString(PW-M,PH-0.45*cm,"Kumar & Clark 11e | Harrison's | Oxford Handbook of Medicine")
    canvas.setFillColor(LT_GREY); canvas.rect(0,0,PW,0.9*cm,fill=1,stroke=0)
    canvas.setFillColor(MID_GREY); canvas.setFont("Helvetica",6.5)
    canvas.drawString(M,0.32*cm,"Refs: Kumar & Clark 11e • Harrison's Principles • Oxford Handbook of Medicine • Bradley & Daroff Neurology • Katzung Pharmacology • ILAE 2017 Guidelines")
    canvas.drawRightString(PW-M,0.32*cm,f"Page {doc.page}")
    canvas.restoreState()

def sec(t,c=DARK_BLUE):
    tb=Table([[Paragraph(f"<b>{t}</b>",sH1)]],colWidths=[W])
    tb.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),c),("TOPPADDING",(0,0),(-1,-1),9),("BOTTOMPADDING",(0,0),(-1,-1),9),("LEFTPADDING",(0,0),(-1,-1),12)]))
    return [tb,Spacer(1,5)]
def h2(t): return [Paragraph(f"<b>{t}</b>",sH2),HRFlowable(width="100%",thickness=1.1,color=MED_BLUE,spaceAfter=3)]
def h3(t): return [Paragraph(f"<b>{t}</b>",sH3)]
def bo(t): return [Paragraph(t,sBo)]
def bu(items): return [Paragraph(f"• {i}",sBu) for i in items]
def sp(h=6): return [Spacer(1,h)]
def box(txt,label,bg,bdr,sty):
    t=Table([[Paragraph(f"<b>{label}:</b> {txt}",sty)]],colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),bg),("BOX",(0,0),(-1,-1),1,bdr),("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),("LEFTPADDING",(0,0),(-1,-1),8),("RIGHTPADDING",(0,0),(-1,-1),8)]))
    return [t,Spacer(1,5)]
def warn(t): return box(t,"⚠ EXAM TRAP",LT_RED,RED,sWN)
def tip(t):  return box(t,"★ HIGH-YIELD",LT_TEAL,TEAL,sTP)
def note(t): return box(t,"◆ SRI LANKA / CLINICAL PEARL",LT_PURPLE,PURPLE,sNT)
def orange(t): return box(t,"◈ IMPORTANT",LT_ORANGE,ORANGE,sON)
def mkt(headers,rows,cw=None,hc=DARK_BLUE):
    if cw is None: cw=[W/len(headers)]*len(headers)
    data=[[Paragraph(f"<b>{h}</b>",sTH) for h in headers]]+[[Paragraph(str(c),sTD) for c in r] for r in rows]
    t=Table(data,colWidths=cw,repeatRows=1)
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,0),hc),("ROWBACKGROUNDS",(0,1),(-1,-1),[WHITE,LT_GREY]),("GRID",(0,0),(-1,-1),0.4,MID_GREY),("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),("LEFTPADDING",(0,0),(-1,-1),5),("RIGHTPADDING",(0,0),(-1,-1),5),("VALIGN",(0,0),(-1,-1),"TOP")]))
    return [t,Spacer(1,7)]
def kbox(items,title,bg,bdr):
    ps=[Paragraph(f"<b>{title}</b>",S("kt",fontSize=10,textColor=bdr,fontName="Helvetica-Bold",spaceAfter=3))]
    for i in items: ps.append(Paragraph(f"◆  {i}",S("ki",fontSize=9,leading=13)))
    t=Table([[ps]],colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),bg),("BOX",(0,0),(-1,-1),1.2,bdr),("TOPPADDING",(0,0),(-1,-1),8),("BOTTOMPADDING",(0,0),(-1,-1),8),("LEFTPADDING",(0,0),(-1,-1),10),("RIGHTPADDING",(0,0),(-1,-1),10)]))
    return [t,Spacer(1,6)]

def cover():
    E=[]
    t=Table([[Paragraph("EPILEPSY",sCT)]],colWidths=[W])
    t.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),DARK_BLUE),("TOPPADDING",(0,0),(-1,-1),28),("BOTTOMPADDING",(0,0),(-1,-1),10)]))
    E.append(t)
    s=Table([[Paragraph("Final Year MBBS Exam Notes — Expanded Edition with Full Management Algorithms",sCS)]],colWidths=[W])
    s.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),MED_BLUE),("TOPPADDING",(0,0),(-1,-1),9),("BOTTOMPADDING",(0,0),(-1,-1),9)]))
    E.append(s); E.append(Spacer(1,14))
    secs=[(DARK_BLUE,"1","Definition & Epidemiology"),(MED_BLUE,"2","Aetiology — ILAE Classification"),(TEAL,"3","Seizure Classification — ILAE 2017"),(PURPLE,"4","Epilepsy Syndromes"),(colors.HexColor("#1A7A6E"),"5","Diagnosis & Investigations"),(ORANGE,"6","Differential Diagnosis (Seizure vs Syncope vs NEAD)"),(GREEN,"7","Management — AED Selection + Full Pharmacology"),(colors.HexColor("#922B21"),"8","Status Epilepticus — Emergency Algorithm"),(colors.HexColor("#6C3483"),"9","Special Situations (Pregnancy, Driving, Febrile Convulsions)"),(DARK_BLUE,"10","NEW: First Seizure & Chronic Epilepsy Algorithms"),(MED_BLUE,"11","NEW: Non-Pharmacological Management (Lifestyle, Ketogenic Diet)"),(TEAL,"12","NEW: Surgical & Device-Based Management"),(ORANGE,"13","NEW: Women with Epilepsy — Complete Guide"),(RED,"14","NEW: SUDEP + Febrile Convulsion Algorithm"),(DARK_BLUE,"15","High-Yield Exam Summary (30 Points)")]
    for col,num,name in secs:
        r=Table([[Paragraph(f"<b>{num}</b>",sNL),Paragraph(f"<b>{name}</b>",S("sn",fontSize=10,textColor=WHITE,leading=14))]],colWidths=[1*cm,W-1*cm-0.1*cm])
        r.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),col),("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),("LEFTPADDING",(0,0),(-1,-1),8),("VALIGN",(0,0),(-1,-1),"MIDDLE")]))
        E.append(r); E.append(Spacer(1,3))
    E.append(Spacer(1,12))
    ref=Table([[Paragraph("References: Kumar & Clark's Clinical Medicine 11e • Harrison's Principles of Internal Medicine • Oxford Handbook of Medicine • Bradley & Daroff's Neurology in Clinical Practice • Katzung Basic & Clinical Pharmacology 16e • ILAE 2017 Classification • Rosen's Emergency Medicine",sCA)]],colWidths=[W])
    ref.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),LT_GREY),("BOX",(0,0),(-1,-1),0.5,MID_GREY),("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),("LEFTPADDING",(0,0),(-1,-1),8)]))
    E.append(ref); E.append(PageBreak())
    return E

def original():
    E=[]
    # S1
    E+=sec("1. Definition & Epidemiology")
    E+=kbox(["Epilepsy = disorder of brain characterised by enduring predisposition to generate epileptic seizures","ILAE 2014: ≥2 unprovoked seizures >24h apart, OR 1 unprovoked seizure with ≥60% risk of recurrence","Epileptic seizure = transient signs/symptoms from abnormal, excessive or synchronous neuronal activity"],"DEFINITIONS",LT_BLUE,DARK_BLUE)
    E+=warn("A single seizure is NOT epilepsy. A provoked seizure (fever, metabolic, drugs, acute brain injury) is NOT epilepsy.")
    E+=mkt(["Parameter","Detail"],[["Prevalence","~1% of the general population"],["Incidence","Bimodal: peak in childhood AND >60 years"],["Drug refractoriness","~30% fail to achieve seizure control with optimal medical therapy"],["SUDEP","Sudden Unexpected Death in Epilepsy — risk 1:1000/year general epilepsy; 1:150 refractory epilepsy"]],cw=[4*cm,W-4*cm])
    E+=sp()
    # S2
    E+=sec("2. Aetiology — ILAE Classification",c=MED_BLUE)
    E+=mkt(["Category","Examples"],[["Structural","Hippocampal sclerosis (mesial TLE — most common structural cause), cortical dysplasia, post-stroke, brain tumour, post-traumatic, tuberous sclerosis, Sturge-Weber"],["Genetic","SCN1A (Dravet syndrome), KCNQ2, KCNQ3 mutations; chromosomal: Down syndrome, Angelman syndrome"],["Infectious","Neurocysticercosis (most common cause of epilepsy worldwide), cerebral TB/tuberculoma, HSV encephalitis, cerebral malaria, HIV"],["Metabolic","Hypoglycaemia, hyponatraemia, hypocalcaemia, hypomagnesaemia, uraemia, hepatic encephalopathy, pyridoxine deficiency"],["Immune","Anti-NMDAR encephalitis, anti-LGI1, anti-CASPR2, anti-AMPAR"],["Unknown","~50% of all epilepsy cases — largest category"]],cw=[3*cm,W-3*cm])
    E+=note("In Sri Lanka/South Asia: Neurocysticercosis and CNS tuberculosis are important infective causes. Always ask about dietary history (pork), travel history, and TB contacts. Consider CT brain for ring-enhancing lesions.")
    E+=sp()
    # S3
    E+=sec("3. Seizure Classification — ILAE 2017",c=TEAL)
    E+=bo("ILAE 2017 classification based on: (1) Onset type, (2) Level of awareness for focal, (3) Motor vs non-motor features.")
    E+=h2("Focal Onset Seizures")
    E+=mkt(["Old Term","New ILAE 2017 Term","Features"],[["Simple partial seizure","Focal AWARE seizure","Consciousness fully preserved"],["Complex partial seizure","Focal IMPAIRED AWARENESS seizure","Consciousness impaired; automatisms (lip smacking, fumbling, chewing)"],["Partial seizure 2° generalised","Focal to BILATERAL TONIC-CLONIC","Starts focally → spreads both hemispheres; preceded by aura"]],cw=[4*cm,4.5*cm,W-8.5*cm])
    E+=h3("Auras by Lobe of Origin:")
    E+=mkt(["Lobe","Aura / Ictal Features"],[["Temporal","Epigastric rising (most common), déjà vu/jamais vu, olfactory hallucinations, fear, automatisms"],["Frontal","Motor manifestations, nocturnal, brief, hypermotor, rapid secondary generalisation"],["Parietal","Sensory (tingling, numbness), pain, distorted body image"],["Occipital","Visual hallucinations (colours, shapes), eye deviation, nystagmus"]],cw=[3*cm,W-3*cm])
    E+=tip("Todd's Paresis = post-ictal focal weakness (minutes to hours) after focal motor seizure. Important localising sign. Always document.")
    E+=h2("Generalised Onset Seizures")
    E+=mkt(["Type","Features","EEG"],[["Tonic-Clonic (Grand Mal)","Tonic (stiffening, cyanosis) → Clonic (rhythmic jerking); lateral tongue bite; urinary incontinence; post-ictal confusion hours","Generalised polyspike-wave; post-ictal diffuse slowing"],["Absence (Petit Mal)","5-20 sec staring; abrupt onset/offset; NO post-ictal; NO aura; eye blinking; childhood","3 Hz spike-and-wave; activated by hyperventilation"],["Myoclonic","Brief bilateral muscle jerks; morning; consciousness preserved","Polyspike-wave 4-6 Hz; may be photosensitive"],["Atonic (Drop Attacks)","Sudden loss of muscle tone → falls; brief LOC","Spike-wave or polyspike-wave"],["Tonic","Sustained muscle contraction; nocturnal; falls","Low amplitude fast activity"],["Epileptic Spasms","Infantile spasms (salaam attacks); flexion/extension trunk in clusters; developmental regression","Hypsarrhythmia"]],cw=[3*cm,7*cm,W-10*cm])
    E+=warn("Absence vs Focal Impaired Awareness: Absence — no aura, no post-ictal, <30 sec, 3 Hz spike-wave, childhood. Complex partial — aura present, post-ictal confusion, longer (1-3 min), temporal focus. VERY commonly tested.")
    E+=warn("Carbamazepine and Phenytoin WORSEN absence, myoclonic, and atonic seizures — NEVER use for these seizure types or JME.")
    E+=sp()
    # S4
    E+=sec("4. Epilepsy Syndromes",c=PURPLE)
    E+=mkt(["Syndrome","Age","Clinical Features","EEG","First-Line Drug"],[["West Syndrome","3-12 months","Salaam attacks in clusters; developmental regression; poor prognosis","Hypsarrhythmia","ACTH / Vigabatrin"],["Lennox-Gastaut","1-7 years","Multiple seizure types (tonic, atonic, atypical absence); intellectual disability; treatment-resistant","Slow spike-wave <2.5 Hz","Valproate + Clobazam; Rufinamide"],["Childhood Absence Epilepsy","4-10 years; F>M","Multiple daily absences; normal development; good prognosis","3 Hz spike-wave; hyperventilation","Ethosuximide; Valproate"],["Juvenile Myoclonic Epilepsy (JME)","12-18 years","Morning myoclonus + GTCS + absence; sleep deprivation precipitates; often lifelong treatment","Polyspike-wave 4-6 Hz; photosensitive","Sodium Valproate (most effective); Levetiracetam; Lamotrigine"],["Temporal Lobe Epilepsy","Any age (>10 y)","Most common focal epilepsy; epigastric aura; déjà vu; automatisms; hippocampal sclerosis on MRI","Anterior temporal spikes; rhythmic theta ictal","Carbamazepine; Lamotrigine"],["Dravet Syndrome","First year","Prolonged febrile seizures → refractory epilepsy; SCN1A mutation 80%; cognitive decline","Varies; photosensitive","Valproate + Clobazam; Stiripentol — AVOID Na+ channel blockers"],["Benign Rolandic Epilepsy","5-12 years","Nocturnal GTCS + facial twitching; self-limited → remits by adolescence","Centrotemporal spikes during sleep","Often none needed; Carbamazepine if required"]],cw=[3*cm,1.8*cm,6.2*cm,3*cm,W-14*cm])
    E+=tip("JME triad: Morning myoclonus + GTCS + absence. Precipitants: sleep deprivation, alcohol, early awakening. Valproate most effective but AVOID in women of childbearing age.")
    E+=sp()
    # S5
    E+=sec("5. Diagnosis & Investigations",c=TEAL)
    E+=h2("Clinical History (Most Important)")
    E+=bu(["Witness account ESSENTIAL — patient may be unaware of ictal behaviour","Onset: focal or generalised? Aura? What was first thing that happened?","Duration, frequency, timing (nocturnal, morning, random), precipitants","Post-ictal: confusion, Todd's paresis, headache, tongue bite, incontinence","Birth history, developmental history, family history, drug/alcohol history"])
    E+=h2("EEG")
    E+=mkt(["EEG Type","Details"],[["Epileptiform activity","Spikes and sharp waves — specific finding. ~90% of epileptics show epileptiform activity on EEG"],["Normal interictal EEG","Does NOT exclude epilepsy — substantial number have consistently normal interictal EEGs"],["False positive rate","Only ~2% of non-epileptics have epileptiform discharges (high specificity)"],["Ictal EEG (Video-EEG monitoring)","GOLD STANDARD — records electrographic seizure during typical attack; used in pre-surgical evaluation"],["Yield-enhancing techniques","Sleep-deprived EEG, hyperventilation (absence), intermittent photic stimulation (photosensitive epilepsy)"],["Photoparoxysmal response","Generalised spike-wave to photic stimulation → photosensitive epilepsy"]],cw=[4*cm,W-4*cm])
    E+=warn("'The EEG is always abnormal in epilepsy' = FALSE. Normal interictal EEG does NOT exclude epilepsy. Diagnosis is CLINICAL.")
    E+=h2("Neuroimaging + Bloods")
    E+=bu(["MRI brain (preferred): structural causes — hippocampal sclerosis (T2/FLAIR hyperintensity + atrophy), cortical dysplasia, tumours, cavernomas","CT brain: acute settings, calcification (neurocysticercosis, tuberous sclerosis)","FDG-PET + Ictal SPECT: pre-surgical evaluation","Bloods: FBC, U&E, glucose, Ca²⁺, Mg²⁺, LFT, AED levels","Prolactin: rises 2-3x within 20 min of GTCS — NORMAL in NEAD/pseudoseizures"])
    E+=sp()
    # S6
    E+=sec("6. Differential Diagnosis",c=ORANGE)
    E+=mkt(["Feature","Epileptic Seizure (GTCS)","Vasovagal Syncope","NEAD / Pseudoseizure"],[["Prodrome","Aura (specific)","Pre-syncope: dizziness, sweating, dimming vision","Variable; emotional trigger common"],["Trigger","Often none; sleep deprivation, lights","Upright position, pain, stress","Emotional stress, trauma history"],["Colour","Cyanosis","Pallor","Normal/flushed"],["Duration","<3 min","Seconds","Often >2 min; waxing-waning"],["Movements","Synchronous, rhythmic, bilateral","Brief myoclonic jerks (if prolonged)","Asynchronous, thrashing, pelvic thrusting"],["Eyes","OPEN, deviated","Open or closed","Usually CLOSED (key sign)"],["Tongue bite","Lateral border (SPECIFIC)","Tip (rare)","Rare; tip if present"],["Incontinence","Common (GTCS)","Uncommon","Uncommon"],["Post-ictal","YES — mins to hours","Rapid recovery","Variable; prolonged tearfulness"],["Prolactin","Elevated within 20 min","Normal","Normal"],["EEG during attack","Abnormal ictal pattern","Normal","Normal"]],cw=[3*cm,4*cm,4*cm,W-11*cm])
    E+=tip("Eyes CLOSED during a 'seizure' strongly suggests NEAD. Eyes OPEN = true GTCS. Also: asynchronous movements, pelvic thrusting, opisthotonus, side-to-side head rolling = NEAD features.")
    E+=sp()
    # S7 — Management
    E+=sec("7. Management — AED Selection & Full Pharmacology",c=GREEN)
    E+=h2("When to Start AEDs")
    E+=mkt(["Situation","Decision"],[["≥2 unprovoked seizures","Start AEDs — standard indication"],["1 unprovoked + high recurrence risk","Start AEDs if: structural lesion, abnormal EEG, abnormal neurology, strong family history, high personal risk (driver, occupation)"],["Provoked seizure","Treat underlying cause; AEDs usually NOT indicated"],["1 unprovoked, low risk","Discuss; patient preference; consider lifestyle/driving; may observe"]],cw=[5*cm,W-5*cm])
    E+=h2("AED Selection by Seizure Type")
    E+=mkt(["Seizure/Syndrome","First-Line","Second-Line","Avoid"],[["Focal seizures","Carbamazepine, Lamotrigine","Levetiracetam, Oxcarbazepine, Valproate, Lacosamide","—"],["Generalised tonic-clonic","Sodium Valproate, Lamotrigine","Levetiracetam, Topiramate","Carbamazepine (may worsen)"],["Absence","Ethosuximide, Sodium Valproate","Lamotrigine","Carbamazepine, Phenytoin, Tiagabine"],["Myoclonic","Sodium Valproate","Levetiracetam, Clonazepam, Topiramate","Carbamazepine, Phenytoin, Gabapentin"],["JME","Sodium Valproate (most effective)","Levetiracetam, Lamotrigine","Carbamazepine, Phenytoin"],["Temporal Lobe Epilepsy","Carbamazepine","Lamotrigine, Levetiracetam","—"],["West Syndrome","ACTH, Vigabatrin","Valproate, Pyridoxine (if B6-dependent)","—"],["Dravet Syndrome","Valproate + Clobazam","Stiripentol, Cannabidiol","Carbamazepine, Lamotrigine, Phenytoin"],["Lennox-Gastaut","Valproate + Clobazam","Rufinamide, Lamotrigine, Topiramate, Cannabidiol","—"]],cw=[3.5*cm,3.5*cm,5*cm,W-12*cm])
    E+=h2("AED Pharmacology — Full Side Effects Table")
    E+=mkt(["Drug","Mechanism","Important Side Effects","Special Points"],[["Carbamazepine","Na⁺ channel blocker","Diplopia, ataxia, drowsiness; hyponatraemia (SIADH); rash → SJS; aplastic anaemia; benign leukopenia","Enzyme INDUCER (↓OCP, warfarin); check HLA-B*1502 in Asian patients before prescribing → SJS risk"],["Phenytoin","Na⁺ channel blocker","Nystagmus, ataxia, diplopia (dose-related); gingival hyperplasia, hirsutism, coarse facies, peripheral neuropathy, folate deficiency, osteoporosis (chronic)","Zero-order kinetics — small dose increase = large level rise; enzyme INDUCER; IV: arrhythmias if given fast; never in dextrose"],["Sodium Valproate","Multiple: Na⁺ channel, GABA↑, T-Ca²⁺ channel","Tremor, weight gain, hair loss (reversible); TERATOGENIC (NTD, cognitive impairment); hepatotoxicity (children <2 y); thrombocytopenia; pancreatitis; polycystic ovaries","HIGHEST teratogenicity risk; Pregnancy Prevention Programme required; AVOID in women of childbearing age unless no alternative"],["Lamotrigine","Na⁺ channel blocker","Rash → SJS if titrated too fast; diplopia, ataxia, insomnia","Titrate SLOWLY especially when added to valproate (valproate doubles lamotrigine levels); preferred in pregnancy; levels reduced by OCP"],["Levetiracetam","SV2A vesicle protein","Behavioural: irritability, aggression, depression ('levetiracetam rage')","No drug interactions; no enzyme induction; safe in pregnancy and renal impairment; preferred in renal/hepatic disease"],["Ethosuximide","T-type Ca²⁺ channel blocker","GI upset (nausea, vomiting); headache; rare blood dyscrasias","ONLY for absence seizures; does NOT treat GTCS — add valproate if GTCS also present"],["Phenobarbitone","GABA-A receptor agonist","Sedation, cognitive impairment, hyperactivity in children; dependence; osteoporosis","Enzyme INDUCER; cheap and widely used in resource-limited settings"],["Topiramate","Multiple mechanisms","Cognitive slowing, word-finding difficulty; weight loss; kidney stones; angle-closure glaucoma; teratogenic (cleft palate)","Useful in migraine prophylaxis; useful for weight reduction"],["Oxcarbazepine","Na⁺ channel blocker","Hyponatraemia (more than CBZ); dizziness, diplopia; rash (25% cross-reactivity with CBZ)","Less enzyme induction than CBZ; check Na⁺ levels"],["Clobazam","GABA-A receptor agonist (1,5-benzodiazepine)","Sedation, tolerance, tolerance (less than 1,4-BZDs); dizziness","Used in Lennox-Gastaut, Dravet, catamenial epilepsy; intermittent use reduces tolerance"]],cw=[2.5*cm,3*cm,5.5*cm,W-11*cm])
    E+=note("HLA-B*1502 (common in Sri Lankan, South Asian, and Southeast Asian populations) strongly associated with carbamazepine-induced Stevens-Johnson Syndrome / TEN. Consider HLA testing before carbamazepine in these populations.")
    E+=warn("Valproate in women of childbearing age: HIGHEST teratogenic risk — neural tube defects, craniofacial abnormalities, cognitive impairment in child (10-15 IQ points). Requires Pregnancy Prevention Programme.")
    E+=h2("Stopping AEDs")
    E+=bu(["Consider after 2 years seizure-free","Taper gradually over months — NEVER abrupt (withdrawal seizures / SE)","Warn about driving (must not drive during withdrawal and for 6 months after in UK)","Higher recurrence risk: structural cause, abnormal EEG, focal epilepsy"])
    E+=sp()
    # S8 — SE
    E+=sec("8. Status Epilepticus — Emergency Algorithm",c=RED)
    E+=kbox(["Operational definition (treat now): seizure >5 MINUTES → START TREATMENT","Traditional definition: >30 min continuous seizure OR ≥2 without full recovery between","Mortality: 10-20% in convulsive SE","Most common cause in known epileptic = AED NON-COMPLIANCE","Delays in benzodiazepine >10 minutes associated with higher mortality"],"STATUS EPILEPTICUS — EMERGENCY",LT_RED,RED)
    E+=mkt(["Time","Phase","Action","Drugs"],[["0–5 min","Stabilise","ABC, left lateral position, O₂ (15L NRB mask), suction; IV/IO access; continuous monitoring; BM glucose; Bloods: FBC, U&E, glucose, Ca²⁺, Mg²⁺, LFT, AED levels, blood cultures, ABG; urine toxicology; ECG","If hypoglycaemia: Thiamine 250 mg IV FIRST (if alcoholic/malnourished) → then 50 mL of 50% dextrose IV"],["5–10 min","1st Line\nBenzodiazepines","Give ASAP; do NOT delay","IV access: Lorazepam IV 0.1 mg/kg (4 mg adult) — DRUG OF CHOICE\nNo IV access: Midazolam IM/buccal 10 mg (adult); Diazepam rectal 10-20 mg\nRepeat once after 5 min if seizure continues"],["10–30 min","2nd Line\nAED Loading","If seizure persists after 2 BZD doses; give concurrently with 2nd BZD dose; three options equally supported:","Levetiracetam IV 60 mg/kg (max 4500 mg) over 10 min — PREFERRED (safest)\nFosphenytoin IV 20 mg PE/kg over 15 min (ECG + BP monitoring)\nSodium Valproate IV 40 mg/kg over 10 min (CI: liver disease, thrombocytopenia, metabolic disease)"],["30–60 min","Refractory SE","Anaesthesia + intubation + ICU + continuous EEG monitoring","Propofol IV infusion OR Thiopental IV OR Midazolam IV infusion\nTitrate to burst-suppression on EEG"],["60+ min","Super-refractory SE","Seizure continues >24h despite anaesthesia; consider autoimmune encephalitis; MDT","Ketamine IV; Hypothermia (35°C); Ketogenic diet; Immunotherapy (IVIG/steroids/plasma exchange if autoimmune — esp. anti-NMDAR); Isoflurane"]],cw=[1.5*cm,2.5*cm,6*cm,W-10*cm])
    E+=tip("Fosphenytoin PREFERRED over phenytoin IV: water-soluble, less cardiotoxic, can give IM, 3x faster infusion rate, compatible with dextrose-containing fluids.")
    E+=warn("Phenytoin IV: give at max 50 mg/min with continuous cardiac monitoring. NEVER mix phenytoin in dextrose IV solutions — precipitates. Risk of hypotension and arrhythmia if infused too fast.")
    E+=sp()
    # S9
    E+=sec("9. Special Situations",c=PURPLE)
    E+=h2("Epilepsy & Driving")
    E+=mkt(["Licence Type","Requirement"],[["Private car (Group 1)","Seizure-free for 1 year before driving; or sleep-only seizures ≥3 years; must notify licensing authority"],["Heavy goods / Bus (Group 2)","Seizure-free for 10 years, off all AEDs for 10 years"],["During AED withdrawal","Must not drive during withdrawal and for 6 months after final dose"],["Physician's duty","Advise patient to notify licensing authority; document advice in medical notes"]],cw=[4*cm,W-4*cm])
    E+=h2("Epilepsy & Pregnancy — AED Teratogenicity")
    E+=bo("PRINCIPLE: Uncontrolled seizures (especially GTCS) are MORE dangerous to the foetus than most AEDs. Do NOT stop AEDs without specialist advice.")
    E+=mkt(["AED","Teratogenic Risk","Comment"],[["Sodium Valproate","HIGHEST — avoid if possible","NTD (spina bifida 1-2%), craniofacial abnormalities, cognitive impairment (10-15 IQ points); Pregnancy Prevention Programme mandatory"],["Carbamazepine","Moderate (NTD ~0.5-1%)","Lowest risk among older AEDs; folic acid 5 mg/day essential"],["Phenytoin","Moderate","Fetal hydantoin syndrome: craniofacial abnormalities, digit hypoplasia, cardiac defects"],["Lamotrigine","Low (preferred)","Preferred in pregnancy; levels fall significantly — monitor monthly and increase dose"],["Levetiracetam","Low (preferred)","Preferred; levels also fall — monitor"],["Phenobarbitone","Moderate","Cardiac defects; neonatal withdrawal, sedation"],["Topiramate","Moderate (cleft palate, SGA)","Avoid if possible"]],cw=[3*cm,3.5*cm,W-6.5*cm])
    E+=bu(["Folic acid 5 mg/day: start ≥3 months pre-conception, continue throughout","Oral Vitamin K 10 mg/day in last 4 weeks of pregnancy (if on enzyme-inducing AEDs)","Neonatal Vitamin K 1 mg IM at birth","Breastfeeding: generally safe; lamotrigine and levetiracetam preferred; phenobarbitone — neonatal sedation risk"])
    E+=h2("Febrile Convulsions")
    E+=mkt(["Type","Definition","Action"],[["Simple","Generalised; <15 min; single in 24 hours; complete recovery","Reassure parents; paracetamol 15 mg/kg; NO regular AEDs; diazepam rectal/midazolam buccal only if >5 min"],["Complex","Focal OR >15 min OR >1 in 24 hours OR incomplete recovery","Investigate: LP (if <18 months or meningism), FBC, U&E, glucose; blood cultures; EEG; MRI; neurology referral"]],cw=[2.5*cm,5.5*cm,W-8*cm])
    E+=bu(["Risk of developing epilepsy later = 2-3% only","Simple febrile convulsions do NOT cause brain damage","Recurrence risk = 30-40%"])
    E+=warn("Do NOT prescribe regular prophylactic AEDs for simple febrile convulsions — no evidence of benefit, significant side effects. A favourite exam question.")
    E+=sp()
    # 30-point summary
    E+=sec("Original 30-Point Exam Summary",c=DARK_BLUE)
    E+=mkt(["#","Key Exam Point","Answer"],[["1","Definition of epilepsy","≥2 unprovoked seizures >24h apart OR 1 unprovoked + ≥60% recurrence risk"],["2","Provoked seizure = epilepsy?","NO — treat the underlying cause"],["3","ILAE 2017 seizure types","Focal (aware/impaired awareness/to bilateral TC) | Generalised | Unknown"],["4","Old 'complex partial' = new term?","Focal impaired awareness seizure"],["5","Absence EEG","3 Hz spike-and-wave; enhanced by hyperventilation"],["6","Drug for absence","Ethosuximide (1st line); Sodium valproate"],["7","AED that worsens absence/myoclonus","Carbamazepine and Phenytoin — NEVER use"],["8","Most teratogenic AED","Sodium Valproate — highest NTD + cognitive risk"],["9","AEDs preferred in pregnancy","Lamotrigine and Levetiracetam"],["10","HLA-B*1502 significance","Asian patients: carbamazepine → SJS/TEN. Test before prescribing."],["11","Phenytoin kinetics","Zero-order (saturable) — small dose increase = large level rise"],["12","Phenytoin chronic side effects","Gingival hyperplasia, hirsutism, coarse facies, peripheral neuropathy"],["13","Enzyme-inducing AEDs","CBZ, PHT, Phenobarbitone, Primidone, Topiramate >200 mg, Oxcarbazepine → reduce OCP, warfarin"],["14","Valproate side effects","Tremor, weight gain, hair loss, teratogenicity, hepatotoxicity, thrombocytopenia, pancreatitis"],["15","Levetiracetam side effect","Behavioural: irritability, aggression, depression ('levetiracetam rage')"],["16","Todd's paresis","Post-ictal focal weakness after focal motor seizure — localising sign"],["17","Prolactin in GTCS","Elevated within 20 min of GTCS; NORMAL in NEAD"],["18","Eyes in NEAD vs true seizure","NEAD: eyes CLOSED; True GTCS: eyes OPEN"],["19","SE operational definition",">5 minutes → START TREATMENT (don't wait for 30 min)"],["20","SE 1st-line drug","Lorazepam IV 0.1 mg/kg (4 mg adult); Midazolam IM/buccal if no IV"],["21","SE 2nd-line drug","Levetiracetam IV / Fosphenytoin IV / Sodium Valproate IV"],["22","Fosphenytoin vs Phenytoin","Fosphenytoin: water-soluble, less cardiotoxic, give IM, 3x faster"],["23","Most common SE cause in known epileptic","AED non-compliance"],["24","Driving after epilepsy (private car)","1 year seizure-free"],["25","Simple febrile convulsion management","Reassure + antipyretics; NO regular AEDs"],["26","Febrile convulsion → epilepsy risk","2-3% only"],["27","Best surgical outcome","Temporal lobectomy for mesial TLE: 80-90% seizure freedom"],["28","Normal EEG excludes epilepsy?","FALSE — substantial proportion have normal interictal EEGs"],["29","JME triad","Morning myoclonus + GTCS + absence; sleep deprivation triggers"],["30","West syndrome EEG","Hypsarrhythmia; treat with ACTH/Vigabatrin"]],cw=[0.7*cm,6*cm,W-6.7*cm])
    E+=PageBreak()
    return E

def new_sections():
    E=[]
    # S10 — Algorithms
    E+=sec("10. NEW — Management Algorithms",c=DARK_BLUE)
    E+=h2("A. First Seizure Management Algorithm")
    E+=mkt(["Step","Decision / Action","Key Points"],[["First seizure presentation","Take full history (witness account essential); examination; rule out acute symptomatic cause","Always get a witness history; examine for focal deficits, signs of raised ICP, meningism"],["Is it PROVOKED?","YES (fever, metabolic, drugs, alcohol withdrawal, acute brain injury) → Treat underlying cause. AEDs usually NOT indicated. May reconsider if underlying structural cause","Provoked seizure ≠ epilepsy. Address the cause."],["Is it UNPROVOKED?","YES → Investigations: EEG (within 24-48h ideally), MRI brain, FBC, U&E, glucose, Ca, Mg, LFT","Aim to complete investigations before starting AEDs if safe to do so"],["High recurrence risk?","YES if: structural lesion on MRI, abnormal EEG (epileptiform), focal neurological deficit, nocturnal seizure, strong family history → RECOMMEND starting AED","Discuss risks/benefits; patient education; driving implications"],["Low recurrence risk?","Discuss with patient. Consider: occupation (driver, pilot, surgeon, works at heights), lifestyle (swimming, sports). Patient may choose to observe OR start AED","Document discussion in notes; ensure patient knows signs to look for"],["AED started","Choose appropriate drug for seizure type identified. Start low, titrate slowly. Arrange follow-up EEG + clinic review in 4-6 weeks","Monotherapy; appropriate for syndrome; warn about side effects and interactions"]],cw=[2.5*cm,6.5*cm,W-9*cm])
    E+=sp(4)
    E+=h2("B. Chronic Epilepsy Management Algorithm (Treat-to-Target)")
    E+=mkt(["Step","Phase","Action"],[["1","New diagnosis confirmed","Confirm: clinical + EEG + MRI → identify seizure type + syndrome → start appropriate AED monotherapy"],["2","First AED — adequate dose","Titrate to therapeutic dose; review at 3-6 months"],["2a","SEIZURE-FREE ≥2 YEARS","→ Consider gradual AED withdrawal (warn driving; taper over months; risk ~30-40% relapse)"],["2b","SEIZURES CONTINUE at adequate dose","→ Check compliance + drug levels → Switch to SECOND AED monotherapy"],["3","Second AED fails","→ Try third monotherapy OR dual therapy (2 AEDs)"],["4","Failed 2 appropriate AEDs = DRUG-REFRACTORY EPILEPSY (20%)","→ REFER to specialist epilepsy centre"],["5","Specialist evaluation","→ Pre-surgical evaluation: Video-EEG + High-res MRI (3T epilepsy protocol) + Neuropsychology + FDG-PET + Ictal SPECT + fMRI + Wada test"],["6a","SURGICAL CANDIDATE","→ Surgery (temporal lobectomy for mesial TLE: 80-90% seizure-free; lesionectomy; hemispherectomy for hemispheric epilepsy)"],["6b","NOT SURGICAL CANDIDATE","→ VNS (50% get ≥50% reduction) OR DBS-ANT (SANTE trial: 68% ≥50% at 5 years) OR RNS NeuroPace (closed-loop) OR Ketogenic diet OR Combination"]],cw=[0.8*cm,4*cm,W-4.8*cm])
    E+=sp()
    # S11
    E+=sec("11. NEW — Non-Pharmacological Management",c=MED_BLUE)
    E+=h2("Lifestyle Modifications")
    E+=mkt(["Modification","Details / Rationale"],[["Sleep hygiene","CRITICAL especially for JME — sleep deprivation is the #1 trigger. Regular sleep schedule; avoid all-nighters; manage shift work carefully"],["Alcohol avoidance","Alcohol lowers seizure threshold directly; withdrawal also precipitates seizures. Advise complete avoidance in poorly controlled epilepsy"],["Stress management","Stress is a common trigger. Relaxation techniques, yoga, mindfulness, CBT"],["Photosensitive epilepsy","Avoid flickering lights (discos, TV flicker, video games with strobing). Wear FL-41 tinted glasses or polarised lenses. Cover one eye if accidentally exposed to strobe"],["Catamenial epilepsy","Seizures perimenstrual (days -3 to +3) or periovulatory. Seizure diary essential. Clobazam 10 mg TDS during catamenial window. Progesterone supplementation days 14-26. GnRH analogues for refractory cases"],["Safety precautions","No swimming alone or unsupervised; shower preferred to bath (drowning risk); no cooking over open flame alone; avoid heights; no operating heavy machinery; no driving until seizure-free"],["Medical alert identification","Medical alert bracelet or card; inform school, employer (if safe to do so), close contacts"],["Seizure diary","Record all seizures, triggers, timing, duration — helps identify patterns, guide treatment, assess response to AEDs"]],cw=[4*cm,W-4*cm])
    E+=h2("Dietary Therapies")
    E+=mkt(["Diet","Composition","Best Indication","Efficacy","Side Effects / Monitoring"],[["Ketogenic Diet (classical)","4:1 fat:(carb+protein) ratio by weight; high fat (cream, butter, oils); protein adequate; carbs minimal","Children with refractory epilepsy; West syndrome; Dravet syndrome; GLUT-1 deficiency; Pyruvate dehydrogenase deficiency","~50% of patients get ≥50% seizure reduction; some become seizure-free; works in 1-3 months","Constipation, hyperlipidaemia, kidney stones, growth retardation, bone demineralisation, vitamin/mineral deficiencies. Monitor: urinary ketones daily, growth, lipid profile, renal USS (stones), FBC, LFTs, bone density"],["Modified Atkins Diet","High fat, low carb (<10-20 g/day); protein unrestricted","Adolescents and adults; more acceptable long-term","Similar to classical KD but slightly lower efficacy","Less strict monitoring needed; GI upset"],["Low Glycaemic Index Treatment (LGIT)","Low glycaemic index foods (<50 GI); carbs ~40-60 g/day","Adults who cannot tolerate classical KD","~50% of responders; milder effect","Fewer dietary restrictions; more sustainable"],["MCT (Medium Chain Triglyceride) Diet","MCT oil supplements; allows more carbohydrate than classical KD","Alternative in children; MCT oil more ketogenic per calorie","Similar to classical KD","GI upset, bloating — titrate MCT oil slowly"]],cw=[3*cm,3.5*cm,3*cm,2*cm,W-11.5*cm])
    E+=tip("Ketogenic diet is especially effective in GLUT-1 deficiency disorder and pyruvate dehydrogenase deficiency — where it is FIRST-LINE treatment, not a last resort.")
    E+=h2("Psychological & Social Support")
    E+=bu(["CBT for depression and anxiety — very common comorbidities in epilepsy (up to 30-50% of patients)","Neuropsychological assessment — memory, cognitive function, academic performance (especially before surgery)","Epilepsy nurse specialist / key worker — patient education, telephone helpline, AED titration support","Seizure first aid training for carers, family, teachers, employers","Patient and family education: seizure diary, trigger identification, medication compliance","Social: DVLA notification (mandatory, not optional), employment guidance (avoid heights/water/machinery), benefits and disability support, support groups (Epilepsy Action, Epilepsy Society in UK)"])
    E+=sp()
    # S12
    E+=sec("12. NEW — Surgical & Device-Based (Neuromodulation) Management",c=TEAL)
    E+=h2("Pre-Surgical Evaluation (Phase 1 & 2)")
    E+=bu(["Indication: drug-refractory epilepsy (failed ≥2 appropriate AEDs at adequate doses)","Phase 1 (non-invasive): prolonged video-EEG + high-res MRI (3T epilepsy protocol, hippocampal volumetry) + neuropsychology + FDG-PET (interictal hypometabolism at focus) + Ictal SPECT (SISCOM — ictal hyperperfusion)","Phase 2 (if Phase 1 inconclusive): invasive intracranial EEG (stereoEEG/SEEG or subdural grids) to map seizure onset zone","fMRI for language and memory lateralisation (non-invasive)","Wada test (intracarotid amobarbital test): injects amobarbital into ICA → temporarily anaesthetises one hemisphere → assesses language dominance and memory reserve of each side before dominant hemisphere surgery"])
    E+=h2("Surgical Procedures")
    E+=mkt(["Procedure","Indication","Seizure-Free Rate","Key Risks"],[["Anterior temporal lobectomy (ATL)","Mesial TLE + hippocampal sclerosis — MOST COMMON epilepsy surgery","60-80% seizure-free at 2 years","Memory impairment (especially dominant hemisphere), superior quadrantanopia ('pie in the sky' — Meyer's loop injury), language deficits if dominant side"],["Lesionectomy","Focal structural lesion: tumour, cavernoma, cortical dysplasia, low-grade glioma","Depends on completeness of resection and lesion type","Related to lesion location; language/motor if eloquent cortex involved"],["Hemispherectomy / Hemispherotomy","Severe unilateral hemispheric epilepsy: Rasmussen encephalitis, hemimegalencephaly, Sturge-Weber, large unilateral cortical dysplasia","60-80%; best in young children with already-deficient hemisphere","Hemiplegia (usually pre-existing), hemianopia; hydrocephalus"],["Corpus callosotomy","Atonic (drop attacks) in LGS; prevents bilateral propagation","Palliative — reduces drop attacks by ~70%; rarely seizure-free","Disconnection syndrome (rare); acute interhemispheric transfer deficits"],["Multiple subpial transection (MST)","Epileptogenic zone overlaps eloquent cortex (Broca, Wernicke, motor strip)","Modest seizure reduction","Transient neurological deficits; not widely used"]],cw=[3.5*cm,4*cm,2.5*cm,W-10*cm])
    E+=h2("Device-Based Therapy (Neuromodulation)")
    E+=mkt(["Device","Target","Mechanism","Efficacy","Side Effects"],[["Vagus Nerve Stimulation (VNS)","Left vagus nerve (right avoided — cardiac projections)","Implanted pulse generator in chest; helical electrode on left vagus; open-loop continuous stimulation; additional magnet to abort individual seizures","~50% achieve ≥50% seizure reduction; ~3% seizure-free; slow improvement over years","Hoarseness (most common), cough, throat pain, dyspnoea during stimulation; voice change"],["Deep Brain Stimulation (DBS)","Anterior nucleus of thalamus (ANT); also centromedian nucleus (CM) for LGS","Bilateral open-loop stimulation; SANTE trial: 110 patients","SANTE trial: 68% had >50% reduction at 5 years; 16% seizure-free","Infection (device), lead migration, stimulation side effects (depression, memory); requires battery replacement"],["Responsive Neurostimulation (RNS / NeuroPace)","Seizure focus (1-2 foci maximum)","Closed-loop: detects ictal EEG pattern → delivers electrical stimulation to abort seizure; implanted in skull","~50-66% seizure reduction at 2+ years; improves over time","Infection (device-related), lead migration; stimulation side effects"],["External Trigeminal Nerve Stimulation (eTNS)","Trigeminal nerve — non-invasive","External device applied to forehead; stimulates trigeminal nerve (cranial V)","Modest evidence; adjunctive therapy for focal epilepsy","Skin irritation; non-invasive; no surgical risk"]],cw=[2.5*cm,2.5*cm,3.5*cm,3*cm,W-11.5*cm])
    E+=sp()
    # S13
    E+=sec("13. NEW — Women with Epilepsy",c=ORANGE)
    E+=h2("Contraception & AEDs")
    E+=mkt(["AED Category","Effect on OCP","Recommendation"],[["Enzyme-inducing AEDs\n(CBZ, PHT, Phenobarb, Primidone, Topiramate >200 mg/day, Oxcarbazepine)","Induce CYP450 → increase oestrogen/progestogen metabolism → REDUCE OCP efficacy → breakthrough pregnancy risk","Use ≥50 mcg ethinylestradiol pill (high-dose combined OCP) OR barrier method OR non-hormonal IUD (copper coil — most reliable)"],["Non-enzyme-inducing AEDs\n(Valproate, Lamotrigine, Levetiracetam, Gabapentin, Pregabalin)","Minimal or no effect on OCP","Standard OCP acceptable"],["OCP effect on Lamotrigine","OCP reduces lamotrigine levels by up to 50% (increases glucuronidation)","Increase lamotrigine dose when OCP started; monitor levels; reduce dose in pill-free week"],["DMPA (Depo-Provera)","Uncertain interaction with enzyme inducers — reduce injection interval to 10 weeks if on enzyme inducers","Discuss; IUD or implant preferred"]],cw=[4*cm,4*cm,W-8*cm])
    E+=h2("Pre-conception Counselling")
    E+=bu(["Start folic acid 5 mg/day at least 3 months BEFORE conception (not just when pregnant)","Aim to switch valproate to safer AED (lamotrigine/levetiracetam) at least 3-6 months before conception to allow stability","Aim for lowest effective dose and monotherapy","Counsel on teratogenic risks of current AED — use EURAP or UK Epilepsy and Pregnancy Register data","Do NOT stop AEDs abruptly — seizure risk to mother and foetus (GTCS → foetal hypoxia, placental abruption)"])
    E+=h2("Management During Pregnancy")
    E+=mkt(["Issue","Management"],[["AED levels change","Lamotrigine levels fall significantly in pregnancy (↑renal clearance); levetiracetam levels also fall. Monitor levels monthly. Increase doses to maintain therapeutic range. Reduce back to pre-pregnancy dose AFTER delivery (or levels will rise above therapeutic → toxicity)"],["Monitoring","Detailed foetal anomaly scan at 18-20 weeks; nuchal translucency scan 11-13 weeks (NTD screening)"],["Vitamin K","Oral vitamin K 10 mg/day in last 4 weeks of pregnancy if on enzyme-inducing AEDs (reduces neonatal haemorrhagic disease from reduced clotting factor synthesis)"],["Labour","Continue AEDs; IV lorazepam immediately available; avoid prolonged labour; caesarean only for obstetric indication or very high seizure risk"],["Post-partum","Reduce lamotrigine/LEV back to pre-pregnancy dose promptly; breastfeeding generally safe; sleep deprivation precautions — enlist support for night feeds; discuss co-sleeping risks"]],cw=[3.5*cm,W-3.5*cm])
    E+=h2("Breastfeeding Safety")
    E+=mkt(["AED","Breastfeeding Safety"],[["Lamotrigine","Low milk levels; generally safe — preferred"],["Levetiracetam","Low milk levels; generally safe — preferred"],["Sodium Valproate","Low milk levels; generally safe"],["Carbamazepine","Low milk levels; generally safe"],["Phenobarbitone","Significant milk levels — neonatal sedation/poor feeding; caution; monitor baby"],["Ethosuximide","Significant milk levels — monitor baby carefully"]],cw=[4*cm,W-4*cm])
    E+=sp()
    # S14
    E+=sec("14. NEW — SUDEP & Febrile Convulsion Algorithm",c=RED)
    E+=h2("SUDEP — Sudden Unexpected Death in Epilepsy")
    E+=mkt(["Aspect","Details"],[["Definition","Sudden, unexpected, witnessed or unwitnessed, non-traumatic, non-drowning death of a person with epilepsy with or without evidence of a seizure, excluding documented status epilepticus"],["Annual risk","1:1000/year in general epilepsy; up to 1:150 in refractory/severe epilepsy"],["Risk factors","Frequent uncontrolled GTCS (most important), nocturnal seizures, sleeping alone, prone position during sleep, young adult male, poor AED compliance, alcohol use, polypharmacy, intellectual disability"],["Mechanism","Likely: post-ictal respiratory depression (central apnoea) + cardiac arrhythmia (post-ictal generalised EEG suppression — PGES); vagal mechanism may also contribute"],["Prevention","Optimise seizure control (most important); nocturnal supervision or movement monitoring devices (bed alarms); avoid sleeping alone; avoid prone sleep position; seizure alert dogs; room-sharing; ensure AED compliance"],["Discussion","SUDEP must be discussed with patients and carers — documented in notes. Use SUDEP Action resources."]],cw=[3.5*cm,W-3.5*cm])
    E+=h2("Febrile Convulsion — Management Algorithm")
    E+=mkt(["Time / Step","Action","Key Points"],[["0–5 min","Recovery position (lateral); time seizure; protect from injury; call for help; O₂ via face mask; check BM glucose; attach monitoring if available","Do NOT put anything in mouth. Time the seizure. Do NOT restrain."],["If seizure >5 min","Buccal Midazolam 0.5 mg/kg (max 10 mg) — preferred for community/first-line\nOR Rectal Diazepam 0.5 mg/kg (if no IV access)\nOR IV/IO Lorazepam 0.1 mg/kg if IV access available","Use buccal midazolam in community (easier, effective, no rectal procedure needed)"],["If still seizing at 10 min","Second dose of benzodiazepine","Same drug same route OR switch route"],["If still seizing at 20 min","Paediatric STATUS EPILEPTICUS PROTOCOL — 2nd line AEDs: IV Levetiracetam / Phenytoin / Valproate","Treat as SE; admit PICU"],["After seizure stops","Antipyretics: Paracetamol 15 mg/kg (NOT aspirin — Reye's syndrome risk)\nCool environment, tepid sponging (do not over-cool)\nInvestigate if any complex features","Reassure parents; explain likely benign nature; give written information"],["Investigate if","Complex features: focal seizure, >15 min, >1 in 24h, incomplete recovery; OR age <18 months; OR signs of meningism; OR first febrile seizure in older child","LP if: <18 months with first febrile seizure OR any age with meningism OR inadequate vaccination history"],["Discharge","Simple febrile convulsion with full recovery → can discharge from ED with safety netting","Give written seizure first aid instructions to parents; paracetamol prescription; GP follow-up"]],cw=[2.5*cm,6.5*cm,W-9*cm])
    E+=warn("Regular prophylactic antipyretics do NOT prevent febrile convulsion recurrence — paracetamol lowers temperature but not seizure threshold. Do NOT prescribe regular AEDs for simple febrile convulsions.")
    E+=note("Parents need clear written instructions for seizure first aid: recovery position, timing seizure, when to call 999 (ambulance if >5 min or child doesn't recover normally), and reassurance that simple febrile convulsions are not dangerous.")
    E+=sp()
    return E

doc=SimpleDocTemplate(OUT,pagesize=A4,leftMargin=M,rightMargin=M,topMargin=M+0.65*cm,bottomMargin=M+0.9*cm,title="Epilepsy — Final Year MBBS Exam Notes v2")
doc.build(cover()+original()+new_sections(),onFirstPage=hdr,onLaterPages=hdr)
print(f"DONE: {OUT}")

??

Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.