1.Malaria- Pathogenesis,morphology* 2.Cysticercoisis-etiopathogenesis,morphology 3.Leprosy-pathogenesis,classify,gross and microscopic Findings *** 4.Common viral and fungal infections 5. Primary Tuberculosis- pathogenesis,common sites,Evolution of tubercle,Primary complex - components * 6.Ghons complex - Gross,microscopic features and fate***2 mbbs pathology refer robbin add easy to draw diagram coloured , answer all question important topics frequently ask topic in muhs exam systemically aswer all

Reading File
Now let me search for all topics simultaneously:
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
I now have enough information from Robbins to compile comprehensive answers. Let me also get the malaria and cysticercosis content from Robbins:
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Now let me get the cysticercosis and TB morphology content:
Reading File
Reading File
I now have extensive content from Robbins to build comprehensive answers. Let me now compile the full notes:Here are your complete, exam-ready MUHS Pathology notes based on Robbins & Kumar (Pathologic Basis of Disease, 10e and Basic Pathology):

2nd MBBS PATHOLOGY - MUHS EXAM NOTES

(Based on Robbins & Kumar Pathology)


1. MALARIA - Pathogenesis & Morphology ⭐

Etiology

Five species: P. falciparum (most virulent), P. vivax, P. ovale, P. malariae, P. knowlesi. Transmitted by the female Anopheles mosquito. Humans are the only natural reservoir.

Life Cycle / Pathogenesis

┌─────────────────────────────────────────────────────────────────┐
│              LIFE CYCLE OF PLASMODIUM FALCIPARUM                │
│                                                                 │
│  Mosquito bites human                                           │
│       ↓                                                         │
│  SPOROZOITES enter blood → travel to LIVER                      │
│  (bind to hepatocytes via thrombospondin & circumsporozoite     │
│   surface proteins)                                             │
│       ↓ (Exo-erythrocytic stage - ASYMPTOMATIC)                 │
│  Sporozoites → MEROZOITES (up to 30,000 per hepatocyte)         │
│  Infected hepatocytes RUPTURE → merozoites released             │
│  [P. vivax / P. ovale → form HYPNOZOITES → relapses]            │
│       ↓                                                         │
│  Merozoites invade RBCs (bind sialic acid on glycophorin)       │
│  [Erythrocytic stage - SYMPTOMATIC]                             │
│       ↓                                                         │
│  Merozoite → TROPHOZOITE → SCHIZONT → new Merozoites            │
│  (PfEMP1 knobs appear on RBC surface)                           │
│       ↓                                                         │
│  RBC LYSIS → fever, chills, rigors (TNF release)               │
│       ↓                                                         │
│  Some trophozoites → GAMETOCYTES (sexual forms)                 │
│  → mosquito ingests gametocytes → cycle restarts                │
└─────────────────────────────────────────────────────────────────┘

Why P. falciparum is More Virulent:

  1. Infects RBCs of ALL ages (not just young/old) → very high parasitemia
  2. PfEMP1 on RBC surface knobs - binds endothelial ICAM-1, VCAM-1, CD36, E-selectin → SEQUESTRATION in capillaries → blocks blood flow → cerebral malaria
  3. Rosette formation - infected RBCs clump together
  4. No hypnozoites - rupture occurs in 8-12 weeks

Fever Periodicity:

  • P. vivax / P. ovale: 48h (tertian - every 3rd day)
  • P. malariae: 72h (quartan - every 4th day)
  • P. falciparum: irregular (malignant tertian)

Host Protection:

  • Sickle cell trait, G6PD deficiency, Duffy antigen negativity (P. vivax) are protective
  • West Africans lack Duffy antigen → not susceptible to P. vivax

Morphology

ORGAN          │ GROSS/MICRO FINDINGS
───────────────┼──────────────────────────────────────────────────
SPLEEN         │ Splenomegaly (may exceed 1000g)
               │ Red pulp congestion + hyperplasia
               │ Gray/black hemozoin pigment in macrophages
               │ Chronic: fibrotic, thick capsule, brittle
───────────────┼──────────────────────────────────────────────────
LIVER          │ Enlarged, pigmented
               │ Kupffer cells laden with malarial pigment,
               │ parasitized RBCs, cellular debris
───────────────┼──────────────────────────────────────────────────
BRAIN          │ (P. falciparum - Cerebral Malaria)
(CEREBRAL)     │ Vessels PLUGGED with parasitized RBCs
               │ Ring hemorrhages around vessels
               │ Malarial granuloma (Dürck granuloma)
               │ Neuronal degeneration, focal ischemic softening
───────────────┼──────────────────────────────────────────────────
KIDNEY         │ Enlarged, congested
               │ Malarial pigment in glomeruli
               │ Hemoglobin casts in tubules
               │ (Blackwater fever - massive hemolysis)
───────────────┼──────────────────────────────────────────────────
BONE MARROW /  │ Pigmented phagocytic cells throughout
LYMPH NODES    │ Hemozoin pigment
───────────────┼──────────────────────────────────────────────────
BLOOD SMEAR    │ Giemsa stain: parasites inside RBCs
               │ Ring trophozoites, schizonts, gametocytes

Diagnostic Test: Giemsa-stained peripheral blood smear (gold standard)


2. CYSTICERCOSIS - Etiopathogenesis & Morphology ⭐

Etiology

  • Caused by Taenia solium (pork tapeworm) larval stage
  • Disease = human acts as INTERMEDIATE host (ingests eggs)
  • Normal: pigs are intermediate host, humans are definitive host (harbor adult worm)
  • Cysticercosis occurs when human ingests T. solium eggs (from contaminated food/water/fecal-oral route, or autoinfection via reverse peristalsis)

Etiopathogenesis

┌──────────────────────────────────────────────────────────────────┐
│                 CYSTICERCOSIS PATHOGENESIS                       │
│                                                                  │
│  Human ingests T. solium EGGS (contaminated food/water)          │
│       ↓                                                          │
│  Eggs hatch in intestine → ONCOSPHERES (hexacanth embryos)       │
│       ↓                                                          │
│  Oncospheres penetrate intestinal wall                           │
│       ↓                                                          │
│  Enter bloodstream → disseminate to TISSUES                      │
│       ↓                                                          │
│  Develop into CYSTICERCI (fluid-filled cysts with scolex inside) │
│                                                                  │
│  Preferred sites: Brain (most dangerous), subcutaneous tissue,   │
│                   eye, muscle, heart, liver                      │
│                                                                  │
│  ALIVE CYST: minimal inflammation (immune evasion)              │
│       ↓ (when cyst dies)                                         │
│  DEAD/DEGENERATING CYST: intense inflammation                    │
│  → eosinophils, neutrophils, macrophages surround cyst           │
│  → fibrous capsule formation                                     │
│  → CALCIFICATION (seen on CT scan)                               │
└──────────────────────────────────────────────────────────────────┘

Clinical Manifestations by Site:

  • Neurocysticercosis (NCC): Seizures (most common cause of acquired epilepsy in endemic areas), headache, raised ICP, hydrocephalus
  • Ocular: Visual disturbances, blindness
  • Subcutaneous: Palpable nodules

Morphology

Gross:

  • Cysticercus cellulosae: Round/oval, translucent, fluid-filled cyst
  • Size: 0.5-2 cm (usually), up to 20 cm (racemose form in brain)
  • Wall is white, glistening
  • Scolex (invaginated head) visible inside as white nodule
  • In brain: cysts in cortex, basal ganglia, ventricles
  • Racemose variant: grapelike, no scolex, in cisterns/ventricles

Microscopic:

STAGE           │ MICROSCOPIC FEATURES
────────────────┼───────────────────────────────────────────────
VIABLE CYST     │ - Outer cuticular layer (lamellar)
                │ - Middle cellular (reticular) layer
                │ - Inner germinal layer
                │ - Scolex with suckers and hooklets visible
                │ - Minimal host inflammatory response
────────────────┼───────────────────────────────────────────────
DEGENERATING/   │ - Cyst wall hyalinizes and breaks down
DEAD CYST       │ - INTENSE INFLAMMATION:
                │   Eosinophils, neutrophils, lymphocytes,
                │   plasma cells, macrophages
                │ - Granuloma formation
                │ - Giant cell reaction
────────────────┼───────────────────────────────────────────────
CALCIFIED CYST  │ - Dense calcification of dead scolex and wall
                │ - Fibrosis/gliosis around it (in brain)

3. LEPROSY - Pathogenesis, Classification, Gross & Microscopic ⭐⭐⭐

Etiology

  • Mycobacterium leprae (and rarely M. lepromatosis)
  • Slow progressive infection affecting skin and peripheral nerves
  • Cannot be cultured in vitro
  • Proliferates best at 32-34°C (cool tissues, extremities)
  • Transmission: human respiratory secretions (main route)

Pathogenesis

M. leprae enters via respiratory tract
       ↓
Taken up by DERMAL MACROPHAGES
       ↓
Disseminates via blood → replicates in COOL TISSUES
(skin, extremities, peripheral nerves)
       ↓
M. leprae: obligate intracellular → uses PGL-1 lipid for cell invasion
         → inhibits mitochondrial energy metabolism
         → evades host immune response
       ↓
┌────────────────────────────────────┐
│    HOST IMMUNE RESPONSE decides    │
│        the TYPE OF LEPROSY         │
└────────────────────────────────────┘
         ↙                     ↘
  STRONG Th1                WEAK Th1
(IL-2, IFN-γ, Th17)      (Th2 dominant/
  response                Reg T cells)
         ↓                      ↓
 TUBERCULOID              LEPROMATOUS
  LEPROSY                  LEPROSY
(Paucibacillary)          (Multibacillary)
 Low organisms,            High organisms,
  Granulomas               No granulomas

Key Immunology:

FeatureTuberculoidLepromatous
T-cell responseStrong Th1 (IFN-γ, IL-2)Weak Th1, Th2 dominant
Bacterial loadLow (paucibacillary)High (multibacillary)
AntibodiesLowHigh (but NOT protective)
CMIIntactDeficient
Lepromin testPositiveNegative

Classification (Ridley-Jopling + WHO)

SPECTRUM OF LEPROSY:

Tuberculoid (TT) ←──── Borderline ────→ Lepromatous (LL)
      │          BT    BB    BL              │
   Strong                               Weak
  Immunity                           Immunity
Paucibacillary                     Multibacillary
WHO Classification (Clinically used):
  • Paucibacillary (PB): 1-5 skin lesions (Tuberculoid/Borderline T)
  • Multibacillary (MB): >5 skin lesions (Lepromatous/Borderline L)

Gross (Clinical) Findings

Tuberculoid Leprosy:

  • Flat, red skin lesions that enlarge
  • Irregular shapes with indurated, elevated, hyperpigmented margins
  • Depressed, pale centers (central healing)
  • Anesthetic (loss of sensation - damaged nerves)
  • Asymmetric large peripheral nerve involvement
  • Nerve thickening: ulnar, radial, common peroneal, great auricular nerves
  • Skin and muscle atrophy, chronic ulcers, contractures, autoamputation of digits

Lepromatous Leprosy:

  • Symmetric skin thickening
  • Macular, papular, or nodular lesions on face, ears, wrists, elbows, knees
  • Coalescence of nodules → Leonine facies (lion-like face)
  • Most skin lesions are hyposthetic or anesthetic
  • Saddle nose deformity (nasal septum destruction)
  • Persistent nasal discharge with bacilli
  • Gynecomastia + testicular destruction → sterility
  • Symmetric nerve involvement (ulnar, peroneal nerves)

Microscopic Findings

TUBERCULOID LEPROSY:
┌──────────────────────────────────────────────────────┐
│  - Well-formed GRANULOMAS (like TB granulomas)       │
│  - Epithelioid cells + Langhans giant cells          │
│  - Dense lymphocytic infiltrate                     │
│  - Granulomas enclose and DESTROY NERVES            │
│  - Bacilli ABSENT or very rare (AFB stain negative) │
│  - Granulomas extend to basal layer of epidermis    │
└──────────────────────────────────────────────────────┘

LEPROMATOUS LEPROSY:
┌──────────────────────────────────────────────────────┐
│  - Large aggregates of LIPID-LADEN MACROPHAGES       │
│    = LEPRA CELLS (Virchow cells / foam cells)        │
│  - Lepra cells filled with GLOBI (masses of AFB)     │
│  - AFB in globi = "cigar bundles" or "cannon balls"  │
│  - NO granulomas (absent cell-mediated immunity)     │
│  - Grenz zone: subepidermal clear zone               │
│  - Lymph nodes: bacteria-filled foamy macrophages    │
│    in paracortical (T-cell) areas + reactive GCs    │
│  - Testes: destruction of seminiferous tubules       │
│  - Nerves: invaded by mycobacteria with MINIMAL      │
│    inflammation                                      │
└──────────────────────────────────────────────────────┘

Easy-to-Draw Diagram - Lepra Cell:

     LEPRA CELL (Lepromatous Leprosy)
          ┌─────────────────────┐
          │    Macrophage        │
          │  ╔═══╗ ╔═══╗ ╔═══╗  │
          │  ║AFB║ ║AFB║ ║AFB║  │  ← Globi (masses of
          │  ╚═══╝ ╚═══╝ ╚═══╝  │     acid-fast bacilli)
          │     Foamy cytoplasm  │
          │         (lipid)      │
          │      [Nucleus]       │
          └─────────────────────┘
Stain: Ziehl-Neelsen (AFB stain) - red bacilli on blue background

4. COMMON VIRAL AND FUNGAL INFECTIONS ⭐

A. Common Viral Infections

1. INFLUENZA

  • Single-stranded RNA virus, 8-segment genome
  • Surface proteins: Hemagglutinin (H) and Neuraminidase (N)
  • Type A infects humans, pigs, horses, birds (major epidemic cause)
  • Antigenic Drift: point mutations in H and N → epidemics
  • Antigenic Shift: recombination with animal viruses → pandemics
  • 1918 pandemic (swine origin, 20-40 million deaths); 2009 H1N1 pandemic

2. CORONAVIRUSES / COVID-19

  • SARS-CoV-2 (COVID-19): spike protein binds ACE2 on nasopharyngeal epithelium + type 2 alveolar cells
  • Pathogenesis: virus replication → DAD (Diffuse Alveolar Damage) → Type II pneumocyte injury → hyaline membranes
  • Severe COVID: coagulopathy, microthrombi, myocarditis, CNS inflammatory infiltrates
  • Treatment: dexamethasone (immunosuppression), low-dose anticoagulants

3. HERPES SIMPLEX VIRUS (HSV)

  • Cowdry type A inclusion bodies (intranuclear eosinophilic)
  • Multinucleated giant cells
  • HSV-1: oral/facial; HSV-2: genital

4. CYTOMEGALOVIRUS (CMV)

  • Large cells with "owl-eye" intranuclear inclusions
  • Dangerous in immunocompromised (AIDS, transplant patients)

5. MEASLES (Rubeola)

  • Warthin-Finkeldey giant cells (multinucleated giant cells with inclusions) in lymphoid organs
  • Koplik spots on buccal mucosa
  • Squamous metaplasia of bronchial epithelium

B. Common Fungal Infections

1. CANDIDIASIS

  • Candida albicans (most common)
  • Pseudohyphae + budding yeast on PAS / GMS stain
  • Superficial: thrush (oral), vulvovaginal
  • Deep: esophageal candidiasis, systemic (neutropenic patients)
  • Micro: Pseudohyphae invading tissue with neutrophilic infiltrate

2. ASPERGILLOSIS

  • Aspergillus fumigatus most common
  • Acute angle (45°) branching septate hyphae - GMS stain
  • Types:
    • Allergic bronchopulmonary aspergillosis (ABPA)
    • Aspergilloma (fungal ball in pre-existing cavity)
    • Invasive aspergillosis (in immunocompromised) - hemorrhagic infarcts (angioinvasive)

3. CRYPTOCOCCOSIS

  • Cryptococcus neoformans
  • India ink stain: thick mucoid capsule (clear halo)
  • PAS/Mucicarmine: magenta capsule
  • Soap bubble lesions in brain (gelatinous pseudocysts)
  • AIDS patients: meningoencephalitis

4. MUCORMYCOSIS (ZYGOMYCOSIS)

  • Rhizopus, Mucor spp.
  • Broad, non-septate hyphae branching at right angles (90°)
  • Angioinvasive → tissue infarction
  • Rhinocerebral form in diabetics (DKA)

5. HISTOPLASMOSIS

  • Histoplasma capsulatum
  • Intracellular within macrophages (2-4 μm yeast)
  • Endemic: Ohio/Mississippi river valleys
  • Mimics TB - granulomas, calcification

5. PRIMARY TUBERCULOSIS - Pathogenesis, Common Sites, Evolution of Tubercle, Primary Complex ⭐

Etiology

  • Mycobacterium tuberculosis (acid-fast bacillus)
  • Transmission: respiratory droplets (aerosol)
  • Primary TB: disease in previously unexposed, unsensitized individual
  • Only ~5% of newly infected develop significant disease

Pathogenesis

┌────────────────────────────────────────────────────────────────┐
│           PATHOGENESIS OF PRIMARY TUBERCULOSIS                 │
│                                                                │
│  INHALATION of M. tuberculosis                                 │
│       ↓                                                        │
│  Bacilli reach ALVEOLI (lower part of UPPER LOBE or            │
│                          upper part of LOWER LOBE)            │
│       ↓                                                        │
│  Phase 1 - INNATE RESPONSE (first 3 weeks):                    │
│  Alveolar macrophages phagocytose bacilli                       │
│  M. tb prevents phagolysosome fusion                           │
│  Bacilli survive & multiply INSIDE macrophages                 │
│  Macrophages release chemokines → monocyte recruitment         │
│  Dendritic cells carry antigens to DRAINING LYMPH NODES        │
│       ↓ (~3 weeks later)                                       │
│  Phase 2 - ADAPTIVE IMMUNITY (Th1 response):                   │
│  DCs present antigens → Th1 differentiation                    │
│  (requires IL-12, IL-18 from APCs)                             │
│       ↓                                                        │
│  Th1 cells produce IFN-γ                                       │
│       ↓                                                        │
│  IFN-γ activates macrophages:                                  │
│  1. Produces nitric oxide + ROS → kills bacteria               │
│  2. Mobilizes defensins (cathelicidin)                         │
│  3. Stimulates AUTOPHAGY                                       │
│       ↓                                                        │
│  Activated macrophages → EPITHELIOID HISTIOCYTES               │
│       ↓                                                        │
│  GRANULOMA FORMATION + CASEOUS NECROSIS                        │
│       ↓                                                        │
│  ~95%: Infection CONTAINED → Ghon complex heals                │
│   ~5%: Progressive primary TB (immunocompromised)              │
└────────────────────────────────────────────────────────────────┘

Role of TNF: Recruits monocytes, maintains granuloma integrity. TNF inhibitors (anti-rheumatic drugs) → reactivation of TB.


Common Sites of Primary TB

  1. Lungs (most common) - subpleural, lower part of upper lobe OR upper part of lower lobe
  2. Intestine (ileum) - from ingestion of M. bovis
  3. Tonsil / pharynx - rare
  4. Skin (primary inoculation TB)

Evolution of the Tubercle (Granuloma)

STAGE 1 - INITIAL LESION:
Local accumulation of macrophages (HISTIOCYTES)
       ↓
STAGE 2 - EPITHELIOID GRANULOMA:
Macrophages transform into EPITHELIOID CELLS
(elongated, pink cytoplasm, looks like epithelium but IS NOT)
Surrounded by LYMPHOCYTES (CD4+ T cells mainly)
       ↓
STAGE 3 - GIANT CELL FORMATION:
Epithelioid cells fuse → LANGHANS GIANT CELLS
(nuclei arranged in horseshoe/peripheral pattern)
       ↓
STAGE 4 - CASEOUS NECROSIS:
Centre becomes CASEOUS (cheese-like, amorphous, eosinophilic)
= due to hypersensitivity (DTH) reaction
Caseous necrosis = PATHOGNOMONIC of TB
       ↓
STAGE 5 - RESOLUTION / HEALING:
Fibrosis → Calcification (Ranke complex)
         OR
Liquefaction → Cavity formation (secondary TB)

Diagram of Tubercle:

          ┌─────────────────────────────────┐
          │   TB GRANULOMA (TUBERCLE)        │
          │                                 │
          │   ~~~~~~~~CASEOUS NECROSIS~~~~~~│ ← Centre
          │  ~    (amorphous, pink,    ~    │
          │  ~     cheese-like)        ~    │
          │   ~~~~~~~~~~~~~~~~~~~~~~~~      │
          │  [E][E][E][L][L][E][E][E]       │ ← Epithelioid cells (E)
          │  [L]  LANGHANS GIANT CELL [L]   │   Lymphocytes (L)
          │        ⊂ nuclei in               │
          │          horseshoe pattern ⊃     │
          │  [E][E][E][L][L][E][E][E]       │
          │ Fibrous capsule (outer rim)      │
          └─────────────────────────────────┘

Primary Complex - Components ⭐

The Primary (Ghon's) Complex = 3 components:
PRIMARY COMPLEX = GHON FOCUS + LYMPHANGITIS + LYMPHADENITIS

     1. GHON FOCUS (Parenchymal lesion)
     ────────────────────────────────────
     - 1-1.5 cm gray-white area of consolidation
     - Subpleural location
     - Lower part of upper lobe or upper part of lower lobe
     - Centre undergoes caseous necrosis
     - = THE PARENCHYMAL COMPONENT

     2. LYMPHANGITIS
     ────────────────
     - Inflammatory involvement of lymphatic channels
     - Between Ghon focus and hilar lymph nodes

     3. HILAR / REGIONAL LYMPHADENOPATHY
     ─────────────────────────────────────
     - Caseous enlargement of regional (hilar) lymph nodes
     - Usually MORE prominent than the parenchymal lesion
     - = THE NODAL COMPONENT

RANKE COMPLEX:

When the Ghon complex undergoes fibrosis + calcification = Ranke complex (visible on chest X-ray)

6. GHON'S COMPLEX - Gross, Microscopic & Fate ⭐⭐⭐

Definition

The combination of the Ghon focus (parenchymal lesion) + caseous hilar lymph node enlargement + the lymphangitis connecting them = Ghon's Complex

Gross Features

GROSS FEATURES OF GHON'S COMPLEX:
─────────────────────────────────────────────────────
GHON FOCUS:
● Location: Subpleural; lower part of upper lobe OR
            upper part of lower lobe (close to pleura)
● Size: 1 to 1.5 cm
● Colour: Gray-white area of consolidation
● Centre: Caseous necrosis (yellow-white, cheese-like material)
● Surface: May show pleural adhesions
● Surrounding: Zone of consolidation

HILAR LYMPH NODES:
● Enlarged, discrete or matted lymph nodes at hilum
● Cut section: Yellow-white caseous material
● Nodes often LARGER than the parenchymal focus
● May show periadenitis / matting together

LYMPHATICS:
● Thickened lymphatic channels visible on gross
● "Beaded" appearance between focus and nodes
─────────────────────────────────────────────────────

Microscopic Features

MICROSCOPIC FEATURES:
─────────────────────────────────────────────────────
At the GHON FOCUS (parenchymal lesion):

1. CASEOUS NECROSIS at centre:
   - Amorphous, granular, eosinophilic material
   - "Ghost" cell outlines may be visible
   - Loses all cellular architecture

2. GRANULOMATOUS INFLAMMATION surrounding it:
   - EPITHELIOID CELLS (activated macrophages)
     - Elongated cells with eosinophilic, granular cytoplasm
     - Blunt-ended, "footprint-shaped" nuclei
   - LANGHANS GIANT CELLS
     - Peripheral / horseshoe arrangement of nuclei
   - LYMPHOCYTES (mainly CD4+ T cells) at periphery
   - Occasional plasma cells

3. FIBROUS CAPSULE:
   - Outer rim of fibrous tissue encapsulating the granuloma

4. AFB STAIN (Ziehl-Neelsen):
   - Red acid-fast bacilli (may be scanty in primary TB)
   - More abundant in progressive disease / immunocompromised

In HILAR LYMPH NODES:
   - Similar caseating granulomas
   - Effacement of nodal architecture
   - Caseous necrosis (may be more extensive than focus)

IMPORTANT: In immunocompromised (HIV, CD4 < 200):
   - Granulomas ABSENT
   - Sheets of macrophages with numerous bacilli
   - No caseous necrosis typical pattern
─────────────────────────────────────────────────────

Fate of Ghon's Complex ⭐⭐⭐

┌─────────────────────────────────────────────────────────────────┐
│                    FATE OF GHON'S COMPLEX                       │
│                                                                 │
│         GHON'S COMPLEX (primary TB lesion)                      │
│                      │                                          │
│          ┌───────────┴────────────┐                             │
│    95% of cases                5% of cases                      │
│    (healthy, normal            (immunocompromised,              │
│     immunity)                   malnourished, children)         │
│          │                           │                          │
│          ↓                           ↓                          │
│    HEALING / RESOLUTION       PROGRESSIVE PRIMARY TB            │
│          │                                                      │
│    ┌─────┴──────┐                                               │
│    ↓            ↓                                               │
│ FIBROSIS    CALCIFICATION                                       │
│             ↓                                                   │
│          RANKE COMPLEX                                          │
│      (fibrosis + calcification                                  │
│       - seen on chest X-ray)                                    │
│                                                                 │
│  IF IMMUNITY WANES LATER:                                       │
│  REACTIVATION → SECONDARY TB                                    │
│  (apical lesion, cavity formation)                              │
│                                                                 │
│  COMPLICATIONS OF PRIMARY TB:                                   │
│  1. Haematogenous spread → Miliary TB                           │
│  2. Lymphatic spread → Meningitis, TB vertebra                  │
│  3. Caseous lymph node ruptures → bronchopneumonia              │
│  4. Pleural effusion                                            │
│  5. Progressive primary TB in immunocompromised                 │
└─────────────────────────────────────────────────────────────────┘

Summary Table - Fate

OutcomeMechanismResult
Resolution (95%)Immune controlFibrosis → Calcification = Ranke complex
Progressive Primary (5%)Immune failureCaseous pneumonia, miliary TB
Reactivation (later)Waning immunitySecondary/post-primary TB (apical cavity)
Miliary TBHaematogenous spreadMillet-seed foci throughout organs
TB MeningitisHaematogenous/lymphaticCNS involvement

Quick Comparison Summary

FeatureGhon FocusGhon ComplexRanke Complex
DefinitionParenchymal lesion onlyFocus + Lymphangitis + NodeCalcified Ghon complex
LocationSubpleural, lower upper lobeLung + hilumSame sites, calcified
Size1-1.5 cmExtendedSmaller (healed)
HistologyCaseating granulomaCaseating granulomas at multiple sitesCalcified fibrous tissue
X-rayNot visibleNot visibleVisible as calcified nodule

Sources: Robbins, Cotran & Kumar - Pathologic Basis of Disease, 10e (9780443264528) and Robbins & Kumar Basic Pathology (9780323790185)

MUHS EXAM TIPS:

  • Ghon complex fate is asked almost every exam - memorize the 5 fates
  • Leprosy - always compare tuberculoid vs lepromatous in a table
  • Lepra cell and Langhans giant cell diagrams are frequently asked to draw
  • Malaria - know PfEMP1, sequestration, and cerebral malaria mechanism
  • Cysticercosis - distinguish between human as intermediate vs definitive host
  • Tubercle evolution - 5 stages, Langhans giant cell nucleus pattern (horseshoe/peripheral)
  • Primary complex components = Ghon focus + Lymphangitis + Hilar adenopathy (3-component answer)

Generate a comprehensive revision PDF with all tables, diagrams & mnemonics for these 6 topics

Reading File
Running Command

ls -la /home/daytona/workspace/ 2>/dev/null || echo "workspace empty or not found"

Writing File

~/muhs-study-guide/generate_pdf.py

#!/usr/bin/env python3
"""
MUHS 2nd MBBS Pathology - Comprehensive Revision PDF
Topics: Malaria, Cysticercosis, Leprosy, Viral/Fungal Infections,
        Primary TB, Ghon's Complex
Based on Robbins & Kumar Pathology
"""

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

OUTPUT_PATH = "/home/daytona/workspace/muhs-study-guide/MUHS_Pathology_Revision.pdf"

# ── COLOUR PALETTE ────────────────────────────────────────────────────────────
C_DARK_BLUE   = colors.HexColor("#1a3a5c")
C_MED_BLUE    = colors.HexColor("#2563a8")
C_LIGHT_BLUE  = colors.HexColor("#dbeafe")
C_TEAL        = colors.HexColor("#0f766e")
C_LIGHT_TEAL  = colors.HexColor("#ccfbf1")
C_RED         = colors.HexColor("#b91c1c")
C_LIGHT_RED   = colors.HexColor("#fee2e2")
C_ORANGE      = colors.HexColor("#c2410c")
C_LIGHT_ORANGE= colors.HexColor("#ffedd5")
C_GREEN       = colors.HexColor("#166534")
C_LIGHT_GREEN = colors.HexColor("#dcfce7")
C_PURPLE      = colors.HexColor("#6b21a8")
C_LIGHT_PURPLE= colors.HexColor("#f3e8ff")
C_YELLOW      = colors.HexColor("#854d0e")
C_LIGHT_YELLOW= colors.HexColor("#fef9c3")
C_DARK_GREY   = colors.HexColor("#374151")
C_MID_GREY    = colors.HexColor("#6b7280")
C_LIGHT_GREY  = colors.HexColor("#f3f4f6")
C_WHITE       = colors.white
C_BLACK       = colors.black

# ── STYLES ────────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

def make_style(name, parent='Normal', **kwargs):
    return ParagraphStyle(name, parent=styles[parent], **kwargs)

# Cover / section heading
S_COVER_TITLE = make_style('CoverTitle',
    fontSize=28, textColor=C_WHITE, alignment=TA_CENTER,
    fontName='Helvetica-Bold', spaceAfter=8)

S_COVER_SUB = make_style('CoverSub',
    fontSize=14, textColor=colors.HexColor("#bfdbfe"),
    alignment=TA_CENTER, fontName='Helvetica', spaceAfter=6)

S_SECTION = make_style('Section',
    fontSize=16, textColor=C_WHITE, fontName='Helvetica-Bold',
    alignment=TA_LEFT, spaceAfter=6, spaceBefore=4)

S_SUBSECTION = make_style('Subsection',
    fontSize=12, textColor=C_DARK_BLUE, fontName='Helvetica-Bold',
    spaceAfter=4, spaceBefore=8)

S_BODY = make_style('Body',
    fontSize=9.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=14, spaceAfter=4, alignment=TA_JUSTIFY)

S_BULLET = make_style('Bullet',
    fontSize=9.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=13, spaceAfter=2, leftIndent=14,
    bulletIndent=4)

S_BULLET2 = make_style('Bullet2',
    fontSize=9, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=12, spaceAfter=1, leftIndent=28, bulletIndent=18)

S_MONO = make_style('Mono',
    fontSize=8.5, textColor=C_DARK_GREY, fontName='Courier',
    leading=12, spaceAfter=2, leftIndent=6)

S_MNEMONIC = make_style('Mnemonic',
    fontSize=10.5, textColor=C_TEAL, fontName='Helvetica-Bold',
    leading=14, spaceAfter=3, alignment=TA_CENTER)

S_KEY = make_style('Key',
    fontSize=9, textColor=C_RED, fontName='Helvetica-Bold',
    leading=13, spaceAfter=2)

S_CAPTION = make_style('Caption',
    fontSize=8, textColor=C_MID_GREY, fontName='Helvetica-Oblique',
    alignment=TA_CENTER, spaceAfter=4)

S_TABLE_HEADER = make_style('TblHdr',
    fontSize=9, textColor=C_WHITE, fontName='Helvetica-Bold',
    alignment=TA_CENTER)

S_TABLE_CELL = make_style('TblCell',
    fontSize=8.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=12, alignment=TA_LEFT)

S_TABLE_CELL_C = make_style('TblCellC',
    fontSize=8.5, textColor=C_DARK_GREY, fontName='Helvetica',
    leading=12, alignment=TA_CENTER)

S_SMALL = make_style('Small',
    fontSize=8, textColor=C_MID_GREY, fontName='Helvetica',
    leading=11, spaceAfter=2)

# ── HELPER FLOWABLES ─────────────────────────────────────────────────────────

class ColorBox(Flowable):
    """A rounded-rectangle coloured banner."""
    def __init__(self, text, bg_color, text_color=colors.white,
                 width=None, height=28, font_size=13, bold=True):
        Flowable.__init__(self)
        self.text = text
        self.bg_color = bg_color
        self.text_color = text_color
        self.width = width or (A4[0] - 4*cm)
        self.height = height
        self.font_size = font_size
        self.bold = bold

    def wrap(self, availW, availH):
        self.width = min(self.width, availW)
        return self.width, self.height

    def draw(self):
        c = self.canv
        c.setFillColor(self.bg_color)
        c.roundRect(0, 0, self.width, self.height, 6, fill=1, stroke=0)
        c.setFillColor(self.text_color)
        fn = 'Helvetica-Bold' if self.bold else 'Helvetica'
        c.setFont(fn, self.font_size)
        c.drawCentredString(self.width/2, self.height/2 - self.font_size/2 + 2, self.text)


class DiagramBox(Flowable):
    """Pre-drawn ASCII-art style box using ReportLab lines."""
    def __init__(self, lines, bg=C_LIGHT_GREY, border=C_MED_BLUE,
                 width=None, font_size=8):
        Flowable.__init__(self)
        self.lines = lines
        self.bg = bg
        self.border = border
        self._width = width
        self.font_size = font_size
        self.line_height = font_size + 3
        self.padding = 8

    def wrap(self, availW, availH):
        self._width = self._width or availW
        h = len(self.lines) * self.line_height + 2 * self.padding
        return self._width, h

    def draw(self):
        c = self.canv
        h = len(self.lines) * self.line_height + 2 * self.padding
        c.setFillColor(self.bg)
        c.setStrokeColor(self.border)
        c.setLineWidth(1)
        c.roundRect(0, 0, self._width, h, 5, fill=1, stroke=1)
        c.setFont('Courier', self.font_size)
        c.setFillColor(C_DARK_GREY)
        y = h - self.padding - self.font_size
        for line in self.lines:
            c.drawString(self.padding, y, line)
            y -= self.line_height


def section_banner(title, topic_num, color=C_DARK_BLUE):
    """Returns a list of flowables forming a section header."""
    return [
        Spacer(1, 0.3*cm),
        ColorBox(f"TOPIC {topic_num}  |  {title}", bg_color=color, font_size=13),
        Spacer(1, 0.2*cm),
    ]


def subsection(title, color=C_MED_BLUE):
    return [
        Spacer(1, 0.15*cm),
        ColorBox(title, bg_color=color, height=22, font_size=10.5, text_color=C_WHITE),
        Spacer(1, 0.1*cm),
    ]


def mnemonic_box(title, items, bg=C_LIGHT_TEAL, border=C_TEAL):
    """A nicely styled mnemonic box."""
    content = [
        [Paragraph(f"<b>🧠 MNEMONIC: {title}</b>", make_style('Mn2',
            fontSize=10, textColor=C_TEAL, fontName='Helvetica-Bold',
            alignment=TA_CENTER))],
    ]
    for item in items:
        content.append([Paragraph(item, make_style('Mn3',
            fontSize=9.5, textColor=C_TEAL, fontName='Helvetica',
            alignment=TA_CENTER, leading=13))])
    t = Table(content, colWidths=[A4[0] - 4*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), bg),
        ('BOX', (0,0), (-1,-1), 1.5, border),
        ('ROUNDEDCORNERS', [6]),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
        ('RIGHTPADDING', (0,0), (-1,-1), 10),
    ]))
    return [t, Spacer(1, 0.2*cm)]


def comparison_table(headers, rows, col_widths=None, header_bg=C_DARK_BLUE):
    """Styled comparison table."""
    header_row = [Paragraph(h, S_TABLE_HEADER) for h in headers]
    table_data = [header_row]
    for r in rows:
        table_data.append([Paragraph(str(c), S_TABLE_CELL) for c in r])
    if col_widths is None:
        n = len(headers)
        col_widths = [(A4[0] - 4*cm) / n] * n
    t = Table(table_data, colWidths=col_widths, repeatRows=1)
    style = [
        ('BACKGROUND', (0,0), (-1,0), header_bg),
        ('TEXTCOLOR', (0,0), (-1,0), C_WHITE),
        ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE', (0,0), (-1,0), 9),
        ('ALIGN', (0,0), (-1,-1), 'LEFT'),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [C_WHITE, C_LIGHT_GREY]),
        ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor("#d1d5db")),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
    ]
    t.setStyle(TableStyle(style))
    return [t, Spacer(1, 0.25*cm)]


def key_fact(text):
    return Paragraph(f"<b>★ KEY FACT:</b> {text}", S_KEY)


def bp(text, indent=0):
    """Bullet paragraph."""
    prefix = "• "
    style = S_BULLET if indent == 0 else S_BULLET2
    return Paragraph(f"{prefix}{text}", style)


def divider(color=C_MED_BLUE):
    return HRFlowable(width="100%", thickness=1, color=color,
                      spaceAfter=4, spaceBefore=4)


# ── PAGE TEMPLATE ─────────────────────────────────────────────────────────────

def on_first_page(canvas, doc):
    canvas.saveState()
    # Full-page gradient background
    canvas.setFillColor(C_DARK_BLUE)
    canvas.rect(0, 0, A4[0], A4[1], fill=1, stroke=0)
    # Decorative band at top
    canvas.setFillColor(C_MED_BLUE)
    canvas.rect(0, A4[1]-80, A4[0], 80, fill=1, stroke=0)
    # Decorative band at bottom
    canvas.setFillColor(C_TEAL)
    canvas.rect(0, 0, A4[0], 40, fill=1, stroke=0)
    canvas.restoreState()


def on_later_pages(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(C_DARK_BLUE)
    canvas.rect(0, A4[1]-25, A4[0], 25, fill=1, stroke=0)
    canvas.setFillColor(C_WHITE)
    canvas.setFont('Helvetica-Bold', 8)
    canvas.drawString(1.5*cm, A4[1]-16, "MUHS 2nd MBBS PATHOLOGY — RAPID REVISION")
    canvas.setFont('Helvetica', 8)
    canvas.drawRightString(A4[0]-1.5*cm, A4[1]-16, "Robbins & Kumar Pathology")
    # Footer
    canvas.setFillColor(C_DARK_BLUE)
    canvas.rect(0, 0, A4[0], 18, fill=1, stroke=0)
    canvas.setFillColor(C_WHITE)
    canvas.setFont('Helvetica', 7.5)
    canvas.drawCentredString(A4[0]/2, 5, f"Page {doc.page}")
    canvas.restoreState()


# ── BUILD CONTENT ─────────────────────────────────────────────────────────────

def build_cover():
    elements = []
    # Large vertical spacer to push content to middle of page
    elements.append(Spacer(1, 5.5*cm))
    # Title
    cover_title_style = make_style('CTMain',
        fontSize=30, textColor=C_WHITE, fontName='Helvetica-Bold',
        alignment=TA_CENTER, spaceAfter=10)
    elements.append(Paragraph("MUHS 2nd MBBS PATHOLOGY", cover_title_style))
    elements.append(Paragraph("COMPREHENSIVE RAPID REVISION", make_style('CT2',
        fontSize=20, textColor=colors.HexColor("#93c5fd"),
        fontName='Helvetica-Bold', alignment=TA_CENTER, spaceAfter=16)))
    elements.append(HRFlowable(width="70%", thickness=2,
                               color=C_TEAL, spaceAfter=16, hAlign='CENTER'))
    # Topics
    topic_style = make_style('CTopic',
        fontSize=11.5, textColor=colors.HexColor("#e0f2fe"),
        fontName='Helvetica', alignment=TA_CENTER, spaceAfter=6, leading=18)
    topics = [
        "1. Malaria – Pathogenesis &amp; Morphology",
        "2. Cysticercosis – Etiopathogenesis &amp; Morphology",
        "3. Leprosy – Pathogenesis, Classification &amp; Findings  ★★★",
        "4. Common Viral &amp; Fungal Infections",
        "5. Primary Tuberculosis – Pathogenesis, Sites &amp; Primary Complex  ★",
        "6. Ghon's Complex – Gross, Microscopic &amp; Fate  ★★★",
    ]
    for t in topics:
        elements.append(Paragraph(t, topic_style))
    elements.append(Spacer(1, 1*cm))
    elements.append(HRFlowable(width="70%", thickness=2,
                               color=C_TEAL, spaceAfter=12, hAlign='CENTER'))
    elements.append(Paragraph("Based on Robbins, Cotran &amp; Kumar — Pathologic Basis of Disease (10e)",
        make_style('CRef', fontSize=9, textColor=colors.HexColor("#bfdbfe"),
                   fontName='Helvetica-Oblique', alignment=TA_CENTER)))
    elements.append(PageBreak())
    return elements


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 1 — MALARIA
# ────────────────────────────────────────────────────────────────────────────
def build_malaria():
    E = []
    E += section_banner("MALARIA", 1, C_RED)

    # Overview box
    overview_lines = [
        "Causative organisms: Plasmodium falciparum (most virulent), P. vivax, P. ovale, P. malariae, P. knowlesi",
        "Vector: Female Anopheles mosquito  |  Reservoir: Humans only",
        "200+ million cases/year worldwide  |  600,000+ deaths/year (mostly children < 5 yrs in Africa)",
    ]
    for l in overview_lines:
        E.append(Paragraph(l, S_BODY))
    E.append(Spacer(1, 0.2*cm))

    # Pathogenesis heading
    E += subsection("PATHOGENESIS — Life Cycle", C_MED_BLUE)

    life_cycle = [
        "  MOSQUITO BITE → Sporozoites enter blood",
        "        ↓",
        "  LIVER (Exo-erythrocytic stage) — ASYMPTOMATIC",
        "  Sporozoites bind hepatocytes (thrombospondin + circumsporozoite protein)",
        "  Sporozoites → Merozoites (up to 30,000 per hepatocyte)",
        "  [P. vivax / P. ovale → form HYPNOZOITES → relapse weeks-months later]",
        "        ↓",
        "  Hepatocytes rupture → Merozoites released into blood",
        "        ↓",
        "  RBC INVASION (Erythrocytic stage) — SYMPTOMATIC",
        "  Merozoites bind sialic acid on glycophorin on RBC surface",
        "  Merozoite → Trophozoite → Schizont → new Merozoites",
        "  P. falciparum: PfEMP1 knobs appear on RBC surface",
        "  RBC LYSIS → merozoites released → fever, chills, rigors (TNF surge)",
        "        ↓",
        "  Some trophozoites → GAMETOCYTES (sexual forms)",
        "  Mosquito ingests gametocytes → restarts cycle",
    ]
    E.append(DiagramBox(life_cycle, bg=C_LIGHT_RED, border=C_RED))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("WHY P. FALCIPARUM IS MORE VIRULENT", C_RED)
    virulence = [
        ("1. Infects ALL ages of RBCs", "Causes high-level parasitemia (vs. only young/old RBCs for other spp.)"),
        ("2. PfEMP1 on RBC surface knobs", "Binds ICAM-1, VCAM-1, CD36, E-selectin on endothelium → SEQUESTRATION in capillaries → blocks blood flow → cerebral malaria"),
        ("3. Rosette formation", "Infected RBCs clump together, worsening blockage"),
        ("4. No hypnozoites", "No relapse, but high acute parasitemia"),
        ("5. Antigenic variation", "Switches PfEMP1 variants each generation → escapes antibody response"),
    ]
    E += comparison_table(["Mechanism", "Effect"],
                          virulence,
                          col_widths=[4.5*cm, 10*cm],
                          header_bg=C_RED)

    E += subsection("FEVER PERIODICITY", C_ORANGE)
    fever_data = [
        ("P. vivax / P. ovale", "Every 48 hours", "Benign tertian malaria"),
        ("P. malariae", "Every 72 hours", "Quartan malaria"),
        ("P. falciparum", "Irregular / every 36-48h", "Malignant tertian malaria (most dangerous)"),
        ("P. knowlesi", "Every 24 hours", "Quotidian / potentially severe"),
    ]
    E += comparison_table(["Species", "Periodicity", "Type"],
                          fever_data, header_bg=C_ORANGE)

    E += subsection("MORPHOLOGY — Organ Changes", C_MED_BLUE)
    morphology_data = [
        ("SPLEEN", "Splenomegaly (may exceed 1000g), gray-black hemozoin pigment, red pulp congestion+hyperplasia; chronic → fibrotic, brittle, thick capsule"),
        ("LIVER", "Enlarged, pigmented; Kupffer cells laden with malarial pigment, parasitized RBCs, cellular debris"),
        ("BRAIN\n(P. falciparum)", "Vessels PLUGGED with parasitized RBCs; ring hemorrhages; Dürck granuloma (malarial granuloma); neuronal degeneration; focal ischemic softening"),
        ("KIDNEY", "Enlarged, congested; malarial pigment in glomeruli; hemoglobin casts in tubules (Blackwater fever = massive hemolysis + hemoglobinuria)"),
        ("BONE MARROW / LYMPH NODES", "Pigmented phagocytic cells; hemozoin pigment throughout"),
        ("BLOOD SMEAR\n(Diagnostic)", "Giemsa stain: ring trophozoites, schizonts, gametocytes inside RBCs. Ring forms with double chromatin dot = P. falciparum"),
    ]
    E += comparison_table(["Organ", "Findings"],
                          morphology_data,
                          col_widths=[3.5*cm, 11*cm],
                          header_bg=C_MED_BLUE)

    E += mnemonic_box("Plasmodium species",
        ["'Fever Very Often Makes People Sick'",
         "F = Falciparum  |  V = Vivax  |  O = Ovale  |  M = Malariae  |  P = P. knowlesi  |  S = Sporozoite entry"],
        bg=C_LIGHT_RED, border=C_RED)

    E += mnemonic_box("P. falciparum virulence — 'SCAR'",
        ["S = Sequestration (PfEMP1 binds endothelium)",
         "C = Can infect all age RBCs",
         "A = Antigenic variation (escapes immunity)",
         "R = Rosette formation"],
        bg=C_LIGHT_ORANGE, border=C_ORANGE)

    E.append(key_fact("Diagnostic test = Giemsa-stained peripheral blood smear. Dürck granuloma = pathognomonic of cerebral malaria."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 2 — CYSTICERCOSIS
# ────────────────────────────────────────────────────────────────────────────
def build_cysticercosis():
    E = []
    E += section_banner("CYSTICERCOSIS", 2, C_PURPLE)

    E.append(Paragraph(
        "<b>Definition:</b> Disease caused by <b>larvae (cysticercus)</b> of <i>Taenia solium</i> "
        "(pork tapeworm) when HUMANS act as the <b>INTERMEDIATE HOST</b>.", S_BODY))
    E.append(Spacer(1, 0.15*cm))

    host_data = [
        ("NORMAL life cycle", "Pig = Intermediate host (harbors cysticercus)\nHuman = Definitive host (harbors adult tapeworm in intestine)"),
        ("CYSTICERCOSIS", "HUMAN = Intermediate host (ingests eggs, develops cysticerci in tissues)"),
    ]
    E += comparison_table(["Condition", "Host Role"], host_data,
                          col_widths=[4.5*cm, 10*cm], header_bg=C_PURPLE)

    E += subsection("ETIOPATHOGENESIS", C_PURPLE)
    patho = [
        "  Human ingests T. solium EGGS (contaminated food/water/fecal-oral route)",
        "        ↓",
        "  Eggs hatch in intestine → ONCOSPHERES (hexacanth embryos with 6 hooklets)",
        "        ↓",
        "  Oncospheres penetrate intestinal wall → enter bloodstream",
        "        ↓",
        "  Haematogenous dissemination to TISSUES",
        "        ↓",
        "  Develop into CYSTICERCI (fluid-filled cysts with invaginated scolex)",
        "        ↓",
        "  PREFERRED SITES: Brain, Subcutaneous tissue, Eye, Skeletal muscle, Heart, Liver",
        "        ↓",
        "  ALIVE CYST → minimal inflammation (immune evasion by cyst)",
        "  DYING/DEAD CYST → intense inflammatory response → granuloma → calcification",
    ]
    E.append(DiagramBox(patho, bg=C_LIGHT_PURPLE, border=C_PURPLE))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("CLINICAL FEATURES BY SITE", C_MED_BLUE)
    clinical = [
        ("Neurocysticercosis (NCC)", "Most dangerous; seizures (most common cause of acquired epilepsy in endemic areas), headache, raised ICP, hydrocephalus, focal neurological deficits"),
        ("Ocular cysticercosis", "Floaters, visual disturbances, blindness (subretinal/vitreous cyst)"),
        ("Subcutaneous", "Palpable, non-tender nodules; calcify on X-ray"),
        ("Muscular", "Pseudohypertrophy of muscles; calcified cysts on imaging"),
    ]
    E += comparison_table(["Site", "Manifestations"], clinical,
                          col_widths=[4*cm, 10.5*cm], header_bg=C_MED_BLUE)

    E += subsection("MORPHOLOGY", C_PURPLE)
    E.append(Paragraph("<b>GROSS FEATURES:</b>", S_SUBSECTION))
    gross = [
        "Round/oval translucent fluid-filled cyst, 0.5–2 cm (up to 20 cm in racemose form)",
        "White, glistening wall; SCOLEX visible as white nodule inside",
        "RACEMOSE variant: grapelike cluster, no scolex, found in cisterns/ventricles of brain",
        "Calcified cysts visible on plain X-ray as 'puffed rice' calcifications (in muscles)",
    ]
    for g in gross:
        E.append(bp(g))

    E.append(Spacer(1, 0.15*cm))
    E.append(Paragraph("<b>MICROSCOPIC FEATURES (3 stages):</b>", S_SUBSECTION))
    micro_data = [
        ("VIABLE CYST", "Outer cuticular layer (lamellar, eosinophilic)\nMiddle cellular (reticular) layer\nInner germinal layer\nScolex with suckers and hooklets visible\nMinimal host inflammatory response"),
        ("DEGENERATING/\nDEAD CYST", "Cyst wall hyalinizes and breaks down\nINTENSE INFLAMMATION:\n• Eosinophils, neutrophils, lymphocytes\n• Plasma cells, macrophages\nGranuloma formation with giant cells"),
        ("CALCIFIED CYST\n(Healed)", "Dense calcification of dead scolex and wall\nFibrosis/gliosis surrounding (in brain)\n'Ghost' of cyst remains"),
    ]
    E += comparison_table(["Stage", "Microscopic Features"], micro_data,
                          col_widths=[4*cm, 10.5*cm], header_bg=C_PURPLE)

    E += mnemonic_box("Cysticercosis — 'CHEST'",
        ["C = Cyst (fluid-filled, with scolex)",
         "H = Hooklets on scolex (6 hooklets in oncosphere)",
         "E = Eggs ingested (fecal-oral route)",
         "S = Seizures (most common presentation — NCC)",
         "T = Taenia solium (pork tapeworm)"],
        bg=C_LIGHT_PURPLE, border=C_PURPLE)

    E.append(key_fact("Neurocysticercosis = most common cause of acquired epilepsy in developing countries. Diagnosis: CT/MRI + serology (EITB). Treatment: Albendazole + steroids."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 3 — LEPROSY ★★★
# ────────────────────────────────────────────────────────────────────────────
def build_leprosy():
    E = []
    E += section_banner("LEPROSY (Hansen Disease)  ★★★", 3, C_TEAL)

    E.append(Paragraph(
        "<b>Causative organism:</b> <i>Mycobacterium leprae</i> (and rarely M. lepromatosis). "
        "Slow progressive infection affecting <b>SKIN and PERIPHERAL NERVES</b>. "
        "Cannot be cultured in vitro. Proliferates best at <b>32–34°C</b> (cool tissues). "
        "Transmission via <b>human respiratory secretions</b>.", S_BODY))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("PATHOGENESIS", C_TEAL)
    patho = [
        "  M. leprae enters via respiratory tract",
        "        ↓",
        "  Taken up by DERMAL MACROPHAGES",
        "        ↓",
        "  Disseminates via blood → replicates in COOL TISSUES (skin, extremities, peripheral nerves)",
        "  PGL-1 lipid: invasion of host cells   |   Inhibits mitochondrial energy metabolism",
        "        ↓",
        "       HOST IMMUNE RESPONSE determines disease pattern:",
        "        ↙                                            ↘",
        "   STRONG Th1                                   WEAK Th1",
        "  (IL-2, IFN-γ, Th17)                       (Th2/Reg-T dominant)",
        "        ↓                                            ↓",
        "  TUBERCULOID LEPROSY                       LEPROMATOUS LEPROSY",
        "  (Paucibacillary)                          (Multibacillary)",
        "  Granulomas present                        No granulomas",
        "  Low bacterial load                        High bacterial load",
        "  Nerve destruction dominant                Diffuse skin/nerve invasion",
    ]
    E.append(DiagramBox(patho, bg=C_LIGHT_TEAL, border=C_TEAL))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("CLASSIFICATION", C_TEAL)
    E.append(Paragraph("<b>Ridley-Jopling Classification (Spectrum):</b>", S_SUBSECTION))
    spectrum_lines = [
        "  TUBERCULOID (TT) ←── BT ──── BB ──── BL ───→ LEPROMATOUS (LL)",
        "  |←────────── STRONG IMMUNITY ──────── WEAK IMMUNITY ──────────→|",
        "  |←───────── PAUCIBACILLARY ──────── MULTIBACILLARY ───────────→|",
        "  |←──── FEW SKIN LESIONS ────────── MANY SKIN LESIONS ─────────→|",
    ]
    E.append(DiagramBox(spectrum_lines, bg=C_LIGHT_TEAL, border=C_TEAL))
    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>WHO Classification (Clinical Use):</b>", S_SUBSECTION))
    who_data = [
        ("Paucibacillary (PB)", "1–5 skin lesions", "Tuberculoid / Borderline-T", "MDT 6 months"),
        ("Multibacillary (MB)", ">5 skin lesions", "Lepromatous / Borderline-L", "MDT 12 months"),
    ]
    E += comparison_table(["WHO Type", "Skin Lesions", "Ridley-Jopling", "MDT Duration"],
                          who_data, header_bg=C_TEAL)

    E += subsection("IMMUNOLOGY COMPARISON", C_MED_BLUE)
    immune_data = [
        ("T-cell response", "Strong Th1 (IFN-γ, IL-2)", "Weak Th1 / Th2 dominant"),
        ("Bacterial load", "Low (paucibacillary)", "High (multibacillary)"),
        ("Granulomas", "Well-formed, like TB", "Absent — lepra cells instead"),
        ("Antibodies", "Low", "High (but NOT protective — may cause vasculitis)"),
        ("Cell-mediated immunity", "Intact", "Deficient"),
        ("Lepromin test", "POSITIVE", "NEGATIVE"),
        ("Nerve involvement", "Asymmetric, destructive", "Symmetric, less inflamed"),
        ("Skin lesions", "Few, hypopigmented, anesthetic", "Multiple, nodular, leonine"),
    ]
    E += comparison_table(["Feature", "Tuberculoid", "Lepromatous"],
                          immune_data,
                          col_widths=[4.5*cm, 5.5*cm, 4.5*cm],
                          header_bg=C_MED_BLUE)

    E += subsection("GROSS (CLINICAL) FINDINGS", C_TEAL)
    E.append(Paragraph("<b>Tuberculoid Leprosy:</b>", S_KEY))
    tub_clinical = [
        "Flat red lesions → enlarge with indurated, elevated, hyperpigmented margins + depressed pale centres (central healing)",
        "ASYMMETRIC large peripheral nerve involvement (ulnar, radial, peroneal, great auricular)",
        "Skin ANESTHESIA (destroyed nerves)",
        "Muscle atrophy, contractures, chronic ulcers, autoamputation of digits",
        "Facial nerve palsy → eyelid paralysis → keratitis, corneal ulcers",
    ]
    for t in tub_clinical:
        E.append(bp(t))

    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>Lepromatous Leprosy:</b>", S_KEY))
    lep_clinical = [
        "SYMMETRIC skin thickening; macular, papular, or NODULAR lesions on face, ears, wrists, elbows, knees",
        "Nodules coalesce → LEONINE FACIES (lion-like face)",
        "Saddle-nose deformity (nasal bone destruction)",
        "Hyposthetic / anesthetic skin lesions",
        "Bacilli-laden nasal discharge",
        "Testes: extensive involvement → destruction of seminiferous tubules → sterility + gynecomastia",
        "Symmetric nerve invasion (ulnar, peroneal) with minimal inflammation",
    ]
    for l in lep_clinical:
        E.append(bp(l))

    E += subsection("MICROSCOPIC FINDINGS", C_TEAL)
    micro_data = [
        ("TUBERCULOID", "Well-formed GRANULOMAS (like TB)\nEpithelioid cells + Langhans giant cells\nDense lymphocytic infiltrate\nGranulomas enclose & DESTROY NERVES\nBacilli ABSENT / very rare (AFB -ve)\nName = PAUCIBACILLARY"),
        ("LEPROMATOUS", "Large aggregates of LIPID-LADEN MACROPHAGES = LEPRA CELLS (Virchow cells)\nLepra cells packed with GLOBI (masses of AFB)\nGlobi look like 'cigar bundles' on AFB stain\nNO granulomas (CMI absent)\nGRENZ ZONE (clear subepidermal zone)\nBacilli abundant — MULTIBACILLARY\nTestes: destruction of seminiferous tubules"),
    ]
    E += comparison_table(["Type", "Microscopic Features"], micro_data,
                          col_widths=[3.5*cm, 11*cm], header_bg=C_TEAL)

    # Lepra cell diagram
    lepra_cell = [
        "          LEPRA CELL DIAGRAM (Lepromatous Leprosy)",
        "    ┌─────────────────────────────────────────────┐",
        "    │          MACROPHAGE (Virchow Cell)           │",
        "    │                                             │",
        "    │   [====AFB====]  [====AFB====]  [==AFB==]   │",
        "    │      GLOBUS 1       GLOBUS 2     GLOBUS 3   │",
        "    │    (masses of acid-fast bacilli in bundles) │",
        "    │                                             │",
        "    │          FOAMY CYTOPLASM (lipid-filled)      │",
        "    │                  [ NUCLEUS ]                │",
        "    └─────────────────────────────────────────────┘",
        "    Stain: Ziehl-Neelsen (AFB) — red bacilli on blue bg",
    ]
    E.append(DiagramBox(lepra_cell, bg=C_LIGHT_TEAL, border=C_TEAL))
    E.append(Spacer(1, 0.15*cm))

    # Langhans giant cell diagram
    lang_cell = [
        "     LANGHANS GIANT CELL DIAGRAM (Tuberculoid / TB)",
        "    ┌──────────────────────────────────────────────┐",
        "    │                                              │",
        "    │         O  O  O  O  O                        │",
        "    │      O                    O                  │",
        "    │                                              │",
        "    │        LARGE PINK CYTOPLASM                  │",
        "    │      (fused epithelioid cells)               │",
        "    │                                              │",
        "    │      O                    O                  │",
        "    │         O  O  O  O  O                        │",
        "    │   Nuclei arranged in HORSESHOE / PERIPHERAL  │",
        "    │             PATTERN (key feature)            │",
        "    └──────────────────────────────────────────────┘",
    ]
    E.append(DiagramBox(lang_cell, bg=C_LIGHT_BLUE, border=C_MED_BLUE))
    E.append(Spacer(1, 0.15*cm))

    E += mnemonic_box("Types of Leprosy — 'TT BB LL (Two Ts, Two Bs, Two Ls)'",
        ["TT = Tuberculoid (one extreme)",
         "BB = Borderline (middle)",
         "LL = Lepromatous (other extreme)",
         "BT = Borderline Tuberculoid  |  BL = Borderline Lepromatous"],
        bg=C_LIGHT_TEAL, border=C_TEAL)

    E += mnemonic_box("LEPRA CELL vs EPITHELIOID CELL — 'Lepra = Lipid-laden, Lepromatous'",
        ["Lepra Cell = Lipid-laden macrophage = Lepromatous = Low immunity = Lots of bacilli",
         "Epithelioid Cell = Elongated macrophage = TB granuloma / Tuberculoid leprosy"],
        bg=C_LIGHT_YELLOW, border=C_YELLOW)

    E.append(key_fact("Leonine facies + saddle nose = Lepromatous leprosy. Anesthetic lesion with thickened peripheral nerve = Tuberculoid leprosy. Most disfiguring = Lepromatous."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 4 — VIRAL & FUNGAL INFECTIONS
# ────────────────────────────────────────────────────────────────────────────
def build_viral_fungal():
    E = []
    E += section_banner("COMMON VIRAL & FUNGAL INFECTIONS", 4, C_ORANGE)

    # VIRAL
    E += subsection("COMMON VIRAL INFECTIONS", C_ORANGE)

    viral_data = [
        ("INFLUENZA", "Type A, B, C\n(RNA virus, 8 segments)\nH and N surface proteins",
         "Antigenic drift (mutations) = epidemics\nAntigenic shift (recombination with animal virus) = PANDEMICS",
         "Diffuse alveolar damage (DAD)\nHyaline membranes\nInterstitial pneumonitis"),
        ("SARS-CoV-2\n(COVID-19)", "Enveloped +ve sense RNA\nSpike protein binds ACE2 on type II alveolar cells + nasopharynx",
         "Viral replication → immune overactivation\n'Cytokine storm'\nCoagulopathy, microthrombi",
         "DAD with hyaline membranes\nMicrothrombi in vessels\nMyocarditis, CNS infiltrates"),
        ("HERPES SIMPLEX\n(HSV-1/2)", "DNA virus (Herpesviridae)\nLatent in ganglia → reactivation",
         "Cell-to-cell spread\nImmune evasion via latency",
         "Cowdry type A intranuclear inclusions\nMultinucleated giant cells with 'ground-glass' nuclei"),
        ("CMV", "Large DNA virus\nDangerous in immunocompromised\n(AIDS, transplant patients)",
         "Reactivation when CMI falls",
         "OWL-EYE intranuclear inclusions (large, purple, surrounded by halo)\nSmaller cytoplasmic inclusions"),
        ("MEASLES\n(Rubeola)", "RNA Paramyxovirus\nDroplet transmission",
         "Enters via respiratory epithelium\nViraemia → dissemination",
         "Warthin-Finkeldey multinucleated giant cells (in lymphoid tissue)\nKoplik spots (buccal mucosa)\nSquamous metaplasia of bronchial epithelium"),
        ("EBV", "DNA Herpesvirus\nB-cell tropism",
         "EBV infects B cells via CD21\nPolyclonal B-cell proliferation",
         "Atypical lymphocytes (Downey cells)\nReactive germinal centres\nAssociated with Burkitt lymphoma, nasopharyngeal carcinoma"),
    ]
    E += comparison_table(
        ["Virus", "Features", "Pathogenesis", "Histology"],
        viral_data,
        col_widths=[2.5*cm, 4*cm, 4.5*cm, 3.5*cm],
        header_bg=C_ORANGE)

    E += subsection("VIRAL INCLUSION BODIES — EASY TABLE", C_RED)
    inclusion_data = [
        ("Cowdry type A (intranuclear)", "HSV, CMV, Yellow Fever", "Large eosinophilic, marginated chromatin"),
        ("Owl-eye inclusions (intranuclear)", "CMV", "Large purple nuclear inclusion + smaller cytoplasmic ones"),
        ("Negri bodies (cytoplasmic)", "Rabies", "Eosinophilic inclusions in neurons (hippocampus, cerebellum)"),
        ("Warthin-Finkeldey giant cells", "Measles", "Multinucleated giant cells in lymphoid tissue"),
        ("Henderson-Patterson bodies", "Molluscum contagiosum", "Large cytoplasmic inclusions"),
        ("Guarnieri bodies (cytoplasmic)", "Smallpox / Vaccinia", "Viral factories in cytoplasm"),
    ]
    E += comparison_table(["Inclusion Body", "Virus", "Description"],
                          inclusion_data,
                          col_widths=[4.5*cm, 3.5*cm, 6.5*cm],
                          header_bg=C_RED)

    # FUNGAL
    E += subsection("COMMON FUNGAL INFECTIONS", C_GREEN)
    fungal_data = [
        ("CANDIDA ALBICANS\n(Candidiasis)", "Pseudohyphae + budding yeast\nPAS / GMS stain",
         "Immunocompromise (neutropenia, AIDS)\nDiabetes, broad-spectrum antibiotics",
         "Superficial: Thrush, vaginitis\nDeep: esophageal, systemic\nNeutrophilic infiltrate with pseudohyphae invading tissue"),
        ("ASPERGILLUS\n(Aspergillosis)", "SEPTATE hyphae\n45° ACUTE ANGLE branching\nGMS / H&E stain",
         "Immunocompromised (neutropenic)\nPre-existing lung cavities\nAtopic patients (ABPA)",
         "3 forms: 1) Aspergilloma (fungal ball in cavity)\n2) ABPA (allergic, eosinophilic)\n3) Invasive: angioinvasion → infarction + hemorrhage"),
        ("CRYPTOCOCCUS\nNEOFORMANS", "Encapsulated yeast\nIndia ink: CLEAR HALO (capsule)\nMucicarmine stain: magenta capsule",
         "Inhalation from pigeon droppings\nOpportunistic in AIDS (CD4 < 200)",
         "Soap-bubble lesions in brain (gelatinous pseudocysts)\nMinimal inflammation in AIDS\nMeningoencephalitis\n'Gumball' appearance on Mucicarmine"),
        ("MUCOR / RHIZOPUS\n(Mucormycosis)", "BROAD non-septate hyphae\n90° RIGHT ANGLE branching\nGMS stain",
         "Diabetics (DKA) — rhinocerebral form\nNeutropenic patients — pulmonary form",
         "Angioinvasion → thrombosis → tissue INFARCTION\nRhinocerebral: orbit, palate, sinuses\nBlack necrotic eschars"),
        ("HISTOPLASMA\nCAPSULATUM", "Small intracellular yeast (2–4 μm)\nInside macrophages\nGMS / PAS stain",
         "Ohio/Mississippi river valleys\nInhalation of bird/bat droppings",
         "Mimics TB: granulomas, caseous necrosis, calcification\nTiny yeast inside macrophages\nDisseminated in AIDS (hepatosplenomegaly)"),
        ("PNEUMOCYSTIS\n(PCP)", "Cysts with 8 intracystic bodies\nGMS stain: dark cysts\nSilver stain",
         "Opportunistic: AIDS (CD4 < 200)\nImmunocompromised (transplant)",
         "Interstitial pneumonia\nFrothy, pink alveolar exudate ('cotton-candy' or 'honeycomb')\nNo granulomas"),
    ]
    E += comparison_table(
        ["Fungus", "Morphology/Stain", "Risk Factors", "Pathology"],
        fungal_data,
        col_widths=[2.8*cm, 3.5*cm, 3.5*cm, 4.7*cm],
        header_bg=C_GREEN)

    E += mnemonic_box("Fungal Hyphae — 'SANE vs BROAD'",
        ["SANE = Septate Acute aNgle = Aspergillus (45° branching)",
         "BROAD = Broad Right-angle Obtuse Angle Dimorphic = Mucor (90° branching, non-septate)"],
        bg=C_LIGHT_GREEN, border=C_GREEN)

    E += mnemonic_box("India Ink Stain — 'Crypto needs a CAP'",
        ["Cryptococcus = India Ink = Clear halo (Clear = Capsule = Crypto)"],
        bg=C_LIGHT_GREEN, border=C_GREEN)

    E.append(key_fact("Invasive Aspergillosis = angioinvasion (like Mucor). Mucor = Right angle, non-septate. Aspergillus = 45° acute angle, septate. CMV = Owl-eye. HSV = Cowdry A."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 5 — PRIMARY TUBERCULOSIS ★
# ────────────────────────────────────────────────────────────────────────────
def build_primary_tb():
    E = []
    E += section_banner("PRIMARY TUBERCULOSIS  ★", 5, C_DARK_BLUE)

    E.append(Paragraph(
        "<b>Definition:</b> Form of TB that develops in a <b>previously unexposed and unsensitized</b> individual. "
        "About <b>5%</b> of newly infected individuals develop significant disease. "
        "Caused by <i>Mycobacterium tuberculosis</i> — acid-fast bacillus (AFB), transmitted by <b>respiratory droplets</b>.", S_BODY))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("PATHOGENESIS", C_DARK_BLUE)
    patho = [
        " INHALATION of M. tuberculosis droplets",
        "       ↓",
        " PHASE 1 — INNATE RESPONSE (first ~3 weeks) — ASYMPTOMATIC",
        " Bacilli reach alveoli → phagocytosed by ALVEOLAR MACROPHAGES",
        " M. tb prevents phagolysosome fusion → survives inside macrophages",
        " Bacilli replicate → macrophages release chemokines → more monocytes recruited",
        " DENDRITIC CELLS carry mycobacterial antigens to HILAR LYMPH NODES",
        "       ↓",
        " PHASE 2 — ADAPTIVE IMMUNITY (~3 weeks) — Th1 RESPONSE",
        " DCs present antigens → Th1 cell differentiation (requires IL-12, IL-18)",
        " Th1 cells produce IFN-γ (CRITICAL mediator)",
        "       ↓",
        " IFN-γ activates macrophages → 3 mechanisms to kill bacteria:",
        "   1. Produces nitric oxide (NO) + reactive oxygen species (ROS)",
        "   2. Mobilizes defensins (cathelicidin)",
        "   3. Stimulates AUTOPHAGY (sequesters & destroys bacilli)",
        "       ↓",
        " Activated macrophages → EPITHELIOID HISTIOCYTES",
        "       ↓",
        " GRANULOMA FORMATION + CASEOUS NECROSIS",
        "       ↓",
        " 95%: Infection CONTAINED → Ghon complex heals → Ranke complex",
        " 5%: Progressive Primary TB (immunocompromised, HIV, malnutrition)",
    ]
    E.append(DiagramBox(patho, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("COMMON SITES OF PRIMARY TB", C_DARK_BLUE)
    sites_data = [
        ("1st", "LUNGS (>95%)", "Subpleural; lower part of UPPER LOBE or upper part of LOWER LOBE (close to pleura)"),
        ("2nd", "INTESTINE (ileum)", "From ingestion of M. bovis (infected milk) — rare now"),
        ("3rd", "TONSIL / PHARYNX", "Very rare; from oral entry"),
        ("4th", "SKIN", "Primary inoculation TB (rare)"),
    ]
    E += comparison_table(["Rank", "Site", "Notes"],
                          sites_data,
                          col_widths=[1.5*cm, 4*cm, 9*cm],
                          header_bg=C_DARK_BLUE)

    E += subsection("EVOLUTION OF THE TUBERCLE (GRANULOMA) — 5 STAGES", C_MED_BLUE)
    stages = [
        "STAGE 1 — INITIAL MACROPHAGE ACCUMULATION",
        "  Local accumulation of macrophages (HISTIOCYTES) at site of infection",
        "",
        "STAGE 2 — EPITHELIOID GRANULOMA",
        "  Macrophages transform into EPITHELIOID CELLS",
        "  (elongated, pink cytoplasm, 'footprint-shaped' nuclei — look like epithelium but ARE macrophages)",
        "  Surrounded by LYMPHOCYTES (mainly CD4+ Th1 cells)",
        "",
        "STAGE 3 — LANGHANS GIANT CELL FORMATION",
        "  Epithelioid cells fuse → LANGHANS GIANT CELLS",
        "  KEY FEATURE: Nuclei arranged in HORSESHOE / PERIPHERAL pattern",
        "",
        "STAGE 4 — CASEOUS NECROSIS",
        "  Centre becomes CASEOUS = cheese-like, amorphous, eosinophilic material",
        "  Due to DTH (delayed-type hypersensitivity) reaction",
        "  Caseous necrosis = PATHOGNOMONIC of TB",
        "",
        "STAGE 5 — RESOLUTION OR PROGRESSION",
        "  A) Fibrosis → Calcification (Ranke complex) — HEALING",
        "  B) Liquefaction → Cavity formation — SECONDARY TB",
    ]
    E.append(DiagramBox(stages, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))
    E.append(Spacer(1, 0.2*cm))

    # Tubercle diagram
    tubercle = [
        "        TB GRANULOMA (TUBERCLE) — DIAGRAM",
        "   ┌──────────────────────────────────────────────────┐",
        "   │  ┌────────────────────────────────────────────┐  │",
        "   │  │  ~~~ CASEOUS NECROSIS (CENTRE) ~~~         │  │",
        "   │  │  ~~~  (amorphous, cheese-like,   ~~~       │  │",
        "   │  │  ~~~   eosinophilic material)    ~~~       │  │",
        "   │  └────────────────────────────────────────────┘  │",
        "   │  [Epi][Epi]  LANGHANS GIANT CELL  [Epi][Epi]     │",
        "   │              O  O  O  O  O                        │",
        "   │           O (horseshoe nuclei) O                  │",
        "   │              O  O  O  O  O                        │",
        "   │  [Lym][Lym][Epi][Epi][Epi][Lym][Lym][Lym]       │",
        "   │       Lymphocytes surround epithelioid cells      │",
        "   │  === FIBROUS CAPSULE (outer layer) ===            │",
        "   └──────────────────────────────────────────────────┘",
        "   Epi = Epithelioid cell  |  Lym = Lymphocyte",
    ]
    E.append(DiagramBox(tubercle, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("PRIMARY COMPLEX — COMPONENTS  ★", C_RED)
    E.append(Paragraph(
        "The <b>Ghon's Complex (Primary Complex)</b> = THREE components:", S_BODY))

    complex_data = [
        ("1. GHON FOCUS\n(Parenchymal lesion)", "1–1.5 cm gray-white area of consolidation\nSubpleural; lower part of upper lobe / upper part of lower lobe\nCentre → caseous necrosis\nSEE: Parenchymal component"),
        ("2. LYMPHANGITIS\n(Connecting vessel)", "Inflammatory thickening of lymphatic channels\nBetween Ghon focus and hilar lymph nodes\nLinks parenchymal + nodal components"),
        ("3. HILAR LYMPHADENOPATHY\n(Nodal component)", "Caseous enlargement of regional (hilar/mediastinal) lymph nodes\nUsually MORE prominent than parenchymal lesion in children\nNodal caseous necrosis\nSEE: Nodal component"),
    ]
    E += comparison_table(["Component", "Features"],
                          complex_data,
                          col_widths=[4.5*cm, 10*cm],
                          header_bg=C_RED)

    complex_diag = [
        "    PRIMARY COMPLEX DIAGRAM",
        "    ┌────────────────────────────────────────────────┐",
        "    │                                                │",
        "    │  [LUNG PARENCHYMA]                             │",
        "    │                                                │",
        "    │    ●  GHON FOCUS (1-1.5 cm, subpleural)       │",
        "    │    |  (caseous centre, gray-white)             │",
        "    │    |                                           │",
        "    │    | ← LYMPHANGITIS (lymphatic channels)       │",
        "    │    |                                           │",
        "    │    ●  HILAR LYMPH NODES (caseous, enlarged)    │",
        "    │       (often larger than Ghon focus)           │",
        "    │                                                │",
        "    │    Together = GHON'S COMPLEX (Primary Complex) │",
        "    └────────────────────────────────────────────────┘",
    ]
    E.append(DiagramBox(complex_diag, bg=C_LIGHT_BLUE, border=C_DARK_BLUE))

    E += mnemonic_box("Primary Complex = 'GHon FLH' (Focus + Lymphangitis + Hilum)",
        ["G = Ghon Focus (parenchymal lesion in lung)",
         "L = Lymphangitis (connecting lymphatics)",
         "H = Hilar lymphadenopathy (nodal lesion)",
         "All 3 together = Ghon Complex / Primary Complex"],
        bg=C_LIGHT_BLUE, border=C_DARK_BLUE)

    E.append(key_fact("Ghon Focus = parenchymal lesion only. Ghon Complex = Focus + Lymphangitis + Lymphadenitis. Ranke Complex = Calcified Ghon Complex (visible on X-ray)."))
    E.append(PageBreak())
    return E


# ────────────────────────────────────────────────────────────────────────────
# TOPIC 6 — GHON'S COMPLEX ★★★
# ────────────────────────────────────────────────────────────────────────────
def build_ghon_complex():
    E = []
    E += section_banner("GHON'S COMPLEX — Gross, Microscopic & Fate  ★★★", 6, C_GREEN)

    E.append(Paragraph(
        "<b>Ghon's Complex</b> = Ghon Focus (parenchymal lung lesion) + Lymphangitis + "
        "Caseous hilar lymphadenopathy in PRIMARY TUBERCULOSIS. "
        "Named after Anton Ghon (1912).", S_BODY))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("GROSS FEATURES", C_GREEN)
    E.append(Paragraph("<b>A. Ghon Focus (Parenchymal Lesion):</b>", S_SUBSECTION))
    gross_focus = [
        "Location: Subpleural; lower part of UPPER LOBE or upper part of LOWER LOBE",
        "Size: 1–1.5 cm",
        "Colour: Gray-white area of consolidation",
        "Centre: Caseous necrosis — yellow-white, cheese-like, friable material",
        "Surrounding: Zone of grey consolidation (solid pneumonia)",
        "Pleural surface: May show fibrinous exudate / pleural adhesions",
    ]
    for g in gross_focus:
        E.append(bp(g))

    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>B. Hilar Lymph Nodes:</b>", S_SUBSECTION))
    gross_nodes = [
        "Enlarged, discrete or matted together at hilum",
        "Cut section: Yellow-white caseous material (more extensive than Ghon focus)",
        "In children: nodal lesion often LARGER than parenchymal lesion",
        "Periadenitis: nodes matted to adjacent structures",
    ]
    for g in gross_nodes:
        E.append(bp(g))

    E.append(Spacer(1, 0.1*cm))
    E.append(Paragraph("<b>C. Lymphatics (Lymphangitis):</b>", S_SUBSECTION))
    E.append(bp("Thickened, visible lymphatic channels between Ghon focus and hilar nodes"))
    E.append(bp("May show 'beaded' appearance due to granulomas along the lymphatic channel"))

    E += subsection("MICROSCOPIC FEATURES", C_GREEN)
    micro_table = [
        ("AT GHON FOCUS", "1. CASEOUS NECROSIS at centre:\n   • Amorphous, granular, eosinophilic material\n   • Ghost cell outlines ('tombstone cells')\n   • Loss of all cellular architecture\n   • No living cells within necrotic core\n\n2. GRANULOMATOUS INFLAMMATION surrounding necrosis:\n   • EPITHELIOID CELLS (activated macrophages)\n     - Elongated, pale pink cytoplasm\n     - 'Footprint-shaped' / oblong nuclei\n   • LANGHANS GIANT CELLS\n     - Peripheral / horseshoe nucleus arrangement\n   • LYMPHOCYTES (mainly CD4+ T cells)\n   • Occasional plasma cells and fibroblasts\n\n3. FIBROUS CAPSULE (outer rim):\n   • Fibroblasts + collagen encapsulating granuloma\n\n4. AFB STAIN (Ziehl-Neelsen):\n   • Red acid-fast bacilli (scanty in primary TB)\n   • More abundant in immunocompromised"),
        ("AT HILAR LYMPH NODES", "• Similar caseating granulomas\n• Effacement of normal nodal architecture\n• Caseous necrosis (may be more extensive)\n• Epithelioid cells + Langhans giant cells\n• Peripheral lymphocyte rim\n• Periadenitis: inflammatory capsular thickening"),
        ("IN IMMUNOCOMPROMISED\n(HIV, CD4 < 200)", "• Granulomas ABSENT\n• Sheets of foamy macrophages with NUMEROUS bacilli\n• No caseous necrosis\n• AFB stain: heavily loaded with acid-fast bacilli\n• = Progressive Primary TB pattern"),
    ]
    E += comparison_table(["Site", "Microscopic Features"],
                          micro_table,
                          col_widths=[3.5*cm, 11*cm],
                          header_bg=C_GREEN)

    # Microscopy diagram
    micro_diag = [
        "    MICROSCOPY OF GHON FOCUS — DIAGRAM",
        "    ┌────────────────────────────────────────────────────┐",
        "    │                                                    │",
        "    │  [FIBROUS CAPSULE] ─────────────────────────────── │",
        "    │                                                    │",
        "    │  Lymphocytes  [L][L][L][L][L][L][L][L]            │",
        "    │                                                    │",
        "    │  Epithelioid cells: [Epi][Epi][Epi][Epi][Epi]     │",
        "    │                                                    │",
        "    │  Langhans Giant Cell:  O O O O O O                 │",
        "    │                       O  LARGE   O  (horseshoe    │",
        "    │                       O  CELL    O   nuclei at    │",
        "    │                       O O O O O O    periphery)   │",
        "    │                                                    │",
        "    │  CASEOUS NECROSIS: ~~~ amorphous ~~~ (centre)      │",
        "    │  ~~~ eosinophilic granular debris ~~~ no cells ~~~ │",
        "    │                                                    │",
        "    └────────────────────────────────────────────────────┘",
    ]
    E.append(DiagramBox(micro_diag, bg=C_LIGHT_GREEN, border=C_GREEN))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("FATE OF GHON'S COMPLEX  ★★★", C_RED)
    fate_diag = [
        "                    GHON'S COMPLEX",
        "                          |",
        "            ┌─────────────┴─────────────┐",
        "         95%                           5%",
        "    Normal immunity               Immunocompromised",
        "         |                             |",
        "         ↓                             ↓",
        "     HEALING                 PROGRESSIVE PRIMARY TB",
        "         |                             |",
        "    ┌────┴────┐               Caseous pneumonia",
        "    ↓         ↓               Miliary spread",
        " FIBROSIS  CALCIFICATION      Tuberculous meningitis",
        "            ↓",
        "       RANKE COMPLEX",
        "   (visible on chest X-ray",
        "    as calcified nodule)",
        "         |",
        "         ↓ (if immunity wanes years later)",
        "    REACTIVATION → SECONDARY TB",
        "    (apical lung cavity)",
    ]
    E.append(DiagramBox(fate_diag, bg=C_LIGHT_GREEN, border=C_GREEN))
    E.append(Spacer(1, 0.2*cm))

    E += subsection("FATE — DETAILED TABLE", C_GREEN)
    fate_data = [
        ("RESOLUTION (95%)", "Immune containment via Th1/IFN-γ", "Fibrosis → Calcification", "Ranke complex on X-ray"),
        ("PROGRESSIVE PRIMARY TB (5%)", "Immunocompromised, HIV, severe malnutrition", "Caseous pneumonia, lobar consolidation", "No granulomas in HIV"),
        ("MILIARY TB", "Haematogenous dissemination via erosion into blood vessel", "Millet-seed foci (1–2 mm) throughout ALL organs (lung, liver, spleen, kidney, brain)", "Classic 'snowstorm' on CXR"),
        ("TB MENINGITIS", "Haematogenous/lymphatic spread to meninges", "Subependymal granuloma ruptures into CSF spaces", "Basal exudate, vasculitis"),
        ("PLEURAL EFFUSION", "Delayed hypersensitivity reaction to TB antigens in pleural space", "Serous lymphocytic effusion", "Exudate, lymphocyte-rich"),
        ("REACTIVATION (Secondary TB)", "Waning immunity (years/decades later)", "Apical lung cavity; cavitation, fibrosis, spread", "AFB-positive sputum"),
    ]
    E += comparison_table(["Fate", "Mechanism", "Pathology", "Notes"],
                          fate_data,
                          col_widths=[3.5*cm, 4.5*cm, 4.5*cm, 2*cm],
                          header_bg=C_GREEN)

    E += subsection("KEY TERMINOLOGY COMPARISON", C_DARK_BLUE)
    terminology = [
        ("Ghon Focus", "Parenchymal lung lesion only (1–1.5 cm caseous nodule)"),
        ("Ghon Complex", "Ghon Focus + Lymphangitis + Hilar lymphadenopathy"),
        ("Ranke Complex", "CALCIFIED Ghon Complex (healed primary TB) — visible on X-ray"),
        ("Primary Complex", "Same as Ghon Complex (broader term)"),
        ("Miliary TB", "Haematogenous dissemination → millet-seed foci throughout body"),
        ("Secondary TB", "Reactivation TB in previously sensitized host — APICAL cavitation"),
    ]
    E += comparison_table(["Term", "Definition"],
                          terminology,
                          col_widths=[3.5*cm, 11*cm],
                          header_bg=C_DARK_BLUE)

    E += mnemonic_box("Fate of Ghon Complex — 'FRAME'",
        ["F = Fibrosis (heals with fibrosis)",
         "R = Ranke complex (calcified form, visible on X-ray)",
         "A = Activation (reactivation → secondary TB if immunity wanes)",
         "M = Miliary spread (haematogenous)",
         "E = Erosion into bronchus (spread to other lung areas) / Effusion"],
        bg=C_LIGHT_GREEN, border=C_GREEN)

    E += mnemonic_box("Granuloma vs Abscess — 'Granuloma = Contained; Abscess = Liquefied'",
        ["Granuloma (TB) = CASEOUS necrosis = dry, cheese-like, NO pus",
         "Abscess (Pyogenic) = LIQUEFACTIVE necrosis = pus, neutrophils",
         "Caseous necrosis = ONLY seen in TB (pathognomonic)"],
        bg=C_LIGHT_YELLOW, border=C_YELLOW)

    E.append(key_fact("MUHS favourite: List 5 fates of Ghon complex. Always include Ranke complex definition. Miliary TB = haematogenous spread with millet-seed lesions everywhere."))

    E.append(Spacer(1, 0.5*cm))
    E.append(divider(C_GREEN))
    E.append(Spacer(1, 0.3*cm))
    E.append(Paragraph("END OF REVISION NOTES", make_style('End',
        fontSize=12, textColor=C_MID_GREY, fontName='Helvetica-Bold',
        alignment=TA_CENTER)))
    E.append(Paragraph("Robbins, Cotran & Kumar — Pathologic Basis of Disease, 10e | Robbins & Kumar Basic Pathology",
        make_style('EndSub', fontSize=8.5, textColor=C_MID_GREY,
                   fontName='Helvetica-Oblique', alignment=TA_CENTER)))
    return E


# ── ASSEMBLE & BUILD ──────────────────────────────────────────────────────────
def build_pdf():
    os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True)
    doc = SimpleDocTemplate(
        OUTPUT_PATH,
        pagesize=A4,
        leftMargin=2*cm,
        rightMargin=2*cm,
        topMargin=2.2*cm,
        bottomMargin=1.8*cm,
        title="MUHS 2nd MBBS Pathology Rapid Revision",
        author="Robbins & Kumar"
    )

    all_elements = []
    all_elements += build_cover()
    all_elements += build_malaria()
    all_elements += build_cysticercosis()
    all_elements += build_leprosy()
    all_elements += build_viral_fungal()
    all_elements += build_primary_tb()
    all_elements += build_ghon_complex()

    doc.build(
        all_elements,
        onFirstPage=on_first_page,
        onLaterPages=on_later_pages
    )
    print(f"PDF successfully generated: {OUTPUT_PATH}")


if __name__ == "__main__":
    build_pdf()
Running Command

ls /home/daytona/workspace/muhs-study-guide/

Editing File

~/muhs-study-guide/generate_pdf.py

Error: String not found in file: '#!/usr/bin/env python3
"""
MUHS 2nd MBBS Pathology - Comprehensive Revision PDF
Topics: Malaria, Cysticercosis, Leprosy, Viral/Fungal Infections,
        Primary TB, Ghon's Complex
Based on Robbins & Kumar Pathology
"""'
Running Command

cat /home/daytona/workspace/muhs-study-guide/generate_pdf.py | head -5

PDF

Reading File
Running Command

ls /home/daytona/workspace/muhs-study-guide/

Writing File

~/muhs-study-guide/build_pathology_revision.py

#!/usr/bin/env python3
"""
MUHS 2nd MBBS Pathology - Comprehensive Revision PDF
6 Topics: Malaria | Cysticercosis | Leprosy | Viral+Fungal | Primary TB | Ghon Complex
Based on Robbins & Kumar Pathology
"""

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.platypus.flowables import Flowable
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
import os

OUT = "/home/daytona/workspace/muhs-study-guide/MUHS_Pathology_Rapid_Revision.pdf"
W = A4[0]
INNER_W = W - 4*cm  # usable text width

# ─── COLOURS ──────────────────────────────────────────────────────────────────
C = dict(
    navy    = colors.HexColor("#0f2d54"),
    blue    = colors.HexColor("#1a5fa8"),
    lblue   = colors.HexColor("#dbeafe"),
    teal    = colors.HexColor("#0f766e"),
    lteal   = colors.HexColor("#ccfbf1"),
    red     = colors.HexColor("#b91c1c"),
    lred    = colors.HexColor("#fee2e2"),
    orange  = colors.HexColor("#c2410c"),
    lorange = colors.HexColor("#ffedd5"),
    green   = colors.HexColor("#166534"),
    lgreen  = colors.HexColor("#dcfce7"),
    purple  = colors.HexColor("#6b21a8"),
    lpurple = colors.HexColor("#f3e8ff"),
    amber   = colors.HexColor("#92400e"),
    lamber  = colors.HexColor("#fef9c3"),
    dkgrey  = colors.HexColor("#1f2937"),
    grey    = colors.HexColor("#6b7280"),
    lgrey   = colors.HexColor("#f3f4f6"),
    mgrey   = colors.HexColor("#e5e7eb"),
    white   = colors.white,
    black   = colors.black,
)

# ─── STYLES ───────────────────────────────────────────────────────────────────
BASE = getSampleStyleSheet()

def S(name, **kw):
    parent = kw.pop('parent', 'Normal')
    return ParagraphStyle(name, parent=BASE[parent], **kw)

sBody    = S('sBody',    fontSize=9,   textColor=C['dkgrey'], leading=14,  spaceAfter=3, alignment=TA_JUSTIFY)
sBullet  = S('sBullet',  fontSize=9,   textColor=C['dkgrey'], leading=13,  spaceAfter=2, leftIndent=12, bulletIndent=2)
sBullet2 = S('sBullet2', fontSize=8.5, textColor=C['dkgrey'], leading=12,  spaceAfter=1, leftIndent=24, bulletIndent=14)
sMono    = S('sMono',    fontSize=8,   textColor=C['dkgrey'], leading=11.5,spaceAfter=1, fontName='Courier')
sKey     = S('sKey',     fontSize=9,   textColor=C['red'],    leading=13,  spaceAfter=3, fontName='Helvetica-Bold')
sTH      = S('sTH',      fontSize=8.5, textColor=C['white'],  leading=12,  alignment=TA_CENTER, fontName='Helvetica-Bold')
sTD      = S('sTD',      fontSize=8.5, textColor=C['dkgrey'], leading=12,  alignment=TA_LEFT)
sTDc     = S('sTDc',     fontSize=8.5, textColor=C['dkgrey'], leading=12,  alignment=TA_CENTER)
sSmall   = S('sSmall',   fontSize=7.5, textColor=C['grey'],   leading=11,  spaceAfter=2)

# ─── FLOWABLE HELPERS ────────────────────────────────────────────────────────

class Banner(Flowable):
    """Coloured rounded-rect banner with text."""
    def __init__(self, text, bg, fg=None, h=26, fs=12, bold=True, width=None):
        super().__init__()
        self.text = text
        self.bg   = bg
        self.fg   = fg or C['white']
        self.h    = h
        self.fs   = fs
        self.bold = bold
        self._w   = width or INNER_W

    def wrap(self, aw, ah):
        self._w = min(self._w, aw)
        return self._w, self.h

    def draw(self):
        cv = self.canv
        cv.setFillColor(self.bg)
        cv.roundRect(0, 0, self._w, self.h, 6, fill=1, stroke=0)
        cv.setFillColor(self.fg)
        fn = 'Helvetica-Bold' if self.bold else 'Helvetica'
        cv.setFont(fn, self.fs)
        cv.drawCentredString(self._w/2, self.h/2 - self.fs/2 + 2, self.text)


class CodeBox(Flowable):
    """Monospace diagram box with coloured background."""
    def __init__(self, lines, bg=None, border=None, fs=7.8, w=None):
        super().__init__()
        self.lines  = lines
        self.bg     = bg or C['lgrey']
        self.border = border or C['blue']
        self.fs     = fs
        self.lh     = fs + 3
        self.pad    = 7
        self._w     = w or INNER_W

    def wrap(self, aw, ah):
        self._w = min(self._w, aw)
        return self._w, len(self.lines)*self.lh + 2*self.pad

    def draw(self):
        cv  = self.canv
        h   = len(self.lines)*self.lh + 2*self.pad
        cv.setFillColor(self.bg)
        cv.setStrokeColor(self.border)
        cv.setLineWidth(0.8)
        cv.roundRect(0, 0, self._w, h, 5, fill=1, stroke=1)
        cv.setFont('Courier', self.fs)
        cv.setFillColor(C['dkgrey'])
        y = h - self.pad - self.fs
        for ln in self.lines:
            cv.drawString(self.pad, y, ln)
            y -= self.lh


def sp(n=0.2): return Spacer(1, n*cm)
def hr(col=None): return HRFlowable(width="100%", thickness=0.6,
                                     color=col or C['mgrey'],
                                     spaceAfter=3, spaceBefore=3)

def section_header(num, title, bg):
    return [sp(0.3), Banner(f"TOPIC {num}  |  {title}", bg=bg, fs=13, h=30), sp(0.15)]

def sub_banner(title, bg):
    return [sp(0.1), Banner(title, bg=bg, fs=10, h=22), sp(0.1)]

def bp(txt, lvl=0):
    st = sBullet if lvl==0 else sBullet2
    return Paragraph(f"• {txt}", st)

def kf(txt):
    return Paragraph(f"★  KEY FACT:  {txt}", sKey)


def table(headers, rows, cw=None, hbg=None):
    hbg = hbg or C['navy']
    if cw is None:
        n = len(headers)
        cw = [INNER_W/n]*n
    hrow = [Paragraph(h, sTH) for h in headers]
    data = [hrow] + [[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), hbg),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [C['white'], C['lgrey']]),
        ('GRID', (0,0), (-1,-1), 0.4, C['mgrey']),
        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
    ]))
    return [t, sp(0.2)]


def mnemonic(title, items, bg=None, border=None):
    bg     = bg     or C['lteal']
    border = border or C['teal']
    content = [[Paragraph(f"🧠  MNEMONIC — {title}",
        S('mn1', fontSize=9.5, textColor=C['teal'], fontName='Helvetica-Bold',
          alignment=TA_CENTER))]]
    for it in items:
        content.append([Paragraph(it, S('mn2', fontSize=9, textColor=C['teal'],
            fontName='Helvetica', alignment=TA_CENTER, leading=13))])
    t = Table(content, colWidths=[INNER_W])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), bg),
        ('BOX', (0,0), (-1,-1), 1.2, border),
        ('TOPPADDING', (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING', (0,0), (-1,-1), 10),
        ('RIGHTPADDING', (0,0), (-1,-1), 10),
    ]))
    return [t, sp(0.2)]


# ─── PAGE CALLBACKS ──────────────────────────────────────────────────────────

def first_page(cv, doc):
    cv.saveState()
    cv.setFillColor(C['navy'])
    cv.rect(0, 0, A4[0], A4[1], fill=1, stroke=0)
    cv.setFillColor(C['blue'])
    cv.rect(0, A4[1]-70, A4[0], 70, fill=1, stroke=0)
    cv.setFillColor(C['teal'])
    cv.rect(0, 0, A4[0], 36, fill=1, stroke=0)
    cv.restoreState()


def later_pages(cv, doc):
    cv.saveState()
    cv.setFillColor(C['navy'])
    cv.rect(0, A4[1]-22, A4[0], 22, fill=1, stroke=0)
    cv.setFillColor(C['white'])
    cv.setFont('Helvetica-Bold', 7.5)
    cv.drawString(1.8*cm, A4[1]-14, "MUHS 2nd MBBS PATHOLOGY — RAPID REVISION")
    cv.setFont('Helvetica', 7.5)
    cv.drawRightString(A4[0]-1.8*cm, A4[1]-14, "Based on Robbins & Kumar")
    cv.setFillColor(C['navy'])
    cv.rect(0, 0, A4[0], 16, fill=1, stroke=0)
    cv.setFillColor(C['white'])
    cv.setFont('Helvetica', 7)
    cv.drawCentredString(A4[0]/2, 4, f"Page {doc.page}")
    cv.restoreState()


# ─── COVER ───────────────────────────────────────────────────────────────────

def cover():
    E = []
    E.append(sp(5.5))
    def cs(txt, fs, col, bold=False):
        fn = 'Helvetica-Bold' if bold else 'Helvetica'
        return Paragraph(txt, S(f'c{fs}', fontSize=fs, textColor=col,
            fontName=fn, alignment=TA_CENTER, spaceAfter=8))
    E.append(cs("MUHS 2nd MBBS PATHOLOGY", 28, C['white'], True))
    E.append(cs("COMPREHENSIVE RAPID REVISION NOTES", 17, colors.HexColor("#93c5fd"), True))
    E.append(HRFlowable(width="65%", thickness=2, color=C['teal'],
                         spaceAfter=14, spaceBefore=4, hAlign='CENTER'))
    topics = [
        "1.  Malaria — Pathogenesis &amp; Morphology",
        "2.  Cysticercosis — Etiopathogenesis &amp; Morphology",
        "3.  Leprosy — Pathogenesis, Classification, Gross &amp; Micro  ★★★",
        "4.  Common Viral &amp; Fungal Infections",
        "5.  Primary Tuberculosis — Pathogenesis, Sites, Tubercle, Complex  ★",
        "6.  Ghon's Complex — Gross, Microscopic &amp; Fate  ★★★",
    ]
    ts = S('ct', fontSize=11, textColor=colors.HexColor("#e0f2fe"),
           fontName='Helvetica', alignment=TA_CENTER, spaceAfter=5, leading=17)
    for t in topics:
        E.append(Paragraph(t, ts))
    E.append(sp(0.9))
    E.append(HRFlowable(width="65%", thickness=2, color=C['teal'],
                         spaceAfter=10, hAlign='CENTER'))
    E.append(cs("Robbins, Cotran &amp; Kumar — Pathologic Basis of Disease, 10e", 9,
                colors.HexColor("#bfdbfe")))
    E.append(PageBreak())
    return E


# ─── TOPIC 1 — MALARIA ───────────────────────────────────────────────────────

def malaria():
    E = []
    E += section_header(1, "MALARIA — Pathogenesis & Morphology", C['red'])

    E.append(Paragraph(
        "<b>Causative organisms:</b> P. falciparum (most virulent), P. vivax, P. ovale, "
        "P. malariae, P. knowlesi. <b>Vector:</b> Female Anopheles mosquito. "
        "<b>Humans = only natural reservoir.</b>  200M+ cases/yr; 600K+ deaths/yr.", sBody))
    E.append(sp(0.15))

    E += sub_banner("PATHOGENESIS — Life Cycle", C['red'])
    lc = [
        "  MOSQUITO BITE → SPOROZOITES enter bloodstream",
        "       ↓",
        "  LIVER STAGE (Exo-erythrocytic) — ASYMPTOMATIC (incubation 1–4 weeks)",
        "  Sporozoites bind hepatocytes via thrombospondin + circumsporozoite surface protein",
        "  Differentiate into MEROZOITES (up to 30,000 per infected hepatocyte)",
        "  [P. vivax / P. ovale → HYPNOZOITES remain dormant → relapse weeks–months later]",
        "       ↓",
        "  Infected hepatocytes rupture → Merozoites released into bloodstream",
        "       ↓",
        "  RBC STAGE (Erythrocytic) — SYMPTOMATIC",
        "  Merozoites bind sialic acid glycophorin on RBC surface → invaginate into RBC",
        "  Merozoite → TROPHOZOITE → SCHIZONT (with PfEMP1 knobs on RBC surface) → Merozoites",
        "  RBC LYSIS → merozoites burst out → fever + chills + rigors (TNF surge)",
        "       ↓",
        "  Some trophozoites → GAMETOCYTES (sexual forms) → infect mosquito → cycle restarts",
    ]
    E.append(CodeBox(lc, bg=C['lred'], border=C['red']))
    E.append(sp(0.2))

    E += sub_banner("WHY P. FALCIPARUM IS MORE VIRULENT", C['red'])
    E += table(
        ["Mechanism", "Significance"],
        [
            ("Infects RBCs of ALL ages", "Very high parasitemia (other spp. infect only young or old RBCs)"),
            ("PfEMP1 knobs on RBC surface", "Binds endothelial ICAM-1, VCAM-1, CD36, E-selectin → SEQUESTRATION in capillaries → blocks blood flow → CEREBRAL MALARIA"),
            ("Rosette formation", "Infected RBCs clump together → worsens vascular blockage"),
            ("No hypnozoites", "No relapse but causes acute high-level parasitemia"),
            ("Antigenic variation", "Switches PfEMP1 variants each generation → evades antibody response"),
        ],
        cw=[4.5*cm, 10*cm], hbg=C['red'])

    E += sub_banner("FEVER PERIODICITY", C['orange'])
    E += table(
        ["Species", "Periodicity", "Pattern Name"],
        [
            ("P. vivax / P. ovale", "Every 48 hours", "Benign tertian malaria"),
            ("P. malariae",         "Every 72 hours", "Quartan malaria"),
            ("P. falciparum",       "Irregular / ~36–48 h", "Malignant tertian malaria ← MOST DANGEROUS"),
            ("P. knowlesi",         "Every 24 hours", "Quotidian malaria"),
        ],
        cw=[4.5*cm, 4.5*cm, 5.5*cm], hbg=C['orange'])

    E += sub_banner("MORPHOLOGY — Organ Changes", C['blue'])
    E += table(
        ["Organ", "Pathological Findings"],
        [
            ("SPLEEN",        "Splenomegaly (may exceed 1000 g); gray-black HEMOZOIN pigment in macrophages; red pulp congestion + hyperplasia; chronic → fibrotic, brittle, thick capsule"),
            ("LIVER",         "Enlarged, pigmented; Kupffer cells laden with malarial pigment, parasitized RBCs, cellular debris"),
            ("BRAIN (P. falciparum)", "Cerebral malaria: vessels PLUGGED by parasitized RBCs; RING HAEMORRHAGES around vessels; DURCK GRANULOMA (malarial granuloma); neuronal degeneration; focal ischaemic softening"),
            ("KIDNEY",        "Enlarged, congested; malarial pigment in glomeruli; haemoglobin casts in tubules. BLACKWATER FEVER = massive haemolysis + haemoglobinuria → AKI"),
            ("BONE MARROW / LYMPH NODES", "Pigmented phagocytic cells throughout; haemozoin deposits"),
            ("BLOOD SMEAR (Dx)", "Giemsa stain: ring trophozoites, schizonts, gametocytes within RBCs. P. falciparum ring = DOUBLE CHROMATIN DOT; banana-shaped gametocytes"),
        ],
        cw=[3.5*cm, 11*cm], hbg=C['blue'])

    E += mnemonic("P. falciparum virulence — 'SCAR'",
        ["S = Sequestration (PfEMP1 sticks to endothelium)",
         "C = Can infect all-age RBCs (high parasitaemia)",
         "A = Antigenic variation (escapes immunity)",
         "R = Rosette formation (RBC clumping)"],
        bg=C['lred'], border=C['red'])

    E += mnemonic("Plasmodium species — 'Fever Very Often Makes People Sick'",
        ["F=Falciparum | V=Vivax | O=Ovale | M=Malariae | P=P.knowlesi | S=Sporozoites"],
        bg=C['lorange'], border=C['orange'])

    E.append(kf("Dürck granuloma = pathognomonic of cerebral malaria. Diagnosis = Giemsa-stained thick & thin blood smear. BLACKWATER FEVER = P. falciparum + haemolysis + haemoglobinuria."))
    E.append(PageBreak())
    return E


# ─── TOPIC 2 — CYSTICERCOSIS ─────────────────────────────────────────────────

def cysticercosis():
    E = []
    E += section_header(2, "CYSTICERCOSIS — Etiopathogenesis & Morphology", C['purple'])

    E.append(Paragraph(
        "<b>Definition:</b> Disease caused by LARVAE (cysticercus) of <i>Taenia solium</i> "
        "(pork tapeworm) when HUMANS act as the INTERMEDIATE HOST by ingesting eggs.", sBody))
    E.append(sp(0.1))
    E += table(
        ["Condition", "Role of Human", "Role of Pig"],
        [
            ("Normal T. solium cycle", "DEFINITIVE host — adult tapeworm in intestine", "INTERMEDIATE host — cysticerci in muscles"),
            ("CYSTICERCOSIS", "INTERMEDIATE host — cysticerci develop in human tissues", "Not involved in this route"),
        ],
        cw=[4*cm, 6.5*cm, 4*cm], hbg=C['purple'])

    E += sub_banner("ETIOPATHOGENESIS", C['purple'])
    p = [
        "  Human ingests T. solium EGGS (contaminated food/water/fecal-oral route or autoinfection)",
        "       ↓",
        "  Eggs hatch in intestine → ONCOSPHERES (hexacanth embryos with 6 hooklets)",
        "       ↓",
        "  Oncospheres penetrate intestinal wall → enter bloodstream",
        "       ↓",
        "  Haematogenous dissemination to TISSUES",
        "       ↓",
        "  Develop into CYSTICERCI (fluid-filled cysts with invaginated SCOLEX inside)",
        "       ↓",
        "  PREFERRED SITES: Brain > Subcutaneous tissue > Eye > Skeletal muscle > Heart > Liver",
        "       ↓",
        "  VIABLE CYST: minimal inflammation (immune evasion by live cyst)",
        "  DYING/DEAD CYST: intense inflammation → granuloma → fibrous capsule → CALCIFICATION",
    ]
    E.append(CodeBox(p, bg=C['lpurple'], border=C['purple']))
    E.append(sp(0.2))

    E += sub_banner("CLINICAL FEATURES BY SITE", C['blue'])
    E += table(
        ["Site", "Clinical Features"],
        [
            ("Neurocysticercosis (NCC)", "SEIZURES (most common cause of acquired epilepsy in endemic areas); headache; raised ICP; hydrocephalus; focal neurological deficits"),
            ("Ocular",                  "Floaters, visual disturbance, blindness (subretinal or vitreous cyst)"),
            ("Subcutaneous",            "Palpable, non-tender nodules; 'puffed rice' calcifications on X-ray"),
            ("Muscular",                "Pseudohypertrophy; calcified cysts on CT/MRI"),
        ],
        cw=[4*cm, 10.5*cm], hbg=C['blue'])

    E += sub_banner("MORPHOLOGY — Gross & Microscopic", C['purple'])
    E.append(Paragraph("<b>GROSS:</b>", sKey))
    for g in [
        "Round/oval translucent fluid-filled cyst, 0.5–2 cm (RACEMOSE form up to 20 cm in brain cisterns/ventricles)",
        "White, glistening wall; SCOLEX visible as a white nodule ('rice grain') inside",
        "RACEMOSE variant: grapelike cluster of cysts, NO scolex — found in cisterns/ventricles",
        "Calcified dead cysts: chalky white, hard — seen on plain X-ray in muscle as 'puffed rice'",
    ]:
        E.append(bp(g))

    E.append(sp(0.1))
    E.append(Paragraph("<b>MICROSCOPIC — 3 Stages:</b>", sKey))
    E += table(
        ["Stage", "Microscopic Features"],
        [
            ("VIABLE CYST", "• Outer cuticular layer (lamellar, eosinophilic)\n• Middle cellular (reticular) layer\n• Inner germinal (nucleated) layer\n• Scolex with suckers + hooklets visible\n• MINIMAL host inflammatory response (immune evasion)"),
            ("DEGENERATING / DEAD CYST", "• Cyst wall hyalinises and breaks down\n• INTENSE INFLAMMATION: eosinophils, neutrophils, lymphocytes, plasma cells, macrophages\n• Granuloma formation with foreign body giant cells"),
            ("CALCIFIED CYST (Healed)", "• Dense calcification of dead scolex + wall\n• Fibrosis/gliosis surrounding (in brain)\n• 'Ghost' outline of original cyst remains"),
        ],
        cw=[3.5*cm, 11*cm], hbg=C['purple'])

    diag = [
        "  CYSTICERCUS CELLULOSAE — MICROSCOPIC DIAGRAM",
        "  ┌────────────────────────────────────────────────┐",
        "  │  [Outer cuticular layer — lamellar/wavy]       │",
        "  │  [Middle cellular/reticular layer]             │",
        "  │  [Inner germinal layer — nucleated cells]      │",
        "  │                                                │",
        "  │       FLUID CAVITY (transparent fluid)         │",
        "  │                                                │",
        "  │   ┌────────────────────────────────────┐       │",
        "  │   │  SCOLEX (invaginated head)          │       │",
        "  │   │  - Rostellum with HOOKLETS          │       │",
        "  │   │  - 4 SUCKERS (acetabula)            │       │",
        "  │   └────────────────────────────────────┘       │",
        "  │                                                │",
        "  │  In viable cyst: minimal host inflammation     │",
        "  │  In dead cyst:   dense eosinophil infiltrate   │",
        "  └────────────────────────────────────────────────┘",
    ]
    E.append(CodeBox(diag, bg=C['lpurple'], border=C['purple']))

    E += mnemonic("Cysticercosis — 'CHEST'",
        ["C = Cyst (fluid-filled, with scolex inside)",
         "H = Hooklets on scolex (oncosphere has 6 hooklets)",
         "E = Eggs ingested (fecal-oral route — key difference from taeniasis)",
         "S = Seizures (most common presentation in NCC)",
         "T = Taenia solium (pork tapeworm)"],
        bg=C['lpurple'], border=C['purple'])

    E.append(kf("NCC = most common cause of acquired epilepsy in developing countries. Treatment: Albendazole + Dexamethasone (steroids to reduce inflammation from dying cysts)."))
    E.append(PageBreak())
    return E


# ─── TOPIC 3 — LEPROSY ★★★ ──────────────────────────────────────────────────

def leprosy():
    E = []
    E += section_header(3, "LEPROSY (Hansen Disease)  ★★★", C['teal'])

    E.append(Paragraph(
        "<b>Causative organism:</b> <i>Mycobacterium leprae</i> (rarely M. lepromatosis). "
        "Slow progressive infection affecting <b>SKIN and PERIPHERAL NERVES</b>. "
        "Cannot be cultured in vitro. Proliferates best at <b>32–34°C</b> (cool tissues). "
        "Transmission: <b>human respiratory secretions</b> (main route); zoonotic from armadillos (rare).", sBody))
    E.append(sp(0.15))

    E += sub_banner("PATHOGENESIS", C['teal'])
    p = [
        "  M. leprae enters via respiratory tract",
        "       ↓",
        "  Taken up by DERMAL MACROPHAGES → PGL-1 lipid mediates cell invasion",
        "  Inhibits mitochondrial energy metabolism → evades host immune killing",
        "       ↓",
        "  Disseminates via blood → replicates in COOL TISSUES (skin, extremities, peripheral nerves)",
        "       ↓",
        "       HOST CELL-MEDIATED IMMUNE RESPONSE determines disease pattern:",
        "",
        "   STRONG Th1 response              WEAK Th1 response",
        "   (IFN-γ, IL-2, Th17)             (Th2 / Regulatory T-cells dominant)",
        "         ↓                                  ↓",
        "   TUBERCULOID LEPROSY             LEPROMATOUS LEPROSY",
        "   (Paucibacillary)                (Multibacillary)",
        "   Well-formed granulomas          No granulomas — Lepra cells",
        "   Low bacterial load              High bacterial load",
        "   Asymmetric nerve damage         Symmetric skin + nerve invasion",
    ]
    E.append(CodeBox(p, bg=C['lteal'], border=C['teal']))
    E.append(sp(0.2))

    E += sub_banner("CLASSIFICATION", C['teal'])
    E.append(Paragraph("<b>Ridley-Jopling spectrum:</b>", sBody))
    sp_lines = [
        "  TUBERCULOID (TT) ←─── BT ─── BB ─── BL ───→ LEPROMATOUS (LL)",
        "  |←── STRONG CMI ──────── BORDERLINE ──────── WEAK CMI ──────→|",
        "  |←── PAUCIBACILLARY ─────────────────── MULTIBACILLARY ─────→|",
    ]
    E.append(CodeBox(sp_lines, bg=C['lteal'], border=C['teal']))
    E.append(sp(0.1))
    E.append(Paragraph("<b>WHO Classification (used clinically for MDT):</b>", sBody))
    E += table(
        ["WHO Type", "Skin Lesions", "Ridley-Jopling Equivalent", "MDT Duration"],
        [
            ("Paucibacillary (PB)", "1–5 lesions", "TT / BT", "6 months"),
            ("Multibacillary (MB)", ">5 lesions", "BB / BL / LL", "12 months"),
        ],
        cw=[3.5*cm, 3*cm, 5*cm, 3*cm], hbg=C['teal'])

    E += sub_banner("IMMUNOLOGY COMPARISON TABLE", C['blue'])
    E += table(
        ["Feature", "TUBERCULOID", "LEPROMATOUS"],
        [
            ("T-cell response", "Strong Th1 (IFN-γ, IL-2)", "Weak Th1 / Th2 + Reg-T dominant"),
            ("Bacterial load", "LOW — PAUCIBACILLARY", "HIGH — MULTIBACILLARY"),
            ("Granulomas", "Well-formed (like TB)", "ABSENT — replaced by lepra cells"),
            ("Antibodies", "Low", "High (but NOT protective; cause vasculitis, erythema nodosum, GN)"),
            ("Cell-mediated immunity", "INTACT", "DEFICIENT"),
            ("Lepromin test", "POSITIVE", "NEGATIVE"),
            ("Nerve involvement", "Asymmetric, destructive granulomas", "Symmetric, low-inflammation invasion"),
            ("Skin lesions", "Few, hypopigmented, ANESTHETIC", "Multiple, nodular, LEONINE, hypoaesthetic"),
        ],
        cw=[4.5*cm, 5*cm, 5*cm], hbg=C['blue'])

    E += sub_banner("GROSS (CLINICAL) FINDINGS", C['teal'])

    E.append(Paragraph("<b>Tuberculoid Leprosy:</b>", sKey))
    for t in [
        "Flat red lesions enlarge → indurated, elevated hyperpigmented margins + depressed pale centre (CENTRAL HEALING)",
        "ASYMMETRIC large peripheral nerve thickening: ulnar, radial, peroneal, great auricular nerves",
        "ANESTHESIA of skin (destroyed small nerves in lesion)",
        "Skin + muscle atrophy, contractures, chronic ulcers, autoamputation of digits (trophic changes)",
        "Facial nerve palsy → lagophthalmos → keratitis + corneal ulcers",
    ]:
        E.append(bp(t))

    E.append(sp(0.1))
    E.append(Paragraph("<b>Lepromatous Leprosy:</b>", sKey))
    for t in [
        "SYMMETRIC skin thickening; macular, papular, or nodular lesions on face, ears, wrists, elbows, knees",
        "Nodules coalesce → LEONINE FACIES (lion-like face) — classic disfigurement",
        "SADDLE-NOSE deformity (destruction of nasal cartilage/bone by bacilli)",
        "Bacilli-laden nasal discharge (source of transmission)",
        "Testes: destruction of seminiferous tubules → sterility + gynecomastia",
        "SYMMETRIC nerve invasion (ulnar, peroneal) with MINIMAL inflammation",
        "Most lesions HYPOAESTHETIC or anesthetic",
    ]:
        E.append(bp(t))

    E += sub_banner("MICROSCOPIC FINDINGS", C['teal'])
    E += table(
        ["Type", "Microscopic Features"],
        [
            ("TUBERCULOID\n(Paucibacillary)", "• Well-formed GRANULOMAS (resembles TB granulomas)\n• EPITHELIOID CELLS (activated macrophages, footprint-shaped nuclei)\n• LANGHANS GIANT CELLS (horseshoe/peripheral nuclei arrangement)\n• Dense LYMPHOCYTIC INFILTRATE surrounding granuloma\n• Granulomas enclose and DESTROY NERVE bundles\n• AFB stain: NEGATIVE / very rare bacilli\n• Granulomas extend up to basal layer of epidermis"),
            ("LEPROMATOUS\n(Multibacillary)", "• Large aggregates of LIPID-LADEN MACROPHAGES = LEPRA CELLS (Virchow cells / foam cells)\n• Lepra cells packed with GLOBI (masses of AFB in 'cigar bundle' / 'cannon ball' arrangement)\n• NO GRANULOMAS (absent cell-mediated immunity)\n• GRENZ ZONE: clear subepidermal zone (thin band of uninvolved dermis)\n• AFB stain: HEAVILY POSITIVE — bacilli in globi\n• Lymph nodes: bacteria-filled foamy macrophages in PARACORTICAL (T-cell) areas + reactive germinal centres\n• Testes: destruction of seminiferous tubules; spleen + liver macrophage aggregates"),
        ],
        cw=[3.5*cm, 11*cm], hbg=C['teal'])

    # Lepra cell diagram
    lc = [
        "  LEPRA CELL (Virchow Cell) — Lepromatous Leprosy",
        "  ┌─────────────────────────────────────────────────┐",
        "  │            MACROPHAGE / FOAM CELL               │",
        "  │                                                 │",
        "  │  [===GLOBUS 1===] [===GLOBUS 2===] [=GLOBUS 3=] │",
        "  │  AFB in bundles   AFB in bundles   AFB bundles  │",
        "  │  ('cigar bundles' or 'cannon balls' on ZN stain)│",
        "  │                                                 │",
        "  │            Foamy cytoplasm (lipid-filled)        │",
        "  │                  [ NUCLEUS ]                    │",
        "  └─────────────────────────────────────────────────┘",
        "  ZN stain: RED acid-fast bacilli on BLUE background",
    ]
    E.append(CodeBox(lc, bg=C['lteal'], border=C['teal']))
    E.append(sp(0.1))

    lgc = [
        "  LANGHANS GIANT CELL — Tuberculoid Leprosy / TB",
        "  ┌─────────────────────────────────────────────────┐",
        "  │                                                 │",
        "  │       O  O  O  O  O  O  (nuclei)               │",
        "  │    O                        O                   │",
        "  │                                                 │",
        "  │        LARGE PINK CYTOPLASM                     │",
        "  │        (multiple fused epithelioid cells)       │",
        "  │                                                 │",
        "  │    O                        O                   │",
        "  │       O  O  O  O  O  O                          │",
        "  │  Nuclei in HORSESHOE / PERIPHERAL arrangement   │",
        "  │  (KEY DISTINGUISHING FEATURE — ask in MUHS!)    │",
        "  └─────────────────────────────────────────────────┘",
    ]
    E.append(CodeBox(lgc, bg=C['lblue'], border=C['blue']))
    E.append(sp(0.15))

    E += mnemonic("Leprosy types — 'Tuberculoid = T for Tough immunity'",
        ["Tuberculoid = Tough/strong Th1 immunity = pauci bacillary = Treatable easily",
         "Lepromatous = Low immunity = Lots of bacilli = Leonine face = Lepra cells"],
        bg=C['lteal'], border=C['teal'])

    E += mnemonic("Leprosy nerve thickening — 'Uncle Rajan Plays Golf All Sundays'",
        ["Ulnar | Radial cutaneous | Peroneal | Great auricular | Auriculotemporal | Sural"],
        bg=C['lamber'], border=C['amber'])

    E.append(kf("Leonine facies + saddle nose = LEPROMATOUS. Anesthetic hypopigmented lesion + thickened nerve = TUBERCULOID. Lepra cell = lipid-laden macrophage = Virchow cell. Grenz zone = lepromatous."))
    E.append(PageBreak())
    return E


# ─── TOPIC 4 — VIRAL & FUNGAL INFECTIONS ─────────────────────────────────────

def viral_fungal():
    E = []
    E += section_header(4, "COMMON VIRAL & FUNGAL INFECTIONS", C['orange'])

    # VIRAL
    E += sub_banner("COMMON VIRAL INFECTIONS", C['orange'])
    E += table(
        ["Virus", "Key Features", "Pathogenesis", "Characteristic Histology"],
        [
            ("INFLUENZA\n(Type A/B/C)", "RNA virus, 8 segments\nH + N surface proteins\nType A = pandemic risk", "Antigenic DRIFT = point mutations → epidemics\nAntigenic SHIFT = recombination with animal virus → PANDEMICS\n(1918, 2009 pandemics = swine origin)", "DAD (diffuse alveolar damage)\nHyaline membrane formation\nInterstitial pneumonitis"),
            ("SARS-CoV-2\n(COVID-19)", "Enveloped +ve-sense RNA\nSpike protein binds ACE2 on\ntype II alveolar cells + nasopharynx", "Rapid replication → immune overactivation\n'Cytokine storm' → DAD\nCoagulopathy → microthrombi", "DAD with hyaline membranes\nMicrothrombi in vessels\nMyocarditis; CNS inflammatory infiltrates"),
            ("HERPES SIMPLEX\n(HSV-1/HSV-2)", "DNA herpesvirus\nLatent in sensory ganglia\nReactivation with stress/immunosuppression", "Cell-to-cell spread\nNeurotropic latency in ganglia\nReactivation → retrograde axonal transport", "COWDRY TYPE A intranuclear inclusions\n(large, eosinophilic, marginated chromatin)\nMultinucleated giant cells ('ground-glass' nuclei)"),
            ("CMV", "Large DNA herpesvirus\nDangerous in immunocompromised\n(AIDS, transplant, neonates)", "Reactivates when CD4 falls / immunosuppression\nInfects endothelium, epithelium, macrophages", "OWL-EYE inclusions (large purple intranuclear inclusion with halo + smaller cytoplasmic ones)\nCell enlargement (cytomegaly)"),
            ("MEASLES\n(Rubeola)", "RNA Paramyxovirus\nDroplet transmission\n3Cs: Cough, Coryza, Conjunctivitis", "Infects respiratory epithelium → viraemia → lymphoid tissue", "WARTHIN-FINKELDEY giant cells in lymphoid tissue\nKoplik spots (buccal mucosa)\nSquamous metaplasia of bronchial epithelium"),
            ("EBV", "DNA herpesvirus\nB-cell tropism via CD21", "Polyclonal B-cell proliferation\nAtypical lymphocytes (Downey cells)", "Atypical lymphocytes in blood smear\nReactive germinal centres in lymph nodes\nAssociated: Burkitt lymphoma, NPC, PTLD"),
        ],
        cw=[2.5*cm, 3.5*cm, 4.5*cm, 4*cm], hbg=C['orange'])

    E += sub_banner("VIRAL INCLUSION BODIES — QUICK REFERENCE", C['red'])
    E += table(
        ["Inclusion Body", "Virus", "Location", "Appearance"],
        [
            ("Cowdry type A", "HSV, CMV, Yellow Fever", "Intranuclear", "Large eosinophilic, chromatin margination"),
            ("OWL-EYE", "CMV", "Intranuclear + cytoplasmic", "Large purple nuclear inclusion with surrounding halo; smaller cytoplasmic dots"),
            ("Negri bodies", "RABIES", "Cytoplasmic (neurons)", "Eosinophilic, hippocampus + Purkinje cells"),
            ("Warthin-Finkeldey giant cells", "MEASLES", "Lymphoid tissue", "Multinucleated giant cells, intranuclear + cytoplasmic inclusions"),
            ("Henderson-Patterson bodies", "Molluscum contagiosum", "Cytoplasmic (keratinocytes)", "Large, pushing nucleus aside"),
            ("Guarnieri bodies", "Smallpox / Vaccinia", "Cytoplasmic", "Viral factories in keratinocytes"),
            ("Torres bodies", "Yellow Fever", "Intranuclear (hepatocytes)", "Eosinophilic (Councilman bodies = apoptotic hepatocytes)"),
        ],
        cw=[4*cm, 3*cm, 3*cm, 4.5*cm], hbg=C['red'])

    # FUNGAL
    E += sub_banner("COMMON FUNGAL INFECTIONS", C['green'])
    E += table(
        ["Fungus", "Morphology / Stain", "Risk Factors", "Pathological Findings"],
        [
            ("CANDIDA ALBICANS\n(Candidiasis)", "PSEUDOHYPHAE + budding yeast\nPAS / GMS stain\n(gram-positive on Gram stain)", "Neutropenia, AIDS, diabetes, broad-spectrum antibiotics, indwelling catheters", "Superficial: thrush (oral white plaques), vulvovaginitis\nDeep/invasive: esophageal, systemic candidiasis\nNeutrophilic infiltrate + pseudohyphae invading tissue"),
            ("ASPERGILLUS\n(Aspergillosis)", "SEPTATE hyphae\n45° ACUTE ANGLE branching\nGMS / H&E stain", "Neutropenia (invasive)\nPre-existing lung cavity (aspergilloma)\nAtopy (ABPA)", "3 forms:\n1) ASPERGILLOMA = fungal ball in cavity (no tissue invasion)\n2) ABPA = allergic, eosinophilic bronchitis\n3) INVASIVE = angioinvasion → haemorrhagic infarcts"),
            ("CRYPTOCOCCUS\nNEOFORMANS", "Encapsulated yeast (5–10 μm)\nINDIA INK = clear halo (capsule)\nMUCICARMINE = magenta capsule\nPAS stain", "AIDS (CD4 <100–200)\nInhalation from pigeon droppings", "SOAP-BUBBLE lesions in brain (gelatinous pseudocysts)\nMinimal inflammation in AIDS\nMeningoencephalitis\nCryptococcomas in immunocompetent"),
            ("MUCOR / RHIZOPUS\n(Mucormycosis)", "BROAD NON-SEPTATE hyphae\n90° RIGHT-ANGLE branching\nGMS stain", "DIABETICS (DKA) — rhinocerebral\nNeutropenic — pulmonary\nOrgan transplant", "ANGIOINVASION → thrombosis → tissue INFARCTION\nRhinocerebral: palate perforation, orbital involvement\nBlack necrotic eschars (hallmark)"),
            ("HISTOPLASMA\nCAPSULATUM", "Small intracellular yeast (2–4 μm)\nInside macrophages\nGMS / PAS stain\n(NOT encapsulated despite name)", "Ohio/Mississippi river valleys\nInhalation of bird/bat droppings\nCave explorers", "Mimics TB: granulomas, caseous necrosis, calcification\nTiny yeast inside macrophages\nDisseminated in AIDS: hepatosplenomegaly, adrenal destruction"),
            ("PNEUMOCYSTIS\nJIROVECII (PCP)", "Cysts (6–8 μm) with 8 intracystic bodies\nGMS stain: dark cysts\nSilver stain (Grocott)", "AIDS (CD4 <200)\nSteroid therapy\nPost-transplant", "INTERSTITIAL PNEUMONIA\nFrothy, pink alveolar exudate ('honeycomb' or 'cotton candy' appearance)\nNo granulomas\nBilateral ground-glass on CT"),
        ],
        cw=[2.8*cm, 3.5*cm, 3.5*cm, 4.7*cm], hbg=C['green'])

    E += mnemonic("Fungal hyphae angle — 'SANE vs BROAD'",
        ["SANE = Septate Acute aNgle branching (45°) = ASPERGILLUS",
         "BROAD = Broad Right Obtuse Angle non-septate = MUCOR / Rhizopus (90°)"],
        bg=C['lgreen'], border=C['green'])

    E += mnemonic("Special stains for fungi — 'GMS for ALL; India Ink for Crypto'",
        ["GMS (Gomori Methenamine Silver) = stains ALL fungi black on green background",
         "India Ink = Cryptococcus ONLY (clear halo = polysaccharide capsule)",
         "Mucicarmine = Cryptococcus capsule stains MAGENTA",
         "PAS (periodic acid-Schiff) = fungi stain magenta/red"],
        bg=C['lorange'], border=C['orange'])

    E.append(kf("Mucor = Right angle, non-septate, angioinvasive, diabetics (DKA). Aspergillus = 45° acute angle, septate, angioinvasive, neutropenic. CMV = owl-eye. HSV = Cowdry A. Crypto = India ink halo."))
    E.append(PageBreak())
    return E


# ─── TOPIC 5 — PRIMARY TUBERCULOSIS ★ ───────────────────────────────────────

def primary_tb():
    E = []
    E += section_header(5, "PRIMARY TUBERCULOSIS  ★", C['navy'])

    E.append(Paragraph(
        "<b>Definition:</b> TB that develops in a <b>previously unexposed and UNSENSITIZED</b> individual. "
        "~5% of newly infected develop significant disease. "
        "<b><i>Mycobacterium tuberculosis</i></b> — acid-fast bacillus; transmission by respiratory droplets.", sBody))
    E.append(sp(0.15))

    E += sub_banner("PATHOGENESIS", C['navy'])
    p = [
        "  INHALATION of M. tuberculosis droplets",
        "       ↓",
        "  PHASE 1 — INNATE RESPONSE (first ~3 weeks) — NO SYMPTOMS",
        "  Bacilli reach alveoli → phagocytosed by ALVEOLAR MACROPHAGES",
        "  M. tb PREVENTS phagolysosome fusion → survives inside macrophages",
        "  Bacilli replicate → chemokines released → monocytes recruited",
        "  DENDRITIC CELLS carry antigens to HILAR LYMPH NODES",
        "       ↓",
        "  PHASE 2 — ADAPTIVE IMMUNITY Th1 RESPONSE (~3 weeks after infection)",
        "  DCs present antigens → Th1 cell differentiation (requires IL-12 + IL-18)",
        "  Th1 cells produce IFN-γ (CRITICAL mediator)",
        "       ↓",
        "  IFN-γ activates macrophages via 3 mechanisms:",
        "   1. Induces nitric oxide (NO) + reactive oxygen species (ROS) → kill bacteria",
        "   2. Mobilises defensins (cathelicidin) — antimicrobial peptides",
        "   3. Stimulates AUTOPHAGY → sequesters and destroys intracellular bacilli",
        "       ↓",
        "  Activated macrophages → EPITHELIOID HISTIOCYTES",
        "  + TNF secretion → recruits more monocytes + maintains granuloma",
        "       ↓",
        "  GRANULOMA FORMATION + CASEOUS NECROSIS",
        "       ↓",
        "  ~95%: Infection CONTAINED → Ghon complex → Fibrosis → Calcification (Ranke complex)",
        "  ~5%:  PROGRESSIVE PRIMARY TB (HIV/AIDS, malnutrition, infants) → no granulomas",
    ]
    E.append(CodeBox(p, bg=C['lblue'], border=C['navy']))
    E.append(sp(0.2))

    E += sub_banner("COMMON SITES OF PRIMARY TB", C['navy'])
    E += table(
        ["Priority", "Site", "Location Detail"],
        [
            ("1st (>95%)", "LUNGS", "Subpleural; LOWER part of UPPER LOBE or UPPER part of LOWER LOBE (close to pleura)"),
            ("2nd", "INTESTINE (terminal ileum)", "Ingestion of M. bovis from infected milk — largely eliminated in high-resource countries"),
            ("3rd", "TONSIL / PHARYNX", "Very rare; oral route of entry"),
            ("4th", "SKIN", "Primary inoculation TB (rare; occupational exposure)"),
        ],
        cw=[2*cm, 4*cm, 8.5*cm], hbg=C['navy'])

    E += sub_banner("EVOLUTION OF THE TUBERCLE — 5 STAGES", C['blue'])
    stages = [
        "STAGE 1 — INITIAL LESION (MACROPHAGE ACCUMULATION)",
        "  Inhaled bacilli reach alveoli → alveolar macrophages accumulate",
        "  HISTIOCYTES (tissue macrophages) congregate at site → early non-specific inflammation",
        "",
        "STAGE 2 — EPITHELIOID GRANULOMA FORMATION",
        "  IFN-γ activates macrophages → transform into EPITHELIOID CELLS",
        "  Epithelioid cells: elongated, pink granular cytoplasm, 'footprint-shaped' oblong nuclei",
        "  Surrounded by LYMPHOCYTES (mainly CD4+ Th1 cells)",
        "",
        "STAGE 3 — LANGHANS GIANT CELL FORMATION",
        "  Epithelioid cells FUSE → LANGHANS GIANT CELLS",
        "  KEY FEATURE: Nuclei arranged in HORSESHOE / PERIPHERAL PATTERN",
        "",
        "STAGE 4 — CASEOUS NECROSIS (Central)",
        "  Centre becomes CASEOUS = cheese-like, amorphous, eosinophilic, granular material",
        "  Caused by DTH (type IV delayed hypersensitivity) reaction — IFN-γ + TNF mediated",
        "  'Ghost' cell outlines (tombstone cells) may remain",
        "  Caseous necrosis = PATHOGNOMONIC OF TUBERCULOSIS",
        "",
        "STAGE 5 — RESOLUTION / PROGRESSION",
        "  A) Fibrosis → CALCIFICATION = HEALING (Ranke complex on X-ray)",
        "  B) Liquefaction → CAVITY = progression to secondary TB",
    ]
    E.append(CodeBox(stages, bg=C['lblue'], border=C['navy']))
    E.append(sp(0.15))

    tubercle_diag = [
        "  TB GRANULOMA (TUBERCLE) — DIAGRAM FOR MUHS",
        "  ┌──────────────────────────────────────────────────────┐",
        "  │  ===== FIBROUS CAPSULE (outer rim) =====             │",
        "  │                                                      │",
        "  │  [L][L][L][L] LYMPHOCYTES (outer layer) [L][L][L]   │",
        "  │                                                      │",
        "  │  [Epi][Epi][Epi] EPITHELIOID CELLS [Epi][Epi][Epi]  │",
        "  │  (elongated pink cells, footprint nuclei)            │",
        "  │                                                      │",
        "  │      O  O  O  O  O  O   LANGHANS GIANT CELL          │",
        "  │   O                    O  (horseshoe nuclei at        │",
        "  │   O    PINK CYTOPLASM  O   periphery — KEY FEATURE)   │",
        "  │      O  O  O  O  O  O                                 │",
        "  │                                                      │",
        "  │  ~~~~~ CASEOUS NECROSIS (CENTRE) ~~~~~               │",
        "  │  ~~~~~ amorphous, cheese-like, eosinophilic ~~~~~~   │",
        "  │  ~~~~~ PATHOGNOMONIC of TUBERCULOSIS ~~~~~~~~~~      │",
        "  └──────────────────────────────────────────────────────┘",
        "  Epi = Epithelioid cell  |  L = Lymphocyte",
    ]
    E.append(CodeBox(tubercle_diag, bg=C['lblue'], border=C['navy']))
    E.append(sp(0.2))

    E += sub_banner("PRIMARY COMPLEX — COMPONENTS  ★", C['red'])
    E.append(Paragraph(
        "Ghon's Complex (Primary Complex) = <b>3 COMPONENTS:</b>", sBody))
    E += table(
        ["Component", "Description"],
        [
            ("1. GHON FOCUS\n(Parenchymal component)", "1–1.5 cm gray-white area of consolidation\nSubpleural location — lower part of upper lobe or upper part of lower lobe\nCentre: CASEOUS NECROSIS (yellow-white, cheese-like)\nThe parenchymal lung lesion"),
            ("2. LYMPHANGITIS\n(Connecting component)", "Inflammatory thickening of lymphatic channels\nBetween Ghon focus and regional lymph nodes\nLinks parenchymal + nodal components\n'Beaded' appearance due to granulomas along lymphatics"),
            ("3. HILAR LYMPHADENOPATHY\n(Nodal component)", "Caseous enlargement of regional HILAR / mediastinal lymph nodes\nIn CHILDREN: nodal lesion is often LARGER than the parenchymal focus\nCaseous necrosis within nodes\nThe nodal component"),
        ],
        cw=[4*cm, 10.5*cm], hbg=C['red'])

    complex_diag = [
        "  PRIMARY (GHON'S) COMPLEX — DIAGRAM",
        "  ┌──────────────────────────────────────────────────┐",
        "  │                [LUNG]                            │",
        "  │                                                  │",
        "  │   ● GHON FOCUS (subpleural, lower upper lobe)   │",
        "  │     1–1.5 cm, grey-white, caseous centre         │",
        "  │     |                                           │",
        "  │     | ← LYMPHANGITIS (lymphatic channels,       │",
        "  │     |    inflamed, thickened, beaded)           │",
        "  │     |                                           │",
        "  │   ● HILAR LYMPH NODES (enlarged, caseous)       │",
        "  │     (often larger than Ghon focus in children)  │",
        "  │                                                  │",
        "  │  ALL THREE TOGETHER = GHON'S COMPLEX            │",
        "  └──────────────────────────────────────────────────┘",
    ]
    E.append(CodeBox(complex_diag, bg=C['lblue'], border=C['navy']))

    E += mnemonic("Primary Complex components — 'GHoN = Focus + Hilar nodes + cNecting lymphatics'",
        ["G = Ghon Focus (parenchymal lung lesion)",
         "H = Hilar lymphadenopathy (caseous lymph nodes)",
         "N = coNNecting lymphangitis (lymphatic channels between)"],
        bg=C['lblue'], border=C['navy'])

    E.append(kf("Ghon Focus = lung lesion only. Ghon Complex = Focus + Lymphangitis + Hilar nodes. Ranke Complex = Calcified Ghon complex visible on X-ray. Caseous necrosis = PATHOGNOMONIC of TB."))
    E.append(PageBreak())
    return E


# ─── TOPIC 6 — GHON'S COMPLEX ★★★ ──────────────────────────────────────────

def ghon_complex():
    E = []
    E += section_header(6, "GHON'S COMPLEX — Gross, Microscopic & Fate  ★★★", C['green'])

    E.append(Paragraph(
        "<b>Definition:</b> The combination of the <b>Ghon Focus</b> (parenchymal lung lesion) + "
        "<b>Lymphangitis</b> (lymphatic channels) + <b>Caseous hilar lymphadenopathy</b> "
        "constitutes the <b>Ghon's Complex (Primary Complex)</b> in primary tuberculosis. "
        "Named after Anton Ghon, 1912.", sBody))
    E.append(sp(0.15))

    E += sub_banner("GROSS FEATURES", C['green'])
    E.append(Paragraph("<b>A. Ghon Focus (Parenchymal Lesion):</b>", sKey))
    for g in [
        "Location: Subpleural; lower part of UPPER LOBE or upper part of LOWER LOBE (close to pleura)",
        "Size: 1–1.5 cm",
        "Colour: Gray-white area of consolidation",
        "Cut section: Centre shows yellow-white CASEOUS NECROSIS (cheese-like, crumbly, friable material)",
        "Surrounding lung: zone of grey consolidation / pneumonic reaction",
        "Pleura: may show fibrinous exudate or fibrous adhesion overlying the focus",
    ]:
        E.append(bp(g))

    E.append(sp(0.1))
    E.append(Paragraph("<b>B. Hilar Lymph Nodes:</b>", sKey))
    for g in [
        "Enlarged, discrete or matted together (periadenitis)",
        "Cut section: Yellow-white caseous material — often MORE EXTENSIVE than the parenchymal focus",
        "In CHILDREN: hilar nodes are characteristically LARGER than the Ghon focus",
        "May calcify with healing → visible on X-ray",
    ]:
        E.append(bp(g))

    E.append(sp(0.1))
    E.append(Paragraph("<b>C. Lymphatics (Lymphangitis):</b>", sKey))
    E.append(bp("Thickened, visible lymphatic channels connecting Ghon focus to hilar nodes"))
    E.append(bp("'Beaded' appearance due to granulomatous lesions along the lymphatic channel"))

    E += sub_banner("MICROSCOPIC FEATURES", C['green'])
    E += table(
        ["Site / Condition", "Microscopic Features"],
        [
            ("GHON FOCUS\n(Parenchymal lesion)", "1. CASEOUS NECROSIS (centre):\n   • Amorphous, granular, eosinophilic material — no living cells\n   • Ghost/tombstone cell outlines visible\n   • Loss of all tissue architecture\n\n2. GRANULOMATOUS INFLAMMATION (surrounding):\n   • EPITHELIOID CELLS — elongated macrophages, pale pink cytoplasm, oblong 'footprint' nuclei\n   • LANGHANS GIANT CELLS — nuclei in horseshoe/peripheral arrangement\n   • LYMPHOCYTES (mainly CD4+ T-cells) — outer rim\n   • Occasional plasma cells and fibroblasts\n\n3. FIBROUS CAPSULE — outer collagen rim\n\n4. ZN STAIN (AFB) — red bacilli (scanty in primary TB)"),
            ("HILAR LYMPH NODES", "• Similar caseating granulomas within nodes\n• Effacement of normal nodal architecture\n• Caseous necrosis (may be more extensive than focus)\n• Epithelioid cells + Langhans giant cells\n• Peripheral lymphocyte cuff\n• Periadenitis: inflammatory fibrous thickening of nodal capsule"),
            ("IMMUNOCOMPROMISED\nHOST (HIV CD4 <200)", "• Granulomas ABSENT\n• Sheets of foamy macrophages with NUMEROUS bacilli\n• No caseous necrosis (classic pattern absent)\n• ZN stain: heavily loaded with AFB\n• = Progressive Primary TB pattern (no containment)"),
        ],
        cw=[3.5*cm, 11*cm], hbg=C['green'])

    micro_diag = [
        "  MICROSCOPY OF GHON FOCUS — ANNOTATED DIAGRAM",
        "  ┌──────────────────────────────────────────────────────┐",
        "  │  ===== FIBROUS CAPSULE (outer rim, collagen) =====   │",
        "  │                                                      │",
        "  │  [L][L][L][L] LYMPHOCYTES (outer mantle) [L][L][L]  │",
        "  │                                                      │",
        "  │  [Epi][Epi][Epi] EPITHELIOID CELLS [Epi][Epi]       │",
        "  │  Pale pink cytoplasm, oblong 'footprint' nuclei      │",
        "  │                                                      │",
        "  │      LANGHANS GIANT CELL:                            │",
        "  │      O  O  O  O  O  O                                │",
        "  │   O  ( large pale cytoplasm ) O  ← horseshoe nuclei  │",
        "  │      O  O  O  O  O  O                                │",
        "  │                                                      │",
        "  │  ~~~~ CASEOUS NECROSIS (central) ~~~~                │",
        "  │  ~~~~ amorphous, granular, eosinophilic ~~~~         │",
        "  │  ~~~~ ghost cell outlines (tombstone cells) ~~~~     │",
        "  │  ~~~~ = PATHOGNOMONIC of TUBERCULOSIS ~~~~           │",
        "  └──────────────────────────────────────────────────────┘",
    ]
    E.append(CodeBox(micro_diag, bg=C['lgreen'], border=C['green']))
    E.append(sp(0.2))

    E += sub_banner("FATE OF GHON'S COMPLEX  ★★★  (MOST ASKED IN MUHS)", C['red'])
    fate_diag = [
        "                    GHON'S COMPLEX",
        "                          |",
        "            ┌─────────────┴──────────────────┐",
        "         ~95%                              ~5%",
        "    Normal immunity               Immunocompromised / Malnourished",
        "         |                                   |",
        "         ↓                                   ↓",
        "     HEALING                       PROGRESSIVE PRIMARY TB",
        "         |                          • Caseous pneumonia",
        "    ┌────┴────┐                     • Miliary spread (haematogenous)",
        "    ↓         ↓                     • TB meningitis",
        " FIBROSIS  CALCIFICATION            • No granulomas in HIV",
        "            ↓",
        "       RANKE COMPLEX",
        "  (calcified Ghon complex — visible on chest X-ray as",
        "   calcified parenchymal nodule + calcified hilar node)",
        "         |",
        "         ↓  (if immunity wanes — years/decades later)",
        "    REACTIVATION → SECONDARY TB",
        "    Apical lung cavity formation",
    ]
    E.append(CodeBox(fate_diag, bg=C['lgreen'], border=C['green']))
    E.append(sp(0.2))

    E += sub_banner("FATE — DETAILED COMPARISON TABLE", C['green'])
    E += table(
        ["Fate", "Mechanism", "Pathology", "Clinical/Imaging"],
        [
            ("RESOLUTION (95%)", "Th1/IFN-γ immune containment", "Fibrosis → calcification", "Ranke complex on CXR"),
            ("PROGRESSIVE PRIMARY TB (5%)", "Immunocompromise: HIV, malnutrition, infants", "Caseous pneumonia, lobar consolidation; NO granulomas in HIV — sheets of macrophages with AFB", "Consolidation; no nodule"),
            ("MILIARY TB", "Haematogenous dissemination via erosion into blood vessel", "1–2 mm millet-seed foci in ALL organs: lung, liver, spleen, kidney, adrenal, meninges", "Classic 'snowstorm' pattern on CXR"),
            ("TB MENINGITIS", "Haematogenous / lymphatic spread; subependymal granuloma ruptures into CSF", "Basal exudate, endarteritis, cranial nerve palsies, hydrocephalus", "Contrast-enhancing meningeal enhancement"),
            ("PLEURAL EFFUSION", "DTH reaction to TB antigens in pleural space (not direct invasion)", "Serous lymphocytic exudate; occasional granulomas on pleural biopsy", "Exudative lymphocytic effusion"),
            ("REACTIVATION (Secondary TB)", "Waning immunity (age, steroid, HIV, TNF inhibitors)", "APICAL lung cavity + fibrosis; caseation + liquefaction; spread via bronchus", "Apical cavitating shadow on CXR; AFB+ve sputum"),
        ],
        cw=[3*cm, 3.5*cm, 5*cm, 3*cm], hbg=C['green'])

    E += sub_banner("KEY TERMINOLOGY — MUST KNOW FOR MUHS", C['navy'])
    E += table(
        ["Term", "Definition"],
        [
            ("Ghon Focus",        "Parenchymal lung lesion ONLY — 1–1.5 cm caseous nodule, subpleural"),
            ("Ghon Complex",      "Ghon Focus + Lymphangitis + Hilar/regional lymphadenopathy — all 3 together"),
            ("Ranke Complex",     "CALCIFIED Ghon Complex (healed primary TB) — visible on chest X-ray as calcified parenchymal + hilar calcification"),
            ("Primary Complex",   "Synonymous with Ghon Complex (broader term used in pathology)"),
            ("Miliary TB",        "Haematogenous dissemination → innumerable millet-seed-sized (1–2 mm) foci throughout body"),
            ("Secondary TB",      "Reactivation in previously sensitized host — classically APICAL cavitating disease"),
            ("Caseous Necrosis",  "Central cheese-like, amorphous, eosinophilic necrosis — PATHOGNOMONIC of TB"),
            ("Epithelioid Cell",  "Activated macrophage in granuloma — elongated, pale pink, oblong 'footprint' nucleus — NOT epithelial"),
            ("Langhans Giant Cell", "Fused epithelioid cells — nuclei in HORSESHOE / PERIPHERAL arrangement — TB and leprosy"),
        ],
        cw=[3.5*cm, 11*cm], hbg=C['navy'])

    E += mnemonic("Fate of Ghon Complex — 'FRAME' (5 fates for MUHS exam)",
        ["F = Fibrosis (heals with fibrous scar)",
         "R = Ranke complex (calcified Ghon complex — visible on X-ray)",
         "A = Activation/Reactivation → Secondary TB (if immunity wanes)",
         "M = Miliary spread (haematogenous dissemination)",
         "E = Erosion → Effusion (pleural) / Extension to bronchus"],
        bg=C['lgreen'], border=C['green'])

    E += mnemonic("Granuloma vs Abscess — KEY DISTINCTION",
        ["GRANULOMA (TB) = CASEOUS necrosis = dry, cheese-like, no pus = ENCLOSED",
         "ABSCESS (Pyogenic) = LIQUEFACTIVE necrosis = pus = NEUTROPHILS",
         "Caseous necrosis = ONLY in TB = PATHOGNOMONIC"],
        bg=C['lamber'], border=C['amber'])

    E.append(kf("MUHS FAVOURITE: 'List the fate of Ghon complex' = FRAME (5 fates). Ranke complex = calcified Ghon complex. Miliary = haematogenous. Caseous necrosis = pathognomonic of TB."))

    E.append(sp(0.4))
    E.append(hr(C['green']))
    E.append(sp(0.2))
    E.append(Paragraph("— END OF RAPID REVISION NOTES —", S('fin',
        fontSize=11, textColor=C['grey'], fontName='Helvetica-Bold', alignment=TA_CENTER)))
    E.append(Paragraph(
        "Robbins, Cotran &amp; Kumar — Pathologic Basis of Disease, 10e &nbsp;|&nbsp; "
        "Robbins &amp; Kumar Basic Pathology",
        S('finsub', fontSize=8, textColor=C['grey'],
          fontName='Helvetica-Oblique', alignment=TA_CENTER, spaceAfter=6)))
    return E


# ─── BUILD ───────────────────────────────────────────────────────────────────

def main():
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    doc = SimpleDocTemplate(
        OUT, pagesize=A4,
        leftMargin=2*cm, rightMargin=2*cm,
        topMargin=2.2*cm, bottomMargin=1.8*cm,
        title="MUHS 2nd MBBS Pathology Rapid Revision",
        author="Robbins & Kumar",
        subject="Malaria, Cysticercosis, Leprosy, Viral/Fungal, Primary TB, Ghon Complex",
    )

    elements = (
        cover() +
        malaria() +
        cysticercosis() +
        leprosy() +
        viral_fungal() +
        primary_tb() +
        ghon_complex()
    )

    doc.build(elements, onFirstPage=first_page, onLaterPages=later_pages)
    print(f"SUCCESS: {OUT}")


if __name__ == "__main__":
    main()
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.