Describe clinical features of diseases of various aetiology affecting all systems in the adult and geriatric population

Reading File
Asking for Preferences
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
This is a comprehensive academic reference covering clinical features of diseases of various aetiologies across all major body systems in the adult and geriatric population. Here is a structured overview of what has been covered:

What This Reference Covers

The document is organized into 10 major parts, each covering a body system with diseases grouped by aetiology:

Part I - Cardiovascular System

Ischaemic heart disease (stable angina, ACS, cardiogenic shock), heart failure (HFrEF and HFpEF), hypertension and hypertensive emergencies, valvular disease (mitral stenosis, aortic stenosis), atrial fibrillation, pericarditis, and myocarditis.

Part II - Respiratory System

Obstructive disease (COPD - "blue bloater" vs "pink puffer," asthma and life-threatening features), infectious disease (typical vs atypical pneumonia, TB with pulmonary and extrapulmonary features), restrictive/interstitial disease (IPF with Velcro crackles and clubbing), pleural disease (transudates vs exudates), and pulmonary embolism.

Part III - Neurological System

Ischaemic stroke by vascular territory (MCA, ACA, PCA, PICA/Wallenberg), haemorrhagic stroke (ICH vs SAH - thunderclap headache), degenerative diseases of the elderly (Alzheimer's disease staging, Parkinson's disease cardinal features and non-motor features, ALS/MND), multiple sclerosis (optic neuritis, INO, Lhermitte's sign), and bacterial meningitis.

Part IV - Gastrointestinal and Hepatic System

GORD and Barrett's oesophagus, peptic ulcer disease (duodenal vs gastric pattern) and complications, Crohn's disease vs ulcerative colitis (distinguishing features and extraintestinal manifestations), viral hepatitis (A/B/C), and cirrhosis with its full range of stigmata and complications (ascites, hepatic encephalopathy, varices, HRS, HCC).

Part V - Renal System

Nephrotic syndrome (causes, features, complications including VTE), nephritic syndrome, AKI (pre-renal/intrinsic/post-renal), and CKD with full uraemic syndrome features and renal osteodystrophy.

Part VI - Endocrine System

Type 1 vs Type 2 diabetes (including DKA, HHS, and all micro/macrovascular complications), hypothyroidism (including myxoedema coma and Hashimoto's), hyperthyroidism and Graves' disease (including ophthalmopathy, thyroid storm, and apathetic thyrotoxicosis in the elderly).

Part VII - Musculoskeletal and Rheumatological System

Rheumatoid arthritis (articular and extra-articular), gout (acute and chronic tophaceous), osteoarthritis (Heberden's/Bouchard's nodes), SLE (butterfly rash and SLICC criteria), and systemic sclerosis (CREST vs diffuse disease).

Part VIII - Haematological System

Anaemias (IDA with Plummer-Vinson/koilonychia/pica, anaemia of chronic disease, megaloblastic with SACDSC in B12 deficiency), acute leukaemias, chronic leukaemias (CML/CLL), and multiple myeloma (CRAB criteria, hyperviscosity).

Part IX - Geriatric Syndromes

Frailty (Fried phenotype), delirium (hyperactive vs hypoactive - most commonly missed), falls and their consequences, urinary incontinence types, and pressure ulcers (staging).

Part X - Infectious Diseases

HIV/AIDS across all stages (primary seroconversion, asymptomatic, AIDS-defining illnesses by CD4 count threshold including PCP, Toxoplasma, CMV retinitis, MAC, cryptococcal meningitis, Kaposi's sarcoma).

Key Cross-Cutting Principles for Geriatric Patients

  • Atypical presentations are the rule: confusion, falls, and functional decline replace classic symptoms
  • Polypharmacy contributes to masking, mimicking, and precipitating disease
  • Reduced physiological reserve: blunted fever, leucocytosis, and inflammatory response
  • Multimorbidity: multiple aetiologies often co-exist
  • Frailty and the Geriatric Giants: impairment in instability, immobility, intellectual decline, and incontinence are the final common pathway of many diseases

Make a short summary of this data

Summary: Clinical Features of Multi-System Disease in Adults and the Elderly


Cardiovascular

Ischaemic heart disease presents with chest pain, diaphoresis, and dyspnoea - often atypically (fatigue, confusion) in the elderly. Heart failure causes dyspnoea, oedema, and raised JVP. Valvular disease (notably aortic stenosis in the elderly) produces the classic triad of angina, syncope, and heart failure. Atrial fibrillation causes irregularly irregular pulse and carries stroke risk.

Respiratory

COPD produces chronic cough, dyspnoea, and wheeze, with two phenotypes: "blue bloater" (hypercapnic, cyanosed) and "pink puffer" (emphysematous, breathless). Pneumonia presents with fever, productive cough, and consolidation signs - atypically as confusion in the elderly. TB causes fever, night sweats, weight loss, and haemoptysis. Pulmonary embolism presents with acute dyspnoea, pleuritic pain, and tachycardia.

Neurological

Stroke causes sudden focal neurological deficits based on the vascular territory affected. Alzheimer's disease progresses from memory loss to global cognitive failure. Parkinson's disease is defined by resting tremor, rigidity, and bradykinesia. Multiple sclerosis presents with relapsing-remitting neurological episodes (optic neuritis, INO, spastic paraparesis). Bacterial meningitis presents with the classic triad of fever, neck stiffness, and altered consciousness.

Gastrointestinal and Hepatic

Peptic ulcer disease causes epigastric pain relieved (duodenal) or worsened (gastric) by food. IBD presents with bloody diarrhoea, abdominal pain, and extraintestinal features (joints, eyes, skin). Liver cirrhosis produces the classic stigmata (spider naevi, palmar erythema, jaundice) and complications: ascites, encephalopathy, variceal haemorrhage, and hepatorenal syndrome.

Renal

Nephrotic syndrome presents with oedema, proteinuria, and hypoalbuminaemia. AKI presents with oliguria and uraemic features. CKD progresses silently to uraemia, anaemia, bone disease, and cardiovascular complications; creatinine underestimates dysfunction in the elderly due to reduced muscle mass.

Endocrine

Diabetes presents with polyuria, polydipsia, and weight loss; in the elderly, HHS (extreme hyperglycaemia, no ketosis) is the dominant emergency. Hypothyroidism causes cold intolerance, weight gain, bradycardia, and hung-up reflexes. Hyperthyroidism causes heat intolerance, weight loss, tremor, and AF - presenting as "apathetic thyrotoxicosis" (depression, weight loss, AF alone) in the elderly.

Musculoskeletal

Rheumatoid arthritis causes symmetrical small joint polyarthritis with morning stiffness and systemic complications. Gout presents with acute, excruciating monoarthritis at the first MTP joint. Osteoarthritis causes activity-related joint pain with bony swelling and crepitus, no systemic inflammation. SLE presents with the butterfly rash, polyarthritis, renal disease, and serositis.

Haematological

Iron deficiency anaemia causes fatigue, pallor, koilonychia, and pica. B12 deficiency additionally causes subacute combined degeneration of the spinal cord. Multiple myeloma presents with the CRAB criteria: hyperCalcaemia, Renal failure, Anaemia, and Bone lytic lesions.

Geriatric Syndromes

The elderly present with atypical disease patterns across all systems. Key syndromes unique to this population include: frailty (weakness, exhaustion, weight loss), delirium (acute fluctuating confusion - most often hypoactive and missed), falls (leading to hip fracture and long-lie complications), urinary incontinence (stress, urge, overflow, functional), and pressure ulcers.

Core Principle: In geriatric patients, the presenting complaint is frequently non-specific - confusion, falls, or functional decline - regardless of the underlying system affected. A low threshold for investigation across all systems is essential.

Summary in 5-6 pages

Asking for Preferences
Reading File
Running Command

ls /home/daytona/skills/docx/

Running Command

mkdir -p /home/daytona/workspace/multisystem-summary && ls /home/daytona/workspace/

Writing File

~/multisystem-summary/generate.js

const {
  Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
  HeadingLevel, AlignmentType, BorderStyle, WidthType, ShadingType,
  VerticalAlign, PageNumber, PageBreak, Header, Footer, TabStopType,
  TabStopPosition
} = require('docx');
const fs = require('fs');

// ─── Helpers ────────────────────────────────────────────────────────────────

function heading1(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_1,
    spacing: { before: 280, after: 120 },
  });
}

function heading2(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_2,
    spacing: { before: 200, after: 80 },
  });
}

function heading3(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_3,
    spacing: { before: 160, after: 60 },
  });
}

function body(text) {
  return new Paragraph({
    children: [new TextRun({ text, size: 22, font: 'Calibri' })],
    spacing: { before: 60, after: 60 },
    alignment: AlignmentType.JUSTIFIED,
  });
}

function bullet(text, bold_prefix) {
  const children = [];
  if (bold_prefix) {
    children.push(new TextRun({ text: bold_prefix, bold: true, size: 21, font: 'Calibri' }));
    children.push(new TextRun({ text, size: 21, font: 'Calibri' }));
  } else {
    children.push(new TextRun({ text, size: 21, font: 'Calibri' }));
  }
  return new Paragraph({
    children,
    bullet: { level: 0 },
    spacing: { before: 40, after: 40 },
  });
}

function subbullet(text) {
  return new Paragraph({
    children: [new TextRun({ text, size: 21, font: 'Calibri' })],
    bullet: { level: 1 },
    spacing: { before: 30, after: 30 },
  });
}

function boldBody(boldPart, normalPart) {
  return new Paragraph({
    children: [
      new TextRun({ text: boldPart, bold: true, size: 22, font: 'Calibri' }),
      new TextRun({ text: normalPart, size: 22, font: 'Calibri' }),
    ],
    spacing: { before: 60, after: 60 },
    alignment: AlignmentType.JUSTIFIED,
  });
}

function spacer() {
  return new Paragraph({ text: '', spacing: { before: 40, after: 40 } });
}

function pageBreak() {
  return new Paragraph({ children: [new PageBreak()] });
}

// ─── Table helper ────────────────────────────────────────────────────────────

function makeTable(headers, rows) {
  const headerCells = headers.map(h =>
    new TableCell({
      children: [new Paragraph({
        children: [new TextRun({ text: h, bold: true, size: 20, font: 'Calibri', color: 'FFFFFF' })],
        alignment: AlignmentType.CENTER,
      })],
      shading: { type: ShadingType.SOLID, color: '1F4E79' },
      verticalAlign: VerticalAlign.CENTER,
      margins: { top: 80, bottom: 80, left: 80, right: 80 },
    })
  );

  const tableRows = [new TableRow({ children: headerCells, tableHeader: true })];

  rows.forEach((row, ri) => {
    const cells = row.map(cell =>
      new TableCell({
        children: [new Paragraph({
          children: [new TextRun({ text: cell, size: 19, font: 'Calibri' })],
          alignment: AlignmentType.LEFT,
        })],
        shading: { type: ShadingType.SOLID, color: ri % 2 === 0 ? 'D6E4F0' : 'FFFFFF' },
        margins: { top: 60, bottom: 60, left: 80, right: 80 },
      })
    );
    tableRows.push(new TableRow({ children: cells }));
  });

  return new Table({
    rows: tableRows,
    width: { size: 100, type: WidthType.PERCENTAGE },
  });
}

// ─── Title page ──────────────────────────────────────────────────────────────

const titleSection = [
  spacer(), spacer(), spacer(),
  new Paragraph({
    children: [new TextRun({
      text: 'Clinical Features of Diseases Across All Body Systems',
      bold: true, size: 40, font: 'Calibri', color: '1F4E79',
    })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 400, after: 200 },
  }),
  new Paragraph({
    children: [new TextRun({
      text: 'In the Adult and Geriatric Population',
      bold: true, size: 32, font: 'Calibri', color: '2E75B6',
    })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 100, after: 400 },
  }),
  new Paragraph({
    children: [new TextRun({
      text: 'A Multi-System Clinical Summary by Aetiology',
      italics: true, size: 24, font: 'Calibri', color: '595959',
    })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 100, after: 600 },
  }),
  new Paragraph({
    children: [new TextRun({
      text: 'Sources: Harrison\'s Principles of Internal Medicine 22e (2025)  |  Goldman-Cecil Medicine  |  Braunwald\'s Heart Disease  |  Murray & Nadel\'s Respiratory Medicine  |  Adams & Victor\'s Neurology  |  Brenner & Rector\'s The Kidney  |  Sleisenger & Fordtran\'s GI & Liver Disease  |  Firestein & Kelley\'s Rheumatology  |  Tietz Textbook of Laboratory Medicine 7e',
      size: 18, font: 'Calibri', color: '7F7F7F',
    })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 200, after: 200 },
  }),
  pageBreak(),
];

// ─── Section 1: Cardiovascular ───────────────────────────────────────────────

const cardioSection = [
  heading1('1. Cardiovascular System'),

  heading2('1.1 Ischaemic Heart Disease'),
  heading3('Stable Angina Pectoris'),
  body('Aetiology: Atherosclerotic coronary artery disease; less commonly vasospasm (Prinzmetal\'s) or microvascular dysfunction.'),
  bullet('Retrosternal chest tightness/pressure radiating to left arm, jaw, neck, or epigastrium'),
  bullet('Precipitated by exertion, cold, meals, or emotion; relieved within 2-5 minutes by rest or sublingual nitrates'),
  bullet('Duration 2-10 minutes; Levine\'s sign (clenched fist over sternum)'),
  bullet('Atypical in elderly and diabetics: dyspnoea, fatigue, or epigastric discomfort ("anginal equivalents"); silent ischaemia more frequent'),

  heading3('Acute Coronary Syndrome (ACS): NSTEMI / STEMI'),
  body('Aetiology: Atherosclerotic plaque rupture with superimposed thrombosis.'),
  bullet('Severe, crushing substernal pain >30 minutes; diaphoresis, nausea, vomiting, angor animi'),
  bullet('S4 gallop (reduced ventricular compliance); new S3 suggests LV failure; new MR murmur (papillary muscle dysfunction)'),
  bullet('Cardiogenic shock (Killip IV): hypotension, cool clammy skin, pulmonary oedema, oliguria, altered consciousness'),
  bullet('NSTEMI/Unstable angina: rest pain or minimal exertion pain with less prominent ECG changes but equally life-threatening'),

  heading2('1.2 Heart Failure'),
  bullet('Left-sided: exertional dyspnoea progressing to orthopnoea and PND; displaced apex, S3 gallop, bilateral basal crackles'),
  bullet('Right-sided: peripheral pitting oedema, raised JVP, hepatomegaly, ascites, hepatojugular reflux'),
  bullet('NYHA Class I-IV based on symptom severity at rest vs. activity'),
  bullet('Geriatric: HFpEF predominates; atypical features (falls, confusion, fatigue)'),

  heading2('1.3 Hypertension'),
  bullet('Usually asymptomatic; headache, visual disturbance in severe disease; fundoscopic grades I-IV'),
  bullet('Hypertensive emergency (BP >180/120 + end-organ damage): encephalopathy, aortic dissection (tearing pain, BP differential between arms), pulmonary oedema, AKI'),
  bullet('Elderly: isolated systolic hypertension from arterial stiffness; pseudohypertension; orthostatic hypotension'),

  heading2('1.4 Valvular Disease, AF & Pericarditis'),
  bullet('Mitral stenosis (rheumatic): dyspnoea, haemoptysis, malar flush, AF, loud S1 + opening snap + mid-diastolic rumble'),
  bullet('Aortic stenosis (degenerative/elderly): classic triad - angina (3-5yr survival), syncope (2-3yr), dyspnoea (1-2yr); slow-rising pulse, ESM radiating to carotids'),
  bullet('Atrial fibrillation: irregularly irregular pulse, palpitations, dyspnoea, thromboembolic risk; elderly often present with stroke or falls only'),
  bullet('Acute pericarditis: pleuritic chest pain, pericardial friction rub, saddle-shaped ST elevation; Beck\'s triad in tamponade (hypotension + muffled sounds + raised JVP)'),

  spacer(),
];

// ─── Section 2: Respiratory ──────────────────────────────────────────────────

const respSection = [
  heading1('2. Respiratory System'),

  heading2('2.1 Obstructive Airway Disease'),
  heading3('COPD'),
  body('Aetiology: Cigarette smoking (>90%), occupational dust, alpha-1-antitrypsin deficiency.'),
  bullet('"Blue Bloater" (chronic bronchitis): cyanosed, obese, hypercapnic, polycythaemic, cor pulmonale, oedematous'),
  bullet('"Pink Puffer" (emphysema): thin, barrel chest, pursed-lip breathing, accessory muscle use, no cyanosis'),
  bullet('Chronic productive cough, wheeze, progressive dyspnoea; AECOPD: increased sputum, dyspnoea, possible hypercapnic encephalopathy'),

  heading3('Asthma'),
  body('Aetiology: Allergic (IgE-mediated, Th2-driven) or non-allergic (aspirin-sensitive, exercise-induced, occupational).'),
  bullet('Episodic wheeze, cough (nocturnal), chest tightness, dyspnoea; diurnal variation, trigger-related, reversible'),
  bullet('Life-threatening features: silent chest, cyanosis, bradycardia, confusion, PEFR <33% predicted; pulsus paradoxus'),

  heading2('2.2 Infectious Respiratory Disease'),
  heading3('Pneumonia (CAP)'),
  bullet('Typical (S. pneumoniae): acute fever, rigors, pleuritic pain, rusty sputum; bronchial breathing, dullness, increased vocal resonance'),
  bullet('Atypical (Mycoplasma, Legionella): insidious, dry cough, prominent systemic features; Legionella - hyponatraemia, GI symptoms, deranged LFTs'),
  bullet('Geriatric: confusion/falls as sole presentation; aspiration pneumonia common (right lower lobe)'),

  heading3('Pulmonary Tuberculosis'),
  bullet('Post-primary (reactivation): fever (evening pyrexia), night sweats, weight loss, productive cough, haemoptysis; apical cavitation on CXR'),
  bullet('Extrapulmonary: TB lymphadenitis (cold abscess), TB meningitis (cranial nerve palsies), Pott\'s disease (vertebral destruction/paraplegia), miliary TB (fine micronodular CXR)'),

  heading2('2.3 Restrictive / Pleural / Vascular Disease'),
  bullet('IPF: insidious progressive dyspnoea, dry cough, bilateral basal Velcro crackles, clubbing (30-70%); UIP pattern on HRCT'),
  bullet('Pleural effusion: dyspnoea, stony dull percussion, reduced breath sounds; transudate (cardiac/hepatic/renal) vs exudate (Light\'s criteria - infection/malignancy/TB)'),
  bullet('Pulmonary embolism: acute dyspnoea, pleuritic pain, haemoptysis; tachycardia (most common sign); massive PE: obstructive shock, S1Q3T3 on ECG, raised JVP + clear lungs'),

  spacer(),
];

// ─── Section 3: Neurological ─────────────────────────────────────────────────

const neuroSection = [
  heading1('3. Neurological System'),

  heading2('3.1 Cerebrovascular Disease'),
  heading3('Ischaemic Stroke'),
  body('Aetiology: Large artery atherosclerosis, cardioembolism, small vessel disease (lacunar), cryptogenic.'),
  bullet('MCA territory (most common): contralateral hemiplegia (face/arm > leg), hemisensory loss, hemianopia; aphasia (dominant) or neglect (non-dominant)'),
  bullet('Wallenberg syndrome (PICA): crossed sensory deficit, ipsilateral Horner\'s, dysphagia, cerebellar signs'),
  bullet('Lacunar: pure motor, pure sensory, ataxic hemiparesis, dysarthria-clumsy hand'),
  bullet('TIA: focal deficit resolving <24h; amaurosis fugax ("curtain falling over eye") from carotid disease'),

  heading3('Haemorrhagic Stroke'),
  bullet('ICH: sudden onset focal deficit + decreased consciousness; hypertensive - putaminal/thalamic; CAA (elderly) - lobar haemorrhages'),
  bullet('SAH: "thunderclap headache" (worst ever, maximal at onset), meningism, photophobia, third nerve palsy (PCom aneurysm), Terson\'s syndrome (retinal haemorrhages)'),

  heading2('3.2 Degenerative Diseases (Predominantly Geriatric)'),
  heading3('Alzheimer\'s Disease'),
  body('Aetiology: Amyloid-beta plaques + neurofibrillary (tau) tangles; APOE e4 risk allele; advancing age is the greatest risk factor.'),
  bullet('Insidious onset: anterograde amnesia (earliest), word-finding difficulty, getting lost in familiar places'),
  bullet('Progresses to apraxia, agnosia, aphasia, behavioural/psychiatric symptoms (delusions, hallucinations), loss of ADLs'),
  bullet('Terminal: non-verbal, immobile, doubly incontinent; death from aspiration pneumonia/sepsis'),

  heading3('Parkinson\'s Disease'),
  body('Aetiology: Loss of dopaminergic neurons in substantia nigra; Lewy body (alpha-synuclein) accumulation.'),
  bullet('Cardinal motor features: resting "pill-rolling" tremor (4-6 Hz), cogwheel rigidity, bradykinesia (micrographia, hypomimia, shuffling gait, festination), postural instability (late)'),
  bullet('Non-motor: anosmia (precedes motor symptoms), constipation, REM sleep behaviour disorder, orthostatic hypotension, depression, PD dementia (80% if followed long enough)'),

  heading3('ALS / Motor Neurone Disease'),
  bullet('Combined UMN + LMN signs: fasciculations + wasting (LMN) + spasticity + Babinski (UMN)'),
  bullet('Limb onset: focal weakness (wrist drop, foot drop); Bulbar onset: dysarthria, dysphagia, tongue fasciculations'),
  bullet('Progressive respiratory failure; eye movements and sphincters spared (key differentiating feature)'),

  heading2('3.3 Demyelinating and Infectious'),
  bullet('Multiple sclerosis: relapsing-remitting episodes - optic neuritis (painful visual loss, RAPD), INO, spastic paraparesis, Lhermitte\'s sign, fatigue; Uhthoff\'s phenomenon'),
  bullet('Bacterial meningitis: classic triad (fever + neck stiffness + altered consciousness); Kernig\'s/Brudzinski\'s signs; non-blanching purpuric rash (meningococcal septicaemia); Waterhouse-Friderichsen syndrome'),
  bullet('Geriatric: neck stiffness absent or attributed to cervical spondylosis; Listeria more common; only altered mental status + low-grade fever'),

  spacer(),
];

// ─── Section 4: GI and Liver ─────────────────────────────────────────────────

const giSection = [
  heading1('4. Gastrointestinal and Hepatic System'),

  heading2('4.1 Upper GI Disease'),
  bullet('GORD: heartburn, acid regurgitation, water brash; extra-oesophageal features (cough, laryngitis, asthma); Barrett\'s oesophagus - adenocarcinoma risk'),
  bullet('Duodenal ulcer (H. pylori, NSAIDs): epigastric pain relieved by food, nocturnal pain, periodicity'),
  bullet('Gastric ulcer: epigastric pain worsened by food, weight loss; complications: haemorrhage (haematemesis, melaena), perforation (board-like abdomen, rebound), pyloric obstruction (projectile vomiting, succussion splash, hypokalaemic alkalosis)'),

  heading2('4.2 Inflammatory Bowel Disease'),
  heading3('Crohn\'s Disease'),
  body('Transmural inflammation; skip lesions; any site mouth to anus; smoking increases risk.'),
  bullet('Diarrhoea (may be bloody), RIF pain/mass, weight loss, fever; perianal disease (fistulae, abscesses - 20-30%)'),
  bullet('Strictures (obstruction), fistulae (pneumaturia, faeculent vaginal discharge); B12 malabsorption (terminal ileum)'),
  bullet('Extra-intestinal: arthropathy, uveitis/episcleritis, erythema nodosum, pyoderma gangrenosum, PSC, oxalate renal stones'),

  heading3('Ulcerative Colitis'),
  body('Mucosal inflammation; continuous from rectum; smoking is protective.'),
  bullet('Bloody diarrhoea (hallmark), tenesmus, urgency; severity by Truelove & Witts criteria'),
  bullet('Toxic megacolon: >6 cm dilatation on AXR, fever, peritonism - risk of perforation'),
  bullet('Long-term colorectal carcinoma risk; PSC (5% of UC; 75% of PSC patients have UC)'),

  heading2('4.3 Liver Cirrhosis'),
  body('Aetiology: Alcohol, chronic HBV/HCV, NAFLD/NASH (metabolic syndrome), autoimmune hepatitis, PBC, PSC, haemochromatosis, Wilson\'s disease.'),
  bullet('Stigmata: spider naevi, palmar erythema, leukonychia, gynaecomastia, testicular atrophy, caput medusae, Dupuytren\'s contracture (alcohol), parotid enlargement'),
  bullet('Decompensation features:'),
  subbullet('Ascites: shifting dullness, fluid thrill; SBP if fever + abdominal pain + deteriorating LFTs'),
  subbullet('Hepatic encephalopathy: asterixis (hepatic flap), fetor hepaticus, personality change, grades I-IV'),
  subbullet('Variceal haemorrhage: haematemesis/melaena, haemodynamic compromise'),
  subbullet('Hepatorenal syndrome: functional AKI, oliguria, hyponatraemia'),
  subbullet('HCC: rapid clinical deterioration, RUQ pain, paraneoplastic features (hypoglycaemia, erythrocytosis)'),

  spacer(),
];

// ─── Section 5: Renal & Endocrine ────────────────────────────────────────────

const renalEndoSection = [
  heading1('5. Renal and Endocrine Systems'),

  heading2('5.1 Renal Disease'),
  bullet('Nephrotic syndrome: proteinuria >3.5g/24h, hypoalbuminaemia, oedema (periorbital + peripheral), frothy urine, hyperlipidaemia; VTE risk (loss of AT-III, proteins S/C); infection risk; causes - MCD (elderly), membranous nephropathy (adults, anti-PLA2R), diabetic nephropathy (most common worldwide)'),
  bullet('Nephritic syndrome: haematuria (red cell casts), sub-nephrotic proteinuria, hypertension, oliguria, AKI; causes - post-streptococcal GN, IgA nephropathy, ANCA vasculitis, anti-GBM disease, lupus nephritis'),
  bullet('AKI: oliguria/anuria, uraemia (nausea, hiccups, pericarditis), hyperkalaemia (peaked T-waves, widened QRS), fluid overload; Pre-renal (most common - dehydration, CCF), intrinsic (ATN, GN, AIN), post-renal (BPH most common in elderly men)'),
  bullet('CKD: Stages 1-3 silent; Stages 4-5 - uraemic syndrome (fatigue, pruritus, nausea, neuropathy), secondary hyperparathyroidism/renal osteodystrophy (subperiosteal erosions, salt-and-pepper skull), LVH, platelet dysfunction; creatinine underestimates CKD severity in the elderly'),

  heading2('5.2 Diabetes Mellitus'),
  bullet('T1DM: acute onset polyuria/polydipsia/weight loss; DKA - Kussmaul breathing, ketotic (sweet/fruity) fetor, dehydration, vomiting, altered consciousness'),
  bullet('T2DM: often asymptomatic/incidental; recurrent genital candidiasis, skin infections; HHS in elderly (extreme hyperglycaemia >30 mmol/L, no/minimal ketosis, severe dehydration, altered consciousness, focal neurological deficits - high mortality)'),
  bullet('Chronic complications: Microvascular - retinopathy (background → proliferative), nephropathy (microalbuminuria → CKD), neuropathy (glove-and-stocking, painful nocturnal, autonomic - gastroparesis, postural hypotension, erectile dysfunction)'),
  bullet('Macrovascular: CAD (leading cause of death in T2DM), PAD (claudication, Charcot foot), stroke'),

  heading2('5.3 Thyroid Disease'),
  bullet('Hypothyroidism: cold intolerance, weight gain, constipation, bradycardia, dry skin/hair, periorbital/peripheral non-pitting myxoedema, hung-up reflexes, Queen Anne\'s sign (loss of outer eyebrow); myxoedema coma (hypothermia, hypoventilation, coma); elderly - mimics normal aging, frequently missed'),
  bullet('Hyperthyroidism: heat intolerance, weight loss, tremor, anxiety, diarrhoea, tachycardia/AF, warm moist skin, proximal myopathy, lid lag, lid retraction'),
  bullet('Graves\' disease specific: goitre (smooth), exophthalmos/proptosis, periorbital oedema, diplopia, optic neuropathy, pretibial myxoedema, thyroid acropachy'),
  bullet('Apathetic thyrotoxicosis (elderly): AF, weight loss, depression, weakness - without classic sympathomimetic features; easily missed'),
  bullet('Thyroid storm: extreme hyperthyroidism, hyperthermia, delirium, cardiac failure; 20-30% mortality'),

  spacer(),
];

// ─── Section 6: Musculoskeletal & Haematological ─────────────────────────────

const mskHaemSection = [
  heading1('6. Musculoskeletal, Rheumatological and Haematological Systems'),

  heading2('6.1 Inflammatory Arthritis and Connective Tissue Disease'),
  heading3('Rheumatoid Arthritis'),
  bullet('Symmetrical small joint polyarthritis: MCPJs, PIPJs, wrists, MTPs; DIPJs spared; morning stiffness >1 hour'),
  bullet('Swan neck/boutonniere deformities, ulnar deviation, Z-thumb, rheumatoid nodules (olecranon)'),
  bullet('Extra-articular: ILD, pleuritis, episcleritis, secondary Sjogren\'s, anaemia, Felty\'s syndrome (RA + splenomegaly + neutropenia), mononeuritis multiplex, atlanto-axial instability (cervical myelopathy), secondary AA amyloidosis'),

  heading3('Gout and Osteoarthritis'),
  bullet('Gout: sudden onset nocturnal monoarthritis (podagra - 1st MTP); exquisitely tender, erythematous, swollen; tophi (helix of ear, Achilles tendon); urate nephropathy; precipitants: alcohol, diuretics, dehydration, surgery'),
  bullet('Osteoarthritis: activity-related joint pain (improves with rest), bony hard swelling (osteophytes), crepitus, restricted ROM; no systemic inflammation; Heberden\'s nodes (DIPJs), Bouchard\'s nodes (PIPJs), first CMC "square thumb"; most common cause of disability >65 years'),

  heading3('SLE and Systemic Sclerosis'),
  bullet('SLE: butterfly rash (spares nasolabial folds), photosensitivity, oral ulcers, non-erosive arthritis, serositis, lupus nephritis, neuropsychiatric (seizures, psychosis), haemolytic anaemia/leucopenia/thrombocytopenia, antiphospholipid syndrome'),
  bullet('Limited SSc (CREST): Calcinosis, Raynaud\'s (first symptom by years), Oesophageal dysmotility, Sclerodactyly, Telangiectasia; anti-centromere antibodies; complication: pulmonary arterial hypertension'),
  bullet('Diffuse SSc: rapid extensive skin fibrosis, ILD (leading cause of death), scleroderma renal crisis (malignant hypertension, AKI), myocarditis; anti-Scl-70 antibodies'),

  heading2('6.2 Anaemias'),
  bullet('Iron deficiency: fatigue, pallor, koilonychia (spoon nails), angular stomatitis, glossitis, pica, Plummer-Vinson syndrome (dysphagia + post-cricoid web + IDA); restless legs; most important cause in elderly men/post-menopausal women - exclude GI malignancy/angiodysplasia'),
  bullet('Megaloblastic (B12/folate): lemon-yellow pallor, glossitis, angular stomatitis; B12-specific - subacute combined degeneration of spinal cord (posterior columns + lateral corticospinal tracts: paraesthesiae → ataxia → spasticity), dementia, psychosis; folate deficiency does NOT cause neurological complications'),
  bullet('Anaemia of chronic disease: mild-moderate normochromic normocytic anaemia; low serum iron + low TIBC + elevated ferritin; underlying disease (RA, IBD, CKD, malignancy) dominates clinical picture'),

  heading2('6.3 Haematological Malignancies'),
  bullet('Acute leukaemia (AML/ALL): bone marrow failure triad - anaemia + neutropenic infections + thrombocytopenic bleeding; organ infiltration: hepatosplenomegaly, lymphadenopathy (ALL > AML), CNS disease, gum hypertrophy (AML M5), DIC (APL/AML M3)'),
  bullet('CML (BCR-ABL t(9;22)): massive splenomegaly, constitutional symptoms; often incidental leucocytosis; blast crisis = acute leukaemia features'),
  bullet('CLL: painless lymphadenopathy, splenomegaly, fatigue; autoimmune AIHA; hypogammaglobulinaemia (recurrent infections); Richter\'s transformation (sudden nodal enlargement, systemic symptoms)'),
  bullet('Multiple myeloma (CRAB): Hypercalcaemia (confusion, constipation, polyuria), Renal failure (light chain cast nephropathy), Anaemia (normochromic normocytic), Bone pain/lytic lesions/pathological fractures; recurrent infections; hyperviscosity syndrome (headache, visual disturbance, bleeding)'),

  spacer(),
];

// ─── Section 7: Geriatric Syndromes & Infectious Disease ─────────────────────

const geriatricInfSection = [
  heading1('7. Geriatric Syndromes and Systemic Infectious Disease'),

  heading2('7.1 Geriatric Syndromes'),
  heading3('Frailty'),
  bullet('Fried phenotype (3/5 criteria = frail): unintentional weight loss, exhaustion, weakness (reduced grip strength), slow gait speed, low physical activity'),
  bullet('Sarcopenia underlies frailty; increased risk of falls, hospitalisation, disability, death'),

  heading3('Delirium (Acute Confusional State)'),
  body('Aetiology: Any acute illness in a vulnerable elder; infection (UTI, pneumonia), drugs (opioids, anticholinergics, benzodiazepines), dehydration, urinary retention, pain, alcohol withdrawal, stroke, metabolic.'),
  bullet('Acute onset + fluctuating course (key distinction from dementia)'),
  bullet('Hyperactive delirium: agitation, hallucinations (visual), combativeness - often misdiagnosed as acute psychosis'),
  bullet('Hypoactive delirium (most common, most missed): withdrawal, drowsiness, reduced responsiveness - attributed to "tiredness" or "dementia"'),
  bullet('Autonomic instability, sleep-wake cycle disruption, disorganised speech/thinking'),

  heading3('Falls, Incontinence and Pressure Ulcers'),
  bullet('Falls: hip fracture (shortened/externally rotated limb), subdural haematoma, "long lie" (hypothermia, rhabdomyolysis, aspiration); fear of falling causes deconditioning'),
  bullet('Urinary incontinence types: Stress (exertion-triggered, sphincter weakness), Urge (OAB, detrusor overactivity), Overflow (BPH/detrusor underactivity - dribbling), Functional (mobility/cognitive impairment)'),
  bullet('Pressure ulcers: Stage 1 (non-blanchable erythema) → Stage 2 (partial thickness) → Stage 3 (full thickness, subcutaneous exposed) → Stage 4 (bone/muscle exposed); risk: immobility, malnutrition, incontinence, reduced sensation'),

  heading2('7.2 HIV/AIDS'),
  body('Aetiology: HIV-1/2; transmission - sexual (most common), IVDU, vertical, blood products.'),
  bullet('Primary seroconversion (2-6 weeks): mononucleosis-like illness - fever, sore throat, lymphadenopathy, maculopapular rash, oral/genital ulcers, diarrhoea'),
  bullet('Asymptomatic phase (median 10 years): persistent generalised lymphadenopathy'),
  bullet('AIDS-defining conditions by CD4 count:'),
  subbullet('CD4 <200: PCP (exertional dyspnoea, dry cough, bilateral perihilar infiltrates, elevated LDH), oesophageal candidiasis (dysphagia, odynophagia)'),
  subbullet('CD4 <100: Toxoplasma encephalitis (ring-enhancing lesions, focal deficits, seizures), cryptococcal meningitis (raised ICP, India ink positive)'),
  subbullet('CD4 <50: CMV retinitis ("pizza pie" fundus), MAC (fever, night sweats, diarrhoea, hepatosplenomegaly)'),
  subbullet('Kaposi\'s sarcoma: purple/brown vascular lesions on skin/palate/GI tract (HIV-8); CNS lymphoma (EBV-associated); HIV-associated dementia'),

  spacer(),
];

// ─── Summary Table ────────────────────────────────────────────────────────────

const summaryTableSection = [
  heading1('8. Rapid Reference: Key Differentiating Clinical Features by System and Aetiology'),
  spacer(),
  makeTable(
    ['System', 'Ischaemic / Vascular', 'Inflammatory / Autoimmune', 'Infectious', 'Neoplastic', 'Degenerative'],
    [
      ['Cardiac', 'Chest pain, diaphoresis, ECG changes, cardiogenic shock', 'Pleuritic pain, friction rub, pericardial effusion, troponin rise', 'Fever, viral prodrome, myocarditis, pericarditis', 'Cachexia, pericardial effusion, arrhythmia', 'Progressive HF, cardiomyopathy'],
      ['Respiratory', 'Acute dyspnoea, pleurisy, haemoptysis (PE)', 'Wheeze, eosinophilia, steroid-responsive (asthma)', 'Fever, productive cough, consolidation signs', 'Haemoptysis, weight loss, clubbing, lymphadenopathy', 'Progressive dyspnoea, basal Velcro crackles (IPF)'],
      ['Neurological', 'Sudden focal deficit, FAST symptoms, thunderclap headache', 'Relapsing-remitting episodes, optic neuritis, INO, Lhermitte\'s', 'Fever + meningism + purpuric rash, Kernig\'s/Brudzinski\'s', 'Progressive focal deficit, raised ICP, headache', 'Insidious cognitive decline, resting tremor, rigidity'],
      ['GI / Liver', 'Mesenteric ischaemia: severe periumbilical pain, bloody diarrhoea', 'IBD: bloody diarrhoea, EIM, abdominal pain, weight loss', 'Fever, diarrhoea, food history, jaundice (hepatitis)', 'Anorexia, weight loss, altered bowel habit, melaena, jaundice (HCC)', 'Cirrhosis stigmata, ascites, encephalopathy, varices'],
      ['Renal', 'Pre-renal AKI: oliguria, reduced JVP, dehydration history', 'Haematuria, proteinuria, red cell casts, systemic disease features', 'Fever, dysuria, loin pain, pyuria (pyelonephritis)', 'Painless haematuria, abdominal mass, weight loss', 'Gradual GFR decline, uraemia, CKD-MBD, anaemia'],
      ['Endocrine', '- ', 'Heat intolerance, weight loss, AF (thyrotoxicosis)', 'Fever, hypotension, adrenal crisis in sepsis', 'Hypercalcaemia (PTHrP), Cushing\'s paraneoplastic', 'Cold intolerance, weight gain, bradycardia, hung-up reflexes (hypothyroid)'],
      ['Musculoskeletal', 'AVN (osteonecrosis): joint pain, steroid/alcohol history', 'Morning stiffness >1h, symmetric polyarthritis, systemic features', 'Acute monoarthritis, fever, skin lesions (septic/gonococcal)', 'Bone pain, pathological fractures, lytic lesions (myeloma)', 'Activity-related pain, bony swelling, crepitus, no systemic features (OA)'],
      ['Haematological', 'DVT/PE risk in polycythaemia, hyperviscosity syndrome (myeloma)', 'Haemolytic anaemia, thrombocytopenia (ITP), AIHA in CLL', 'Fever, neutropenia, bone marrow infiltration, splenomegaly', 'Anaemia, thrombocytopenia, lymphadenopathy, hepatosplenomegaly', 'Normochromic normocytic anaemia of chronic disease'],
    ]
  ),
  spacer(),
];

// ─── Section 9: Geriatric Principles ─────────────────────────────────────────

const geriatricPrinciplesSection = [
  heading1('9. Core Principles: Disease Presentation in the Geriatric Population'),
  body('The geriatric population consistently manifests disease differently from younger adults due to the following key physiological changes and clinical principles:'),
  spacer(),
  boldBody('1. Atypical Presentations: ', 'Classic symptoms are frequently absent. Confusion, falls, or functional decline may be the only manifestation of ACS, sepsis, stroke, or pulmonary embolism. A high index of suspicion and low threshold for investigation across all systems is essential.'),
  boldBody('2. Polypharmacy Effects: ', 'Multiple medications contribute to drug interactions, adverse effects, and masking of true disease (e.g., anticholinergic burden causing cognitive impairment; beta-blockers masking hypoglycaemia).'),
  boldBody('3. Reduced Physiological Reserve: ', 'Inflammatory response is blunted - absence of fever and leucocytosis common even in severe sepsis. Renal clearance, hepatic metabolism, and cardiac reserve are all reduced.'),
  boldBody('4. Multimorbidity: ', 'Multiple co-existing conditions complicate diagnosis and management. A presenting complaint may have several simultaneous aetiologies; treating one condition may exacerbate another.'),
  boldBody('5. Geriatric Giants (Impaired): ', 'Instability (falls), Immobility, Intellectual decline (dementia/delirium), Incontinence - these four syndromes are often the final common pathway of multiple underlying diseases across all systems.'),
  boldBody('6. Cognitive Impairment as a Confounder: ', 'Dementia impairs symptom reporting. Proxy history from carers, collateral from family, and careful clinical observation are essential to accurate diagnosis.'),
  boldBody('7. Delirium vs. Dementia: ', 'Delirium is acute and fluctuating (hours to days); dementia is insidious and progressive (months to years). Delirium superimposed on dementia is common and carries poor prognosis. Hypoactive delirium (withdrawn, drowsy) is frequently missed.'),
  spacer(),
  body('Sources: Harrison\'s Principles of Internal Medicine 22e (McGraw Hill, 2025); Goldman-Cecil Medicine; Braunwald\'s Heart Disease 12e; Fuster & Hurst\'s The Heart 15e; Murray & Nadel\'s Respiratory Medicine 7e; Adams & Victor\'s Principles of Neurology 12e; Brenner & Rector\'s The Kidney 11e; Sleisenger & Fordtran\'s GI & Liver Disease 11e; Firestein & Kelley\'s Textbook of Rheumatology 11e; Tietz Textbook of Laboratory Medicine 7e.'),
];

// ─── Assemble Document ────────────────────────────────────────────────────────

const doc = new Document({
  title: 'Clinical Features of Multi-System Disease - Adult and Geriatric Population',
  description: 'A comprehensive academic summary organized by body system and aetiology',
  styles: {
    paragraphStyles: [
      {
        id: 'Heading1',
        name: 'Heading 1',
        basedOn: 'Normal',
        next: 'Normal',
        run: { size: 28, bold: true, color: '1F4E79', font: 'Calibri' },
        paragraph: {
          spacing: { before: 300, after: 120 },
          border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: '2E75B6', space: 4 } },
        },
      },
      {
        id: 'Heading2',
        name: 'Heading 2',
        basedOn: 'Normal',
        next: 'Normal',
        run: { size: 24, bold: true, color: '2E75B6', font: 'Calibri' },
        paragraph: { spacing: { before: 200, after: 80 } },
      },
      {
        id: 'Heading3',
        name: 'Heading 3',
        basedOn: 'Normal',
        next: 'Normal',
        run: { size: 22, bold: true, italics: true, color: '1F4E79', font: 'Calibri' },
        paragraph: { spacing: { before: 160, after: 60 } },
      },
    ],
  },
  sections: [
    {
      headers: {
        default: new Header({
          children: [
            new Paragraph({
              children: [
                new TextRun({ text: 'Clinical Features of Multi-System Disease - Adult & Geriatric Population', size: 18, font: 'Calibri', color: '7F7F7F', italics: true }),
              ],
              alignment: AlignmentType.CENTER,
            }),
          ],
        }),
      },
      footers: {
        default: new Footer({
          children: [
            new Paragraph({
              children: [
                new TextRun({ text: 'Page ', size: 18, font: 'Calibri', color: '7F7F7F' }),
                new TextRun({ children: [PageNumber.CURRENT], size: 18, font: 'Calibri', color: '7F7F7F' }),
                new TextRun({ text: ' of ', size: 18, font: 'Calibri', color: '7F7F7F' }),
                new TextRun({ children: [PageNumber.TOTAL_PAGES], size: 18, font: 'Calibri', color: '7F7F7F' }),
              ],
              alignment: AlignmentType.CENTER,
            }),
          ],
        }),
      },
      children: [
        ...titleSection,
        ...cardioSection,
        ...respSection,
        ...neuroSection,
        ...giSection,
        ...renalEndoSection,
        ...mskHaemSection,
        ...geriatricInfSection,
        ...summaryTableSection,
        ...geriatricPrinciplesSection,
      ],
    },
  ],
});

Packer.toBuffer(doc).then(buffer => {
  fs.writeFileSync('/home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary.docx', buffer);
  console.log('Document created successfully.');
});
Running Command

cd /home/daytona/workspace/multisystem-summary && node generate.js 2>&1

Running Command

python3 /home/daytona/skills/docx/scripts/office/validate.py /home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary.docx 2>&1

Running Command

cd /home/daytona/workspace/multisystem-summary && python3 -c " import zipfile, os docx = 'MultiSystem_Disease_Summary.docx' if zipfile.is_zipfile(docx): with zipfile.ZipFile(docx) as z: print('Valid ZIP/DOCX. Files inside:', z.namelist()[:10]) size = os.path.getsize(docx) print(f'File size: {size} bytes ({size/1024:.1f} KB)') else: print('NOT a valid DOCX/ZIP file') "

The document is valid and ready for download.

MultiSystem Disease Summary

Word Document · DOCX


Here is what the 5-6 page Word document contains, fully formatted with headers, bullet points, a colour summary table, page numbers, and a running header:
SectionContent
Title PageFull title, subtitle, source list
1. CardiovascularAngina, ACS, heart failure (NYHA), hypertension, valvular disease, AF, pericarditis
2. RespiratoryCOPD (blue bloater/pink puffer), asthma, CAP, TB (pulmonary + extrapulmonary), IPF, pleural effusion, PE
3. NeurologicalStroke by territory, ICH, SAH, Alzheimer's, Parkinson's, ALS, MS, bacterial meningitis
4. GI & HepaticGORD, PUD + complications, Crohn's vs UC, liver cirrhosis + all decompensation complications
5. Renal & EndocrineNephrotic/nephritic syndrome, AKI, CKD, T1DM/T2DM, hypothyroidism, hyperthyroidism/Graves'
6. MSK & HaematologicalRA, gout, OA, SLE, systemic sclerosis, IDA, megaloblastic anaemia, leukaemias, myeloma
7. Geriatric & InfectionsFrailty, delirium (hyperactive vs hypoactive), falls, incontinence, pressure ulcers, HIV/AIDS by CD4 count
8. Rapid Reference Table8 systems x 5 aetiologies - key differentiating features at a glance
9. Geriatric Principles7 core principles of atypical geriatric disease presentation

Make pdf and all in black and white only and remove references and all just topic and discussion

Reading File
Writing File

~/multisystem-summary/generate_pdf.py

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

# ── Output path ──────────────────────────────────────────────────────────────
OUTPUT = '/home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary_BW.pdf'

# ── Page setup ───────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=2*cm,
    rightMargin=2*cm,
    topMargin=2.2*cm,
    bottomMargin=2.2*cm,
    title='Clinical Features of Multi-System Disease in Adults and the Geriatric Population',
)

W = A4[0] - 4*cm   # usable width

# ── Styles ───────────────────────────────────────────────────────────────────
BASE = getSampleStyleSheet()

TITLE = ParagraphStyle('Title', fontName='Helvetica-Bold', fontSize=18,
                        leading=22, alignment=TA_CENTER, textColor=black,
                        spaceAfter=4)
SUBTITLE = ParagraphStyle('Subtitle', fontName='Helvetica-Oblique', fontSize=12,
                           leading=16, alignment=TA_CENTER, textColor=black,
                           spaceAfter=12)
H1 = ParagraphStyle('H1', fontName='Helvetica-Bold', fontSize=13,
                     leading=16, textColor=black, spaceBefore=14, spaceAfter=4,
                     borderPad=2)
H2 = ParagraphStyle('H2', fontName='Helvetica-Bold', fontSize=11,
                     leading=14, textColor=black, spaceBefore=10, spaceAfter=3)
H3 = ParagraphStyle('H3', fontName='Helvetica-BoldOblique', fontSize=10,
                     leading=13, textColor=black, spaceBefore=7, spaceAfter=2)
BODY = ParagraphStyle('Body', fontName='Helvetica', fontSize=9.5,
                       leading=13, alignment=TA_JUSTIFY, textColor=black,
                       spaceAfter=4)
BULLET = ParagraphStyle('Bullet', fontName='Helvetica', fontSize=9.5,
                         leading=13, alignment=TA_JUSTIFY, textColor=black,
                         leftIndent=14, firstLineIndent=-10, spaceAfter=2)
SUBBULLET = ParagraphStyle('SubBullet', fontName='Helvetica', fontSize=9,
                            leading=12, textColor=black,
                            leftIndent=26, firstLineIndent=-10, spaceAfter=2)
NOTE = ParagraphStyle('Note', fontName='Helvetica-Oblique', fontSize=8.5,
                       leading=11, textColor=black, spaceAfter=6, alignment=TA_CENTER)

def h1(text):
    return [
        HRFlowable(width='100%', thickness=1.5, color=black, spaceAfter=2),
        Paragraph(text.upper(), H1),
        HRFlowable(width='100%', thickness=0.5, color=black, spaceAfter=4),
    ]

def h2(text):
    return Paragraph(text, H2)

def h3(text):
    return Paragraph(text, H3)

def body(text):
    return Paragraph(text, BODY)

def bl(text, bold=''):
    if bold:
        return Paragraph(f'\u2022  <b>{bold}</b>{text}', BULLET)
    return Paragraph(f'\u2022  {text}', BULLET)

def sbl(text):
    return Paragraph(f'\u2013  {text}', SUBBULLET)

def sp(h=4):
    return Spacer(1, h)

def pb():
    return PageBreak()

# ── Summary Table ─────────────────────────────────────────────────────────────
def make_table(headers, rows):
    col_widths = [2.8*cm, 3.1*cm, 3.1*cm, 3.1*cm, 3.1*cm, 3.1*cm]
    data = [[Paragraph(f'<b>{h}</b>', ParagraphStyle('TH', fontName='Helvetica-Bold',
              fontSize=8, leading=10, textColor=white, alignment=TA_CENTER)) for h in headers]]
    for i, row in enumerate(rows):
        data.append([Paragraph(cell, ParagraphStyle('TD', fontName='Helvetica',
                    fontSize=7.5, leading=10, textColor=black)) for cell in row])
    tbl = Table(data, colWidths=col_widths, repeatRows=1)
    style = TableStyle([
        ('BACKGROUND', (0,0), (-1,0), black),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [HexColor('#E8E8E8'), white]),
        ('GRID', (0,0), (-1,-1), 0.4, black),
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('TOPPADDING', (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING', (0,0), (-1,-1), 4),
        ('RIGHTPADDING', (0,0), (-1,-1), 4),
    ])
    tbl.setStyle(style)
    return tbl

# ── Content ───────────────────────────────────────────────────────────────────
story = []

# ── TITLE PAGE ────────────────────────────────────────────────────────────────
story += [
    sp(60),
    Paragraph('Clinical Features of Diseases Across All Body Systems', TITLE),
    Paragraph('In the Adult and Geriatric Population', SUBTITLE),
    HRFlowable(width='80%', thickness=1, color=black, spaceAfter=10),
    Paragraph('A Multi-System Clinical Summary by Aetiology', NOTE),
    sp(8),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 1. CARDIOVASCULAR SYSTEM
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('1. Cardiovascular System')

story += [h2('1.1  Ischaemic Heart Disease'), sp(2)]
story += [h3('Stable Angina Pectoris')]
story += [
    bl('Retrosternal chest tightness or pressure radiating to the left arm, jaw, neck, or epigastrium; precipitated by exertion, cold, meals, or emotional stress.'),
    bl('Relieved within 2-5 minutes by rest or sublingual nitrates; duration 2-10 minutes; Levine\'s sign (clenched fist over sternum).'),
    bl('Elderly and diabetics: atypical presentations - dyspnoea, fatigue, or epigastric discomfort ("anginal equivalents"); silent ischaemia more frequent due to altered pain perception.'),
    sp(4),
]

story += [h3('Acute Coronary Syndrome (ACS): NSTEMI / STEMI')]
story += [
    bl('Severe, crushing substernal pain >30 minutes; diaphoresis, nausea, vomiting, sense of impending doom (angor animi); radiation to left arm, jaw, or back.'),
    bl('S4 gallop (reduced ventricular compliance); new S3 indicates LV failure; new mitral regurgitation murmur suggests papillary muscle dysfunction.'),
    bl('Cardiogenic shock (Killip Class IV): persistent hypotension, cool clammy skin, pulmonary oedema, oliguria, altered consciousness - requires vasopressors.'),
    bl('NSTEMI/Unstable angina: rest or minimal exertion pain, fewer ECG changes but equally life-threatening.'),
    sp(4),
]

story += [h2('1.2  Chronic Heart Failure'), sp(2)]
story += [
    bl('Left-sided failure: progressive exertional dyspnoea, orthopnoea, paroxysmal nocturnal dyspnoea; displaced apex beat, S3 gallop, bilateral basal crackles, pleural effusion.'),
    bl('Right-sided failure: bilateral pitting oedema, raised JVP, hepatomegaly, ascites; positive hepatojugular reflux.'),
    bl('NYHA classification grades symptom severity from Class I (no limitation) to Class IV (symptoms at rest).'),
    bl('Geriatric: HFpEF (preserved ejection fraction) predominates; atypical features - falls, confusion, fatigue without obvious dyspnoea.'),
    sp(4),
]

story += [h2('1.3  Hypertension'), sp(2)]
story += [
    bl('Usually asymptomatic; headache (occipital, morning), visual disturbance, epistaxis in severe disease.'),
    bl('Fundoscopic grading: Grade I-II (arterial changes/AV nipping); Grade III-IV (haemorrhages, cotton wool spots, papilloedema) indicates hypertensive emergency.'),
    bl('Hypertensive emergency (BP >180/120 + end-organ damage): encephalopathy, aortic dissection (tearing pain, BP differential between arms), acute pulmonary oedema, AKI.'),
    bl('Elderly: isolated systolic hypertension (reduced aortic compliance); orthostatic hypotension complicates treatment; pseudohypertension (Osler\'s sign).'),
    sp(4),
]

story += [h2('1.4  Valvular Disease, Arrhythmia and Pericarditis'), sp(2)]
story += [
    bl('Mitral stenosis (rheumatic): dyspnoea, haemoptysis, malar flush, atrial fibrillation; loud S1 + opening snap + mid-diastolic rumble at apex.'),
    bl('Aortic stenosis (degenerative/elderly): classic triad - angina (3-5yr survival), syncope (2-3yr), dyspnoea/heart failure (1-2yr); slow-rising pulse, ejection systolic murmur radiating to carotids.'),
    bl('Atrial fibrillation: irregularly irregular pulse, palpitations, dyspnoea; major thromboembolic risk; elderly often present with stroke, falls, or fatigue as the only feature.'),
    bl('Acute pericarditis: sharp pleuritic chest pain relieved by leaning forward; scratchy triphasic friction rub; saddle-shaped ST elevation. Beck\'s triad in tamponade: hypotension + muffled heart sounds + raised JVP.'),
    bl('Myocarditis: chest pain, dyspnoea, troponin rise, arrhythmias; preceded by viral illness; mimics ACS in presentation.'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 2. RESPIRATORY SYSTEM
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('2. Respiratory System')

story += [h2('2.1  Obstructive Airway Disease'), sp(2)]
story += [h3('Chronic Obstructive Pulmonary Disease (COPD)')]
story += [
    bl('"Blue Bloater" phenotype (chronic bronchitis): central cyanosis, productive cough, hypercapnia, polycythaemia, peripheral oedema, cor pulmonale.'),
    bl('"Pink Puffer" phenotype (emphysema): thin, barrel chest, pursed-lip breathing, accessory muscle use, no cyanosis; hyperresonant chest, reduced breath sounds.'),
    bl('Acute exacerbation (AECOPD): increased dyspnoea and sputum purulence/volume; hypercapnic encephalopathy (confusion, somnolence) in severe episodes.'),
    sp(4),
]

story += [h3('Asthma')]
story += [
    bl('Episodic wheeze, nocturnal cough, chest tightness, dyspnoea; trigger-related, reversible, diurnal variation.'),
    bl('Severe attack: unable to complete sentences, RR >25/min, HR >110/min, PEFR 33-50%.'),
    bl('Life-threatening: silent chest (no air entry), cyanosis, bradycardia, confusion, PEFR <33%; pulsus paradoxus (>10 mmHg systolic fall on inspiration).'),
    sp(4),
]

story += [h2('2.2  Infectious Respiratory Disease'), sp(2)]
story += [h3('Community-Acquired Pneumonia')]
story += [
    bl('Typical (S. pneumoniae): acute fever, rigors, pleuritic chest pain, rusty/purulent sputum; consolidation signs - bronchial breathing, dullness to percussion, increased vocal resonance.'),
    bl('Atypical (Mycoplasma, Legionella): insidious onset, dry cough, prominent systemic features; Legionella specifically causes hyponatraemia, GI symptoms, deranged liver function tests.'),
    bl('Elderly: confusion or functional decline as sole presentation; aspiration pneumonia common (right lower lobe); higher mortality.'),
    sp(4),
]

story += [h3('Pulmonary Tuberculosis')]
story += [
    bl('Post-primary (reactivation): constitutional features - fever (evening pyrexia), drenching night sweats, weight loss, malaise; productive cough, haemoptysis; apical cavitation on chest X-ray.'),
    bl('Extrapulmonary sites: cervical cold abscess (lymphadenitis); TB meningitis (cranial nerve palsies, raised ICP); Pott\'s disease (vertebral destruction, cold abscess, paraplegia); miliary TB (fine micronodular shadowing on CXR, hepatosplenomegaly).'),
    sp(4),
]

story += [h2('2.3  Restrictive, Pleural and Vascular Disease'), sp(2)]
story += [
    bl('Idiopathic Pulmonary Fibrosis (IPF): insidious exertional dyspnoea, dry persistent cough, bilateral basal fine "Velcro" inspiratory crackles, finger clubbing (30-70%); UIP pattern on HRCT - honeycombing with traction bronchiectasis.'),
    bl('Pleural effusion: dyspnoea, dullness to percussion, reduced breath sounds and vocal resonance; transudates (cardiac/hepatic/renal failure) vs exudates (infection, malignancy, TB - Light\'s criteria).'),
    bl('Pulmonary embolism: acute dyspnoea, pleuritic chest pain, haemoptysis; tachycardia most common sign; DVT features (calf swelling, warmth). Massive PE: obstructive shock (hypotension + raised JVP + clear lungs), S1Q3T3 on ECG, right heart strain.'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 3. NEUROLOGICAL SYSTEM
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('3. Neurological System')

story += [h2('3.1  Cerebrovascular Disease'), sp(2)]
story += [h3('Ischaemic Stroke')]
story += [
    bl('MCA territory (most common): contralateral hemiplegia (face/arm > leg), hemisensory loss, homonymous hemianopia; dominant hemisphere - aphasia; non-dominant - neglect and visuospatial deficits.'),
    bl('Wallenberg syndrome (PICA): crossed sensory deficit (ipsilateral face, contralateral body), ipsilateral Horner\'s syndrome, dysphagia, dysarthria, ipsilateral cerebellar signs.'),
    bl('Lacunar strokes (small vessel disease): pure motor, pure sensory, ataxic hemiparesis, or dysarthria-clumsy hand syndromes.'),
    bl('TIA: focal neurological deficit fully resolving within 24 hours; amaurosis fugax ("curtain falling over eye") indicates carotid territory ischaemia.'),
    sp(4),
]

story += [h3('Haemorrhagic Stroke')]
story += [
    bl('Intracerebral haemorrhage (ICH): sudden focal deficit with rapid deterioration; hypertensive ICH typically affects putamen/thalamus; cerebral amyloid angiopathy (elderly) causes lobar haemorrhages.'),
    bl('Subarachnoid haemorrhage (SAH): "thunderclap headache" - worst headache ever, maximal at onset; meningism (neck stiffness, photophobia); third nerve palsy indicates posterior communicating artery aneurysm; Terson\'s syndrome (retinal haemorrhages).'),
    sp(4),
]

story += [h2('3.2  Degenerative Diseases'), sp(2)]
story += [h3('Alzheimer\'s Disease')]
story += [
    bl('Insidious onset: anterograde amnesia earliest (forgetting recent events, repetitive questions), word-finding difficulty, getting lost in familiar places.'),
    bl('Moderate stage: apraxia, agnosia, aphasia, behavioural disturbances (delusions, hallucinations, agitation), impaired activities of daily living.'),
    bl('Severe stage: non-verbal, immobile, doubly incontinent; death from aspiration pneumonia or sepsis.'),
    sp(4),
]

story += [h3('Parkinson\'s Disease')]
story += [
    bl('Cardinal motor features: resting "pill-rolling" tremor (4-6 Hz, disappears with intentional movement), cogwheel rigidity, bradykinesia (micrographia, hypomimia, shuffling gait, festination, reduced arm swing), postural instability (late feature).'),
    bl('Non-motor features: anosmia (precedes motor symptoms by years), constipation, REM sleep behaviour disorder, orthostatic hypotension, depression, cognitive decline; PD dementia occurs in ~80% if followed long enough.'),
    sp(4),
]

story += [h3('Amyotrophic Lateral Sclerosis / Motor Neurone Disease')]
story += [
    bl('Combined upper and lower motor neurone signs: fasciculations, wasting, weakness (LMN) + spasticity, hyperreflexia, Babinski sign (UMN).'),
    bl('Limb onset (60%): focal weakness - wrist drop or foot drop; bulbar onset (30%): dysarthria, dysphagia, tongue fasciculations.'),
    bl('Progressive respiratory failure (dyspnoea, orthopnoea); eye movements and sphincters spared - key differentiating feature.'),
    sp(4),
]

story += [h2('3.3  Demyelinating and Infectious Disease'), sp(2)]
story += [
    bl('Multiple sclerosis: relapsing-remitting course with dissemination in time and space; optic neuritis (painful monocular visual loss, RAPD, Uhthoff\'s phenomenon), internuclear ophthalmoplegia, spastic paraparesis, bladder dysfunction, Lhermitte\'s sign, fatigue.'),
    bl('Bacterial meningitis: classic triad - fever + neck stiffness + altered consciousness; Kernig\'s and Brudzinski\'s signs; non-blanching purpuric rash (meningococcal septicaemia - glass test); Waterhouse-Friderichsen syndrome (bilateral adrenal haemorrhage, DIC, shock).'),
    bl('Elderly meningitis: neck stiffness absent or attributed to cervical spondylosis; Listeria monocytogenes more common; may present with only low-grade fever and confusion.'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 4. GASTROINTESTINAL AND HEPATIC SYSTEM
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('4. Gastrointestinal and Hepatic System')

story += [h2('4.1  Upper Gastrointestinal Disease'), sp(2)]
story += [
    bl('GORD: retrosternal burning (heartburn), acid regurgitation, water brash; extra-oesophageal features - chronic cough, laryngitis, asthma; Barrett\'s oesophagus (columnar metaplasia) carries risk of adenocarcinoma.'),
    bl('Duodenal ulcer: epigastric pain relieved by food and antacids; nocturnal pain waking patient; periodicity. Gastric ulcer: pain worsened by food, weight loss more prominent.'),
    bl('PUD complications: haemorrhage (haematemesis, coffee-ground vomit, melaena); perforation (sudden severe pain, board-like abdomen, peritonism, absent bowel sounds); pyloric obstruction (projectile vomiting, succussion splash, hypokalaemic hypochloraemic alkalosis).'),
    sp(4),
]

story += [h2('4.2  Inflammatory Bowel Disease'), sp(2)]
story += [h3('Crohn\'s Disease')]
story += [
    bl('Transmural inflammation with skip lesions affecting any site from mouth to anus; diarrhoea (may be bloody), right iliac fossa pain and mass, weight loss, fever.'),
    bl('Perianal disease (fistulae, abscesses) in 20-30%; strictures cause intestinal obstruction; fistulae cause pneumaturia or faeculent vaginal discharge.'),
    bl('Extraintestinal manifestations: peripheral arthropathy (mirrors disease activity), uveitis, episcleritis, erythema nodosum, pyoderma gangrenosum, oxalate renal stones.'),
    sp(4),
]
story += [h3('Ulcerative Colitis')]
story += [
    bl('Mucosal inflammation starting from rectum extending continuously proximally; hallmark - bloody diarrhoea with tenesmus and urgency.'),
    bl('Severe UC (Truelove & Witts): >6 bloody stools/day plus fever, tachycardia, or anaemia.'),
    bl('Toxic megacolon: colonic dilatation >6 cm on AXR with systemic toxicity and peritonism - risk of perforation. Long-term colorectal carcinoma risk after 8-10 years of pancolitis.'),
    sp(4),
]

story += [h2('4.3  Liver Cirrhosis'), sp(2)]
story += [
    body('Aetiology: Alcohol, chronic viral hepatitis (B, C), NAFLD/NASH (metabolic syndrome), autoimmune hepatitis, primary biliary cholangitis, haemochromatosis, Wilson\'s disease.'),
    bl('Stigmata of chronic liver disease: spider naevi, palmar erythema, leukonychia, gynaecomastia, testicular atrophy, loss of body hair, caput medusae, Dupuytren\'s contracture and parotid enlargement (alcohol).'),
    bl('Decompensation - Ascites: shifting dullness, fluid thrill; spontaneous bacterial peritonitis presents with fever, abdominal pain, and deteriorating liver function.'),
    bl('Decompensation - Hepatic encephalopathy: asterixis (hepatic flap), fetor hepaticus, personality change, cognitive impairment; graded I-IV.'),
    bl('Decompensation - Variceal haemorrhage: haematemesis or melaena with haemodynamic compromise; portal hypertension (HVPG >12 mmHg) drives risk.'),
    bl('Hepatorenal syndrome: functional AKI - oliguria, hyponatraemia; no intrinsic renal pathology.'),
    bl('Hepatocellular carcinoma: rapid clinical deterioration, right upper quadrant pain, paraneoplastic features (hypoglycaemia, erythrocytosis, hypercalcaemia).'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 5. RENAL AND ENDOCRINE SYSTEMS
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('5. Renal and Endocrine Systems')

story += [h2('5.1  Renal Disease'), sp(2)]
story += [
    bl('Nephrotic syndrome: proteinuria >3.5g/24h, hypoalbuminaemia, periorbital and peripheral oedema, frothy urine, hyperlipidaemia; complications include VTE (loss of antithrombin III, proteins S/C) and increased infection risk.'),
    bl('Nephritic syndrome: haematuria (red cell casts), sub-nephrotic proteinuria, hypertension, oliguria, AKI; systemic features of underlying disease (rash/joints in SLE; haemoptysis in anti-GBM disease).'),
    bl('Acute kidney injury: oliguria/anuria, uraemia (nausea, vomiting, hiccups, pericarditis, encephalopathy), hyperkalaemia (peaked T-waves, widened QRS, arrhythmia), metabolic acidosis (Kussmaul breathing). Pre-renal (hypovolaemia, CCF) most common; post-renal (BPH most common cause in elderly men).'),
    bl('Chronic kidney disease: silent through stages 1-3; uraemic syndrome in stages 4-5 - pruritus, restless legs, peripheral neuropathy, renal osteodystrophy (secondary hyperparathyroidism, subperiosteal erosions), LVH, platelet dysfunction, normochromic normocytic anaemia. Creatinine underestimates severity in elderly due to reduced muscle mass.'),
    sp(4),
]

story += [h2('5.2  Diabetes Mellitus'), sp(2)]
story += [
    bl('Type 1 DM: acute onset polyuria, polydipsia, weight loss; DKA - Kussmaul breathing (deep, rapid respirations), ketotic (sweet/fruity) breath, vomiting, dehydration, altered consciousness.'),
    bl('Type 2 DM: often asymptomatic/incidental; recurrent genital candidiasis, skin infections, osmotic blurring of vision. Hyperosmolar hyperglycaemic state (HHS) in the elderly: extreme hyperglycaemia (>30 mmol/L), profound dehydration, no/minimal ketosis, altered consciousness, focal neurological deficits - high mortality.'),
    bl('Microvascular complications: Retinopathy (background microaneurysms → proliferative new vessels, vitreous haemorrhage); Nephropathy (microalbuminuria → CKD); Neuropathy (painful nocturnal glove-and-stocking sensorimotor; autonomic - gastroparesis, postural hypotension, erectile dysfunction).'),
    bl('Macrovascular complications: coronary artery disease (leading cause of death), peripheral arterial disease (claudication, Charcot foot), stroke.'),
    sp(4),
]

story += [h2('5.3  Thyroid Disease'), sp(2)]
story += [
    bl('Hypothyroidism: cold intolerance, weight gain despite reduced appetite, constipation, fatigue, bradycardia, dry coarse skin, periorbital and peripheral non-pitting myxoedema, Queen Anne\'s sign (loss of outer third of eyebrows), prolonged (hung-up) tendon reflexes, hoarse voice; myxoedema coma (hypothermia, hypoventilation, profound coma).'),
    bl('Hyperthyroidism: heat intolerance, weight loss, tremor, anxiety, palpitations/AF, diarrhoea, warm moist skin, proximal myopathy, lid lag, lid retraction.'),
    bl('Graves\' disease specific features: smooth goitre, exophthalmos/proptosis, periorbital oedema, diplopia (extraocular muscle infiltration), optic neuropathy, pretibial myxoedema.'),
    bl('Apathetic thyrotoxicosis (elderly): depression, weight loss, atrial fibrillation, weakness - without the classic sympathomimetic features; easily missed and frequently attributed to "ageing".'),
    bl('Thyroid storm: extreme hyperthyroidism - hyperthermia, delirium, extreme tachycardia, cardiac failure; 20-30% mortality without prompt treatment.'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 6. MUSCULOSKELETAL AND HAEMATOLOGICAL SYSTEMS
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('6. Musculoskeletal, Rheumatological and Haematological Systems')

story += [h2('6.1  Inflammatory Arthritis'), sp(2)]
story += [h3('Rheumatoid Arthritis')]
story += [
    bl('Symmetrical small joint polyarthritis predominantly affecting MCPJs, PIPJs, wrists, and MTPs; DIPJs typically spared; morning stiffness lasting >1 hour.'),
    bl('Deformities: swan neck (PIPJ hyperextension, DIPJ flexion), boutonniere (PIPJ flexion, DIPJ hyperextension), ulnar deviation, Z-thumb; subcutaneous rheumatoid nodules on extensor surfaces.'),
    bl('Extraarticular: pulmonary (ILD, pleuritis, nodules, obliterative bronchiolitis), cardiovascular (accelerated atherosclerosis, pericarditis), ocular (episcleritis, scleritis, secondary Sjogren\'s), neurological (mononeuritis multiplex, atlanto-axial instability causing cervical myelopathy), haematological (Felty\'s syndrome: RA + splenomegaly + neutropenia), renal (secondary AA amyloidosis).'),
    sp(4),
]

story += [h3('Gout and Osteoarthritis')]
story += [
    bl('Acute gout: sudden onset (often nocturnal) excruciating monoarthritis; first MTP joint (podagra) most classic; exquisitely tender, erythematous, swollen joint; systemic fever; resolves spontaneously in 3-14 days; precipitants include alcohol, diuretics, surgery, dehydration.'),
    bl('Chronic tophaceous gout: chalky tophi (helix of ear, Achilles tendon, extensor surfaces), chronic joint damage, urate nephropathy.'),
    bl('Osteoarthritis: activity-related joint pain (improves with rest, not with activity); bony hard swelling (osteophytes), crepitus, restricted range of motion; no systemic inflammation; Heberden\'s nodes (DIPJs), Bouchard\'s nodes (PIPJs), first CMC "square thumb"; most common cause of disability in adults over 65.'),
    sp(4),
]

story += [h3('Systemic Lupus Erythematosus (SLE) and Systemic Sclerosis')]
story += [
    bl('SLE: butterfly (malar) rash sparing nasolabial folds, photosensitivity, oral ulcers, non-erosive arthritis, serositis (pleuritis, pericarditis), lupus nephritis, neuropsychiatric features (seizures, psychosis), haemolytic anaemia, leucopenia, thrombocytopenia, antiphospholipid syndrome (thrombosis, recurrent pregnancy loss).'),
    bl('Limited SSc (CREST): Calcinosis, Raynaud\'s phenomenon (first symptom by years), Oesophageal dysmotility, Sclerodactyly, Telangiectasia; anti-centromere antibodies; major complication is pulmonary arterial hypertension.'),
    bl('Diffuse SSc: rapid extensive skin fibrosis, ILD (leading cause of death), scleroderma renal crisis (malignant hypertension, AKI), myocarditis; anti-Scl-70 (anti-topoisomerase I) antibodies.'),
    sp(4),
]

story += [h2('6.2  Anaemias'), sp(2)]
story += [
    bl('Iron deficiency anaemia: fatigue, pallor, koilonychia (spoon nails), angular stomatitis, glossitis, pica (ice, clay), Plummer-Vinson syndrome (dysphagia + post-cricoid web + IDA), restless legs; key in elderly men and post-menopausal women - colorectal malignancy/angiodysplasia must be excluded.'),
    bl('Megaloblastic anaemia (B12/folate): lemon-yellow pallor, glossitis; B12 deficiency specifically causes subacute combined degeneration of the spinal cord (posterior columns + lateral corticospinal tracts: symmetrical paraesthesiae and numbness → ataxia → spasticity), dementia, and psychosis. Folate deficiency does NOT cause neurological complications.'),
    bl('Anaemia of chronic disease: mild-to-moderate normochromic normocytic anaemia; low serum iron, low TIBC, elevated ferritin; underlying disease (RA, IBD, CKD, malignancy) dominates clinical picture.'),
    sp(4),
]

story += [h2('6.3  Haematological Malignancies'), sp(2)]
story += [
    bl('Acute leukaemia: bone marrow failure triad - anaemia (fatigue, pallor, dyspnoea) + neutropenia (recurrent infections, mouth ulcers) + thrombocytopenia (petechiae, purpura, gum bleeding). Organ infiltration: hepatosplenomegaly, lymphadenopathy, CNS disease; gum hypertrophy (AML M5); DIC in APL (AML M3).'),
    bl('CML (BCR-ABL, t(9;22)): massive splenomegaly (most prominent sign), constitutional symptoms; often incidental leucocytosis; blast crisis mimics acute leukaemia.'),
    bl('CLL: painless lymphadenopathy, splenomegaly, fatigue; autoimmune haemolytic anaemia; hypogammaglobulinaemia causing recurrent infections; Richter\'s transformation (sudden nodal enlargement, systemic symptoms).'),
    bl('Multiple myeloma (CRAB criteria): Hypercalcaemia (confusion, constipation, polyuria), Renal failure (light chain cast nephropathy), Anaemia (normochromic normocytic), Bone pain/lytic lesions/pathological fractures; recurrent infections; hyperviscosity syndrome (headache, visual disturbance, mucosal bleeding).'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 7. GERIATRIC SYNDROMES AND SYSTEMIC INFECTIONS
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('7. Geriatric Syndromes and Systemic Infectious Disease')

story += [h2('7.1  Geriatric Syndromes'), sp(2)]
story += [h3('Frailty')]
story += [
    bl('Fried phenotype (3 of 5 criteria = frail): unintentional weight loss (>4.5 kg/year), self-reported exhaustion, weakness (reduced grip strength), slow walking speed, low physical activity.'),
    bl('Underlying sarcopenia (reduced skeletal muscle mass and function); increased risk of falls, hospitalisations, disability, and mortality.'),
    sp(4),
]

story += [h3('Delirium (Acute Confusional State)')]
story += [
    bl('Acute onset and fluctuating course (hours to days) distinguishes delirium from dementia; impaired attention, disorganised thinking, altered consciousness level.'),
    bl('Hyperactive delirium: agitation, combativeness, visual hallucinations - often misdiagnosed as acute psychosis.'),
    bl('Hypoactive delirium (most common, most frequently missed): withdrawal, drowsiness, reduced responsiveness - attributed to tiredness or dementia; carries poor prognosis.'),
    bl('Common precipitants: infection (UTI, pneumonia), drugs (opioids, anticholinergics, benzodiazepines), dehydration, urinary retention, pain, alcohol withdrawal, metabolic disturbance.'),
    sp(4),
]

story += [h3('Falls, Incontinence and Pressure Ulcers')]
story += [
    bl('Falls: hip fracture (shortened, externally rotated limb) most feared complication; subdural haematoma; "long lie" complications (hypothermia, rhabdomyolysis, aspiration pneumonia, pressure injuries); fear of falling causes progressive deconditioning.'),
    bl('Urinary incontinence types: Stress (sphincter weakness, exertion-triggered); Urge (overactive bladder, detrusor overactivity); Overflow (BPH or detrusor underactivity - constant dribbling, incomplete emptying); Functional (mobility/cognitive impairment prevents reaching toilet).'),
    bl('Pressure ulcers: Stage 1 (non-blanchable erythema, intact skin) to Stage 4 (bone/muscle/tendon exposed); risk factors: immobility, malnutrition, moisture/incontinence, reduced sensation.'),
    sp(4),
]

story += [h2('7.2  HIV/AIDS'), sp(2)]
story += [
    bl('Primary seroconversion (2-6 weeks post-exposure): mononucleosis-like illness - fever, pharyngitis, lymphadenopathy, maculopapular rash, oral/genital ulcers, diarrhoea.'),
    bl('AIDS-defining conditions by CD4 count threshold:'),
    sbl('CD4 <200/μL: Pneumocystis jirovecii pneumonia (PCP) - exertional dyspnoea, dry cough, bilateral perihilar infiltrates, elevated LDH; oesophageal candidiasis - dysphagia, odynophagia.'),
    sbl('CD4 <100/μL: Toxoplasma encephalitis (ring-enhancing lesions, focal deficits, seizures); Cryptococcal meningitis (raised ICP, India ink stain positive).'),
    sbl('CD4 <50/μL: CMV retinitis ("pizza pie" fundus appearance); Mycobacterium avium complex - fever, night sweats, diarrhoea, hepatosplenomegaly.'),
    bl('AIDS-defining malignancies: Kaposi\'s sarcoma (purple/brown vascular lesions - skin, palate, GI tract; HIV-8 associated); CNS lymphoma (EBV-associated, periventricular lesions, focal deficits); HIV-associated neurocognitive disorder.'),
    sp(6),
    pb(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# 8. RAPID REFERENCE TABLE
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('8. Rapid Reference: Differentiating Clinical Features by System and Aetiology')
story += [sp(6)]

tbl = make_table(
    ['System', 'Ischaemic/Vascular', 'Inflammatory/Autoimmune', 'Infectious', 'Neoplastic/Degenerative'],
    [
        ['Cardiac',
         'Chest pain, diaphoresis, ECG changes; cardiogenic shock',
         'Pleuritic pain, friction rub, pericardial effusion; troponin rise',
         'Fever, viral prodrome, myocarditis',
         'Cachexia, effusion; progressive cardiomyopathy'],
        ['Respiratory',
         'Acute dyspnoea, pleurisy, haemoptysis (PE)',
         'Wheeze, eosinophilia, steroid-responsive (asthma)',
         'Fever, productive cough, consolidation signs',
         'Haemoptysis, clubbing, weight loss; progressive dyspnoea, Velcro crackles (IPF)'],
        ['Neurological',
         'Sudden focal deficit; thunderclap headache (SAH)',
         'Relapsing-remitting episodes; optic neuritis, INO',
         'Fever + meningism + purpuric rash',
         'Progressive focal deficit, raised ICP; insidious cognitive decline, tremor, rigidity'],
        ['GI / Liver',
         'Mesenteric ischaemia: severe periumbilical pain',
         'Bloody diarrhoea, EIM, abdominal pain (IBD)',
         'Fever, diarrhoea, jaundice (hepatitis)',
         'Weight loss, altered bowel habit; cirrhosis stigmata, ascites, encephalopathy'],
        ['Renal',
         'Pre-renal AKI: oliguria, reduced JVP',
         'Haematuria, red cell casts, systemic features',
         'Fever, dysuria, loin pain (pyelonephritis)',
         'Painless haematuria, abdominal mass; gradual GFR decline, uraemia'],
        ['Endocrine',
         '—',
         'Heat intolerance, tremor, AF (thyrotoxicosis)',
         'Hypotension, adrenal crisis (sepsis)',
         'Hypercalcaemia (PTHrP); cold intolerance, bradycardia (hypothyroid)'],
        ['MSK',
         'AVN: joint pain, steroid/alcohol history',
         'Morning stiffness >1h, symmetric arthritis',
         'Acute monoarthritis, fever (septic arthritis)',
         'Bone pain, lytic lesions (myeloma); activity pain, crepitus (OA)'],
        ['Haematological',
         'Hyperviscosity syndrome (myeloma)',
         'AIHA, ITP, autoimmune cytopenias',
         'Fever, neutropenia, splenomegaly',
         'Anaemia, thrombocytopenia, lymphadenopathy (leukaemia/lymphoma)'],
    ]
)

story += [tbl, sp(6), pb()]

# ═══════════════════════════════════════════════════════════════════════════════
# 9. GERIATRIC PRINCIPLES
# ═══════════════════════════════════════════════════════════════════════════════
story += h1('9. Core Principles: Disease Presentation in the Geriatric Population')
story += [
    body('The geriatric population consistently manifests disease differently from younger adults. Understanding these differences is essential for accurate diagnosis and management.'),
    sp(4),
]

principles = [
    ('Atypical Presentations',
     'Classic symptoms are frequently absent. Confusion, falls, or functional decline may be the only manifestation of ACS, sepsis, stroke, or pulmonary embolism. A high index of suspicion and low threshold for investigation is essential across all systems.'),
    ('Polypharmacy Effects',
     'Multiple medications contribute to drug interactions and adverse effects that mask true disease or mimic illness (e.g., anticholinergic burden causing cognitive impairment; beta-blockers masking hypoglycaemia; diuretics precipitating dehydration and falls).'),
    ('Reduced Physiological Reserve',
     'The inflammatory response is blunted - absence of fever and leucocytosis is common even in severe sepsis. Renal clearance, hepatic metabolism, and cardiac reserve are all reduced. Recovery from acute illness is slower and complications more common.'),
    ('Multimorbidity',
     'Multiple co-existing conditions complicate diagnosis and management. A presenting complaint may have several simultaneous aetiologies. Treating one condition may exacerbate another (e.g., fluid replacement in AKI causing pulmonary oedema in heart failure).'),
    ('Geriatric Giants',
     'Instability (falls), Immobility, Intellectual decline (dementia/delirium), and Incontinence are the four classic geriatric syndromes that frequently represent the final common pathway of multiple underlying diseases across all organ systems.'),
    ('Cognitive Impairment as a Confounder',
     'Dementia impairs symptom reporting and the history is often unreliable. Proxy history from carers, collateral from family members, and careful clinical observation are essential to accurate diagnosis.'),
    ('Delirium vs. Dementia',
     'Delirium is acute and fluctuating (hours to days onset); dementia is insidious and progressive (months to years). Delirium superimposed on dementia is common and carries poor prognosis. Hypoactive delirium (withdrawn, drowsy, quiet) is the most common subtype and the most frequently missed.'),
]

for i, (title, text) in enumerate(principles, 1):
    story += [
        Paragraph(f'{i}.  <b>{title}</b>', BODY),
        Paragraph(f'    {text}', ParagraphStyle('IndBody', parent=BODY, leftIndent=18)),
        sp(5),
    ]

# ── Build PDF ────────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    canvas.setFont('Helvetica', 8)
    canvas.setFillColor(black)
    # Header line
    canvas.drawCentredString(A4[0]/2, A4[1]-1.4*cm,
        'Clinical Features of Multi-System Disease - Adult & Geriatric Population')
    canvas.line(2*cm, A4[1]-1.6*cm, A4[0]-2*cm, A4[1]-1.6*cm)
    # Footer
    canvas.line(2*cm, 1.6*cm, A4[0]-2*cm, 1.6*cm)
    canvas.drawCentredString(A4[0]/2, 1.1*cm, f'Page {doc.page}')
    canvas.restoreState()

doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print('PDF created successfully.')
Running Command

cd /home/daytona/workspace/multisystem-summary && python3 generate_pdf.py 2>&1

Running Command

python3 -c " from pypdf import PdfReader r = PdfReader('/home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary_BW.pdf') import os size = os.path.getsize('/home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary_BW.pdf') print(f'Pages: {len(r.pages)}') print(f'Size: {size} bytes ({size/1024:.1f} KB)') "

Your PDF is ready - 13 pages, fully black and white, no references, clean topic headings and clinical discussion only.

MultiSystem Disease Summary BW

PDF Document · PDF


What the document contains:
PageContent
1Title page
2Cardiovascular System (angina, ACS, heart failure, hypertension, valvular disease, AF, pericarditis)
3Respiratory System (COPD, asthma, pneumonia, TB, IPF, pleural effusion, PE)
4Neurological System (stroke, ICH, SAH, Alzheimer's, Parkinson's, ALS, MS, meningitis)
5Gastrointestinal and Hepatic System (GORD, PUD, Crohn's, UC, cirrhosis)
6Renal and Endocrine Systems (nephrotic/nephritic, AKI, CKD, DM, thyroid disease)
7Musculoskeletal and Haematological Systems (RA, gout, OA, SLE, SSc, anaemias, leukaemias, myeloma)
8Geriatric Syndromes and HIV/AIDS
9Rapid Reference Table (8 systems x 5 aetiologies)
10-13Geriatric principles (7 core concepts with full discussion)

Convert in word file

Running Command

cd /home/daytona/workspace/multisystem-summary && python3 /home/daytona/skills/docx/scripts/office/soffice.py --headless --convert-to docx MultiSystem_Disease_Summary_BW.pdf 2>&1

Running Command

cd /home/daytona/workspace/multisystem-summary && soffice --headless --infilter="writer_pdf_import" --convert-to docx MultiSystem_Disease_Summary_BW.pdf 2>&1

Running Command

mkdir -p /home/daytona/workspace/multisystem-summary/tmp_convert && soffice --headless --infilter="writer_pdf_import" --convert-to docx --outdir /home/daytona/workspace/multisystem-summary/tmp_convert /home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary_BW.pdf 2>&1

Writing File

~/multisystem-summary/generate_bw.js

const {
  Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
  HeadingLevel, AlignmentType, BorderStyle, WidthType, ShadingType,
  VerticalAlign, PageNumber, PageBreak, Header, Footer
} = require('docx');
const fs = require('fs');

// ── Styles (all black & white) ───────────────────────────────────────────────
const BLACK = '000000';
const GREY  = 'CCCCCC';
const LGREY = 'EFEFEF';
const WHITE = 'FFFFFF';

function h1(text) {
  return new Paragraph({
    children: [new TextRun({ text: text.toUpperCase(), bold: true, size: 26, font: 'Calibri', color: BLACK })],
    spacing: { before: 280, after: 60 },
    border: {
      bottom: { style: BorderStyle.SINGLE, size: 8, color: BLACK, space: 4 }
    },
  });
}
function h2(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 23, font: 'Calibri', color: BLACK })],
    spacing: { before: 200, after: 60 },
  });
}
function h3(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, italics: true, size: 21, font: 'Calibri', color: BLACK })],
    spacing: { before: 140, after: 40 },
  });
}
function body(text) {
  return new Paragraph({
    children: [new TextRun({ text, size: 20, font: 'Calibri', color: BLACK })],
    spacing: { before: 40, after: 40 },
    alignment: AlignmentType.JUSTIFIED,
  });
}
function bl(boldPart, rest) {
  const runs = [new TextRun({ text: '\u2022  ', size: 20, font: 'Calibri', color: BLACK })];
  if (boldPart) runs.push(new TextRun({ text: boldPart, bold: true, size: 20, font: 'Calibri', color: BLACK }));
  if (rest)     runs.push(new TextRun({ text: rest,     size: 20, font: 'Calibri', color: BLACK }));
  return new Paragraph({
    children: runs,
    indent: { left: 240, hanging: 200 },
    spacing: { before: 30, after: 30 },
    alignment: AlignmentType.JUSTIFIED,
  });
}
function sbl(text) {
  return new Paragraph({
    children: [new TextRun({ text: '\u2013  ' + text, size: 19, font: 'Calibri', color: BLACK })],
    indent: { left: 480, hanging: 200 },
    spacing: { before: 20, after: 20 },
    alignment: AlignmentType.JUSTIFIED,
  });
}
function sp() { return new Paragraph({ text: '', spacing: { before: 30, after: 30 } }); }
function pb() { return new Paragraph({ children: [new PageBreak()] }); }

// ── Table ─────────────────────────────────────────────────────────────────────
function makeTable(headers, rows) {
  const colWidths = [1700, 2200, 2200, 2200, 2200]; // twips

  const headerRow = new TableRow({
    children: headers.map(h =>
      new TableCell({
        children: [new Paragraph({
          children: [new TextRun({ text: h, bold: true, size: 17, font: 'Calibri', color: WHITE })],
          alignment: AlignmentType.CENTER,
        })],
        shading: { type: ShadingType.SOLID, color: BLACK },
        verticalAlign: VerticalAlign.CENTER,
        margins: { top: 60, bottom: 60, left: 80, right: 80 },
      })
    ),
    tableHeader: true,
  });

  const dataRows = rows.map((row, ri) =>
    new TableRow({
      children: row.map(cell =>
        new TableCell({
          children: [new Paragraph({
            children: [new TextRun({ text: cell, size: 16, font: 'Calibri', color: BLACK })],
          })],
          shading: { type: ShadingType.SOLID, color: ri % 2 === 0 ? LGREY : WHITE },
          margins: { top: 50, bottom: 50, left: 80, right: 80 },
        })
      ),
    })
  );

  return new Table({
    rows: [headerRow, ...dataRows],
    width: { size: 100, type: WidthType.PERCENTAGE },
  });
}

// ── Title page ─────────────────────────────────────────────────────────────────
const titlePage = [
  new Paragraph({ text: '', spacing: { before: 1400 } }),
  new Paragraph({
    children: [new TextRun({ text: 'Clinical Features of Diseases Across All Body Systems', bold: true, size: 36, font: 'Calibri', color: BLACK })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 0, after: 200 },
  }),
  new Paragraph({
    children: [new TextRun({ text: 'In the Adult and Geriatric Population', bold: true, size: 28, font: 'Calibri', color: BLACK })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 0, after: 200 },
  }),
  new Paragraph({
    children: [new TextRun({ text: 'A Multi-System Clinical Summary by Aetiology', italics: true, size: 22, font: 'Calibri', color: BLACK })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 0, after: 800 },
  }),
  pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 1. CARDIOVASCULAR
// ══════════════════════════════════════════════════════════════════════════════
const cardio = [
  h1('1. Cardiovascular System'),
  h2('1.1  Ischaemic Heart Disease'),
  h3('Stable Angina Pectoris'),
  bl('', 'Retrosternal chest tightness or pressure radiating to the left arm, jaw, neck, or epigastrium; precipitated by exertion, cold, meals, or emotional stress; relieved within 2-5 minutes by rest or sublingual nitrates.'),
  bl('', 'Duration typically 2-10 minutes; Levine\'s sign (clenched fist over sternum). No pleuritic quality, no positional change, no chest wall tenderness.'),
  bl('Elderly/diabetics: ', 'Atypical presentations common - dyspnoea, fatigue, or epigastric discomfort ("anginal equivalents"); silent ischaemia more frequent due to altered pain perception.'),
  sp(),
  h3('Acute Coronary Syndrome (NSTEMI / STEMI)'),
  bl('', 'Severe crushing substernal pain >30 minutes; diaphoresis, nausea, vomiting, sense of impending doom (angor animi); radiation to left arm, jaw, or back.'),
  bl('', 'S4 gallop (reduced ventricular compliance); new S3 indicates LV failure; new mitral regurgitation murmur suggests papillary muscle dysfunction or rupture.'),
  bl('Cardiogenic shock (Killip IV): ', 'Persistent hypotension, cool clammy skin, pulmonary oedema, oliguria, altered consciousness - requires vasopressor support.'),
  bl('NSTEMI/Unstable angina: ', 'Rest or minimal exertion pain, fewer ECG changes but equally life-threatening. Accelerating (crescendo) pattern or new onset severe angina.'),
  sp(),
  h2('1.2  Chronic Heart Failure'),
  bl('Left-sided failure: ', 'Progressive exertional dyspnoea, orthopnoea, paroxysmal nocturnal dyspnoea; displaced apex beat, S3 gallop, bilateral basal crackles, pleural effusion.'),
  bl('Right-sided failure: ', 'Bilateral pitting oedema, raised JVP, hepatomegaly, ascites; positive hepatojugular reflux; Kussmaul\'s sign in constrictive pericarditis.'),
  bl('NYHA classification: ', 'Grades symptom severity from Class I (no limitation) to Class IV (symptoms at rest).'),
  bl('Geriatric: ', 'HFpEF (heart failure with preserved ejection fraction) predominates; atypical features - falls, confusion, fatigue without obvious dyspnoea.'),
  sp(),
  h2('1.3  Hypertension'),
  bl('', 'Usually asymptomatic ("silent killer"); headache (occipital, morning), visual disturbance, epistaxis in severe disease.'),
  bl('Fundoscopic grading: ', 'Grades I-II (arterial narrowing, AV nipping); Grades III-IV (haemorrhages, cotton wool spots, papilloedema) indicate hypertensive emergency.'),
  bl('Hypertensive emergency (BP >180/120 + end-organ damage): ', 'Encephalopathy, aortic dissection (tearing pain, BP differential between arms), acute pulmonary oedema, AKI.'),
  bl('Elderly: ', 'Isolated systolic hypertension from arterial stiffness; orthostatic hypotension complicates treatment; pseudohypertension (Osler\'s sign).'),
  sp(),
  h2('1.4  Valvular Disease, Arrhythmia and Pericarditis'),
  bl('Mitral stenosis (rheumatic): ', 'Dyspnoea, haemoptysis, malar flush, atrial fibrillation; loud S1 + opening snap + mid-diastolic rumble at apex (best heard in left lateral decubitus).'),
  bl('Aortic stenosis (degenerative/elderly): ', 'Classic triad - angina (3-5yr survival), syncope (2-3yr), dyspnoea/heart failure (1-2yr); slow-rising pulse, harsh ejection systolic murmur radiating to carotids.'),
  bl('Atrial fibrillation: ', 'Irregularly irregular pulse, palpitations, dyspnoea; major thromboembolic risk; elderly often present with stroke, falls, or fatigue as the only feature.'),
  bl('Acute pericarditis: ', 'Sharp pleuritic chest pain relieved by leaning forward; triphasic pericardial friction rub; saddle-shaped ST elevation on ECG. Beck\'s triad in tamponade (hypotension + muffled heart sounds + raised JVP).'),
  bl('Myocarditis: ', 'Chest pain, dyspnoea, troponin rise, arrhythmias; preceded by viral illness; can present identically to ACS.'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 2. RESPIRATORY
// ══════════════════════════════════════════════════════════════════════════════
const resp = [
  h1('2. Respiratory System'),
  h2('2.1  Obstructive Airway Disease'),
  h3('Chronic Obstructive Pulmonary Disease (COPD)'),
  bl('"Blue Bloater" (chronic bronchitis): ', 'Central cyanosis, chronic productive cough, hypercapnia, polycythaemia, peripheral oedema, cor pulmonale; hypercapnic respiratory drive.'),
  bl('"Pink Puffer" (emphysema): ', 'Thin, barrel chest, pursed-lip breathing, accessory muscle use, no cyanosis; hyperresonant chest, reduced breath sounds, prolonged expiratory phase.'),
  bl('AECOPD: ', 'Increased dyspnoea and sputum purulence/volume; hypercapnic encephalopathy (confusion, somnolence) in severe episodes; precipitated by infection, pollutants, or PE.'),
  sp(),
  h3('Asthma'),
  bl('', 'Episodic wheeze, nocturnal cough, chest tightness, dyspnoea; trigger-related, reversible, diurnal variation; bilateral polyphonic wheeze on auscultation.'),
  bl('Severe attack: ', 'Unable to complete sentences, RR >25/min, HR >110/min, PEFR 33-50% predicted.'),
  bl('Life-threatening: ', 'Silent chest (no air entry), cyanosis, bradycardia, confusion, PEFR <33%; pulsus paradoxus (>10 mmHg systolic fall on inspiration).'),
  sp(),
  h2('2.2  Infectious Respiratory Disease'),
  h3('Community-Acquired Pneumonia'),
  bl('Typical (S. pneumoniae): ', 'Acute fever, rigors, pleuritic chest pain, rusty/purulent sputum; consolidation signs - bronchial breathing, dullness to percussion, increased vocal resonance, aegophony.'),
  bl('Atypical (Mycoplasma, Legionella): ', 'Insidious onset, dry cough, prominent systemic features; Legionella causes hyponatraemia, GI symptoms, deranged liver function tests.'),
  bl('Elderly: ', 'Confusion or functional decline as sole presentation; aspiration pneumonia common (right lower lobe); absence of fever or leucocytosis; higher mortality.'),
  sp(),
  h3('Pulmonary Tuberculosis'),
  bl('Post-primary (reactivation): ', 'Evening pyrexia, drenching night sweats, weight loss, malaise; productive cough, haemoptysis; apical cavitation or consolidation on CXR.'),
  bl('Extrapulmonary: ', 'Cervical cold abscess (lymphadenitis); TB meningitis (cranial nerve palsies, raised ICP); Pott\'s disease (vertebral destruction, paraplegia); miliary TB (fine micronodular CXR, hepatosplenomegaly, choroidal tubercles).'),
  sp(),
  h2('2.3  Restrictive, Pleural and Vascular Disease'),
  bl('Idiopathic Pulmonary Fibrosis: ', 'Insidious exertional dyspnoea, dry persistent cough, bilateral basal fine "Velcro" inspiratory crackles, finger clubbing (30-70%); UIP pattern on HRCT (honeycombing with traction bronchiectasis).'),
  bl('Pleural effusion: ', 'Dyspnoea, stony dull percussion, reduced breath sounds and vocal resonance; transudates (cardiac/hepatic/renal) vs exudates (infection, malignancy, TB) by Light\'s criteria.'),
  bl('Pulmonary embolism: ', 'Acute dyspnoea, pleuritic chest pain, haemoptysis (pulmonary infarction); tachycardia (most common sign). Massive PE: obstructive shock (hypotension + raised JVP + clear lungs), S1Q3T3 on ECG, right heart strain.'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 3. NEUROLOGICAL
// ══════════════════════════════════════════════════════════════════════════════
const neuro = [
  h1('3. Neurological System'),
  h2('3.1  Cerebrovascular Disease'),
  h3('Ischaemic Stroke'),
  bl('MCA territory (most common): ', 'Contralateral hemiplegia (face/arm > leg), hemisensory loss, homonymous hemianopia; dominant hemisphere - aphasia; non-dominant - neglect, visuospatial deficits.'),
  bl('Wallenberg syndrome (PICA): ', 'Crossed sensory deficit (ipsilateral face, contralateral body), ipsilateral Horner\'s syndrome, dysphagia, dysarthria, ipsilateral cerebellar signs.'),
  bl('Lacunar strokes: ', 'Pure motor, pure sensory, ataxic hemiparesis, or dysarthria-clumsy hand syndromes (small vessel disease of deep perforating arteries).'),
  bl('TIA: ', 'Focal neurological deficit fully resolving within 24 hours; amaurosis fugax ("curtain falling over eye") indicates carotid territory ischaemia.'),
  sp(),
  h3('Haemorrhagic Stroke'),
  bl('Intracerebral haemorrhage: ', 'Sudden focal deficit with rapid deterioration; hypertensive ICH affects putamen/thalamus/pons; CAA in elderly causes lobar haemorrhages.'),
  bl('Subarachnoid haemorrhage: ', '"Thunderclap headache" - worst headache ever, maximal at onset; meningism; third nerve palsy (PCom aneurysm); Terson\'s syndrome (retinal haemorrhages); sentinel headache in 30% weeks prior.'),
  sp(),
  h2('3.2  Degenerative Diseases'),
  h3('Alzheimer\'s Disease'),
  bl('Early stage: ', 'Anterograde amnesia (earliest feature), word-finding difficulty, getting lost in familiar places; insidious onset, gradual progression.'),
  bl('Moderate stage: ', 'Apraxia, agnosia, aphasia, behavioural disturbances (delusions, hallucinations, agitation), impaired activities of daily living.'),
  bl('Severe stage: ', 'Non-verbal, immobile, doubly incontinent; death from aspiration pneumonia or sepsis.'),
  sp(),
  h3('Parkinson\'s Disease'),
  bl('Cardinal motor features: ', 'Resting "pill-rolling" tremor (4-6 Hz), cogwheel rigidity, bradykinesia (micrographia, hypomimia, shuffling gait, festination, reduced arm swing), postural instability (late).'),
  bl('Non-motor features: ', 'Anosmia (precedes motor symptoms by years), constipation, REM sleep behaviour disorder, orthostatic hypotension, depression; PD dementia in ~80% if followed long enough.'),
  sp(),
  h3('ALS / Motor Neurone Disease'),
  bl('', 'Combined UMN + LMN signs: fasciculations, wasting, weakness (LMN) + spasticity, hyperreflexia, Babinski sign (UMN).'),
  bl('Presentations: ', 'Limb onset (60%): focal weakness - wrist drop or foot drop; bulbar onset (30%): dysarthria, dysphagia, tongue fasciculations.'),
  bl('', 'Progressive respiratory failure; eye movements and sphincters are spared - key differentiating feature from other motor neurone diseases.'),
  sp(),
  h2('3.3  Demyelinating and Infectious Disease'),
  bl('Multiple sclerosis: ', 'Relapsing-remitting course with dissemination in time and space; optic neuritis (painful monocular visual loss, RAPD, Uhthoff\'s phenomenon), internuclear ophthalmoplegia, spastic paraparesis, bladder dysfunction, Lhermitte\'s sign, fatigue.'),
  bl('Bacterial meningitis: ', 'Classic triad - fever + neck stiffness + altered consciousness; Kernig\'s and Brudzinski\'s signs; non-blanching purpuric rash in meningococcal septicaemia (glass test); Waterhouse-Friderichsen syndrome (bilateral adrenal haemorrhage, DIC, shock).'),
  bl('Elderly meningitis: ', 'Neck stiffness absent or attributed to cervical spondylosis; Listeria monocytogenes more common; may present with only low-grade fever and confusion.'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 4. GASTROINTESTINAL AND HEPATIC
// ══════════════════════════════════════════════════════════════════════════════
const gi = [
  h1('4. Gastrointestinal and Hepatic System'),
  h2('4.1  Upper Gastrointestinal Disease'),
  bl('GORD: ', 'Retrosternal burning, acid regurgitation, water brash; extra-oesophageal features - chronic cough, laryngitis, asthma; Barrett\'s oesophagus (columnar metaplasia) carries risk of adenocarcinoma.'),
  bl('Duodenal ulcer: ', 'Epigastric pain relieved by food and antacids; nocturnal pain waking patient; periodicity (seasonal exacerbations). Gastric ulcer: pain worsened by food; weight loss more prominent.'),
  bl('PUD complications: ', 'Haemorrhage (haematemesis, melaena); perforation (sudden severe pain, board-like abdomen, peritonism, absent bowel sounds); pyloric obstruction (projectile vomiting, succussion splash, hypokalaemic hypochloraemic metabolic alkalosis).'),
  sp(),
  h2('4.2  Inflammatory Bowel Disease'),
  h3('Crohn\'s Disease'),
  bl('', 'Transmural inflammation; skip lesions; any site mouth to anus; diarrhoea (may be bloody), right iliac fossa pain and mass, weight loss, fever; smoking increases risk.'),
  bl('Complications: ', 'Perianal disease (fistulae, abscesses) in 20-30%; strictures causing intestinal obstruction; fistulae causing pneumaturia or faeculent vaginal discharge; B12 malabsorption (terminal ileum disease).'),
  bl('Extraintestinal: ', 'Peripheral arthropathy (mirrors disease activity), uveitis, episcleritis, erythema nodosum, pyoderma gangrenosum, oxalate renal stones.'),
  sp(),
  h3('Ulcerative Colitis'),
  bl('', 'Mucosal inflammation starting from rectum extending proximally; bloody diarrhoea (hallmark) with tenesmus and urgency; smoking is protective.'),
  bl('Severe UC (Truelove & Witts): ', '>6 bloody stools/day + fever, tachycardia, or anaemia.'),
  bl('Complications: ', 'Toxic megacolon (colonic dilatation >6 cm on AXR, systemic toxicity, peritonism - risk of perforation); long-term colorectal carcinoma risk after 8-10 years of pancolitis.'),
  sp(),
  h2('4.3  Liver Cirrhosis'),
  body('Aetiology: Alcohol, chronic HBV/HCV, NAFLD/NASH (metabolic syndrome), autoimmune hepatitis, primary biliary cholangitis, haemochromatosis, Wilson\'s disease.'),
  bl('Stigmata: ', 'Spider naevi, palmar erythema, leukonychia, gynaecomastia, testicular atrophy, loss of body hair, caput medusae, Dupuytren\'s contracture and parotid enlargement (alcohol).'),
  bl('Ascites: ', 'Shifting dullness, fluid thrill; spontaneous bacterial peritonitis presents with fever, abdominal pain, and deteriorating liver function.'),
  bl('Hepatic encephalopathy: ', 'Asterixis (hepatic flap), fetor hepaticus, personality change, cognitive impairment; grades I-IV.'),
  bl('Variceal haemorrhage: ', 'Haematemesis or melaena with haemodynamic compromise; driven by portal hypertension (HVPG >12 mmHg).'),
  bl('Hepatorenal syndrome: ', 'Functional AKI - oliguria, hyponatraemia; no intrinsic renal pathology.'),
  bl('Hepatocellular carcinoma: ', 'Rapid clinical deterioration, right upper quadrant pain, paraneoplastic features (hypoglycaemia, erythrocytosis, hypercalcaemia).'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 5. RENAL AND ENDOCRINE
// ══════════════════════════════════════════════════════════════════════════════
const renalEndo = [
  h1('5. Renal and Endocrine Systems'),
  h2('5.1  Renal Disease'),
  bl('Nephrotic syndrome: ', 'Proteinuria >3.5g/24h, hypoalbuminaemia, periorbital and peripheral oedema, frothy urine, hyperlipidaemia; complications include VTE (loss of AT-III, proteins S/C) and increased infection risk.'),
  bl('Nephritic syndrome: ', 'Haematuria (red cell casts), sub-nephrotic proteinuria, hypertension, oliguria, AKI; systemic features point to cause (rash in SLE, haemoptysis in anti-GBM disease).'),
  bl('Acute kidney injury: ', 'Oliguria/anuria, uraemic symptoms (nausea, vomiting, hiccups, pericarditis), hyperkalaemia (peaked T-waves, widened QRS), metabolic acidosis (Kussmaul breathing); pre-renal most common; BPH is the leading cause of post-renal AKI in elderly men.'),
  bl('Chronic kidney disease: ', 'Silent through stages 1-3; uraemic syndrome in stages 4-5 - pruritus, restless legs, peripheral neuropathy, secondary hyperparathyroidism (renal osteodystrophy - subperiosteal erosions, brown tumours), LVH, platelet dysfunction, normochromic normocytic anaemia. Creatinine underestimates severity in elderly due to reduced muscle mass.'),
  sp(),
  h2('5.2  Diabetes Mellitus'),
  bl('Type 1 DM: ', 'Acute onset polyuria, polydipsia, polyphagia, weight loss; DKA - Kussmaul breathing, ketotic (sweet/fruity) breath, vomiting, dehydration, altered consciousness.'),
  bl('Type 2 DM: ', 'Often asymptomatic or incidental; recurrent genital candidiasis, skin infections, osmotic blurring of vision. HHS in elderly: extreme hyperglycaemia (>30 mmol/L), profound dehydration, no/minimal ketosis, altered consciousness, focal neurological deficits - high mortality.'),
  bl('Microvascular complications: ', 'Retinopathy (background microaneurysms → proliferative new vessels/vitreous haemorrhage); nephropathy (microalbuminuria → CKD); neuropathy (painful nocturnal glove-and-stocking; autonomic - gastroparesis, postural hypotension, erectile dysfunction).'),
  bl('Macrovascular complications: ', 'Coronary artery disease (leading cause of death), peripheral arterial disease (claudication, Charcot foot), stroke.'),
  sp(),
  h2('5.3  Thyroid Disease'),
  bl('Hypothyroidism: ', 'Cold intolerance, weight gain, constipation, fatigue, bradycardia, dry coarse skin and hair, periorbital and peripheral non-pitting myxoedema, Queen Anne\'s sign (loss of outer third of eyebrows), hung-up tendon reflexes, hoarse voice; myxoedema coma (hypothermia, hypoventilation, coma).'),
  bl('Hyperthyroidism: ', 'Heat intolerance, weight loss, tremor, anxiety, palpitations/AF, diarrhoea, warm moist skin, proximal myopathy, lid lag, lid retraction.'),
  bl('Graves\' disease specific: ', 'Smooth goitre, exophthalmos/proptosis, periorbital oedema, diplopia, optic neuropathy, pretibial myxoedema.'),
  bl('Apathetic thyrotoxicosis (elderly): ', 'Depression, weight loss, AF, weakness - without classic sympathomimetic features; easily missed and attributed to "ageing".'),
  bl('Thyroid storm: ', 'Extreme hyperthyroidism - hyperthermia, delirium, extreme tachycardia, cardiac failure; 20-30% mortality without prompt treatment.'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 6. MUSCULOSKELETAL AND HAEMATOLOGICAL
// ══════════════════════════════════════════════════════════════════════════════
const mskHaem = [
  h1('6. Musculoskeletal, Rheumatological and Haematological Systems'),
  h2('6.1  Inflammatory Arthritis'),
  h3('Rheumatoid Arthritis'),
  bl('', 'Symmetrical small joint polyarthritis - MCPJs, PIPJs, wrists, MTPs; DIPJs spared; morning stiffness >1 hour; boggy synovial thickening.'),
  bl('Deformities: ', 'Swan neck, boutonniere, ulnar deviation, Z-thumb; subcutaneous rheumatoid nodules on extensor surfaces (olecranon).'),
  bl('Extraarticular: ', 'Pulmonary (ILD, pleuritis, nodules), cardiovascular (pericarditis, accelerated atherosclerosis), ocular (episcleritis, secondary Sjogren\'s), neurological (mononeuritis multiplex, atlanto-axial instability causing cervical myelopathy), Felty\'s syndrome (RA + splenomegaly + neutropenia), secondary AA amyloidosis.'),
  sp(),
  h3('Gout and Osteoarthritis'),
  bl('Acute gout: ', 'Sudden onset (often nocturnal) excruciating monoarthritis; first MTP joint (podagra) most classic; exquisitely tender, erythematous, swollen joint; systemic fever; precipitants include alcohol, diuretics, surgery, dehydration.'),
  bl('Chronic tophaceous gout: ', 'Chalky tophi at helix of ear, Achilles tendon, extensor surfaces; chronic joint damage; urate nephropathy.'),
  bl('Osteoarthritis: ', 'Activity-related joint pain improving with rest; bony hard swelling (osteophytes), crepitus, restricted range of motion; no systemic inflammation; Heberden\'s nodes (DIPJs), Bouchard\'s nodes (PIPJs), first CMC "square thumb"; most common cause of disability in adults >65 years.'),
  sp(),
  h3('SLE and Systemic Sclerosis'),
  bl('SLE: ', 'Butterfly malar rash (spares nasolabial folds), photosensitivity, oral ulcers, non-erosive arthritis, serositis, lupus nephritis, neuropsychiatric features (seizures, psychosis), haemolytic anaemia/leucopenia/thrombocytopenia, antiphospholipid syndrome.'),
  bl('Limited SSc (CREST): ', 'Calcinosis, Raynaud\'s phenomenon (often first symptom), oesophageal dysmotility, sclerodactyly, telangiectasia; anti-centromere antibodies; major complication is pulmonary arterial hypertension.'),
  bl('Diffuse SSc: ', 'Rapid extensive skin fibrosis, ILD (leading cause of death), scleroderma renal crisis (malignant hypertension, AKI), myocarditis; anti-Scl-70 (anti-topoisomerase I) antibodies.'),
  sp(),
  h2('6.2  Anaemias'),
  bl('Iron deficiency anaemia: ', 'Fatigue, pallor, koilonychia (spoon nails), angular stomatitis, glossitis, pica (ice, clay), Plummer-Vinson syndrome (dysphagia + post-cricoid web + IDA), restless legs; in elderly men and post-menopausal women - colorectal malignancy and angiodysplasia must be excluded.'),
  bl('Megaloblastic anaemia (B12/folate): ', 'Lemon-yellow pallor, glossitis; B12 specifically causes subacute combined degeneration of spinal cord (posterior columns + lateral corticospinal tracts: symmetrical paraesthesiae → ataxia → spasticity), dementia, psychosis. Folate deficiency does NOT cause neurological complications.'),
  bl('Anaemia of chronic disease: ', 'Mild-moderate normochromic normocytic anaemia; low serum iron, low TIBC, elevated ferritin; underlying disease (RA, IBD, CKD, malignancy) dominates the clinical picture.'),
  sp(),
  h2('6.3  Haematological Malignancies'),
  bl('Acute leukaemia: ', 'Bone marrow failure triad - anaemia (fatigue, pallor) + neutropenia (infections, mouth ulcers) + thrombocytopenia (petechiae, purpura, gum bleeding); organ infiltration: hepatosplenomegaly, lymphadenopathy, CNS disease; gum hypertrophy (AML M5); DIC in APL.'),
  bl('CML (BCR-ABL, t(9;22)): ', 'Massive splenomegaly (most prominent sign), constitutional symptoms; often incidental leucocytosis; blast crisis mimics acute leukaemia.'),
  bl('CLL: ', 'Painless lymphadenopathy, splenomegaly, fatigue; autoimmune haemolytic anaemia; hypogammaglobulinaemia causing recurrent infections; Richter\'s transformation.'),
  bl('Multiple myeloma (CRAB): ', 'Hypercalcaemia (confusion, constipation, polyuria), Renal failure (light chain cast nephropathy), Anaemia (normochromic normocytic), Bone pain/lytic lesions/pathological fractures; recurrent infections; hyperviscosity syndrome.'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 7. GERIATRIC AND INFECTIONS
// ══════════════════════════════════════════════════════════════════════════════
const geriatricInf = [
  h1('7. Geriatric Syndromes and Systemic Infectious Disease'),
  h2('7.1  Geriatric Syndromes'),
  h3('Frailty'),
  bl('Fried phenotype (3/5 = frail): ', 'Unintentional weight loss (>4.5 kg/year), self-reported exhaustion, weakness (reduced grip strength), slow walking speed, low physical activity.'),
  bl('', 'Underlying sarcopenia; increased risk of falls, hospitalisations, disability, and mortality.'),
  sp(),
  h3('Delirium (Acute Confusional State)'),
  bl('', 'Acute onset and fluctuating course (hours to days) distinguishes delirium from dementia; impaired attention, disorganised thinking, altered consciousness.'),
  bl('Hyperactive delirium: ', 'Agitation, combativeness, visual hallucinations - frequently misdiagnosed as acute psychosis.'),
  bl('Hypoactive delirium (most common, most missed): ', 'Withdrawal, drowsiness, reduced responsiveness - attributed to tiredness or dementia; carries worse prognosis than hyperactive type.'),
  bl('Common precipitants: ', 'Infection (UTI, pneumonia), drugs (opioids, anticholinergics, benzodiazepines), dehydration, urinary retention, pain, alcohol withdrawal, metabolic disturbance.'),
  sp(),
  h3('Falls, Incontinence and Pressure Ulcers'),
  bl('Falls: ', 'Hip fracture (shortened, externally rotated limb) most feared complication; subdural haematoma; "long lie" complications (hypothermia, rhabdomyolysis, aspiration pneumonia); fear of falling causes progressive deconditioning.'),
  bl('Urinary incontinence: ', 'Stress (sphincter weakness); Urge (overactive bladder); Overflow (BPH or detrusor underactivity - constant dribbling); Functional (mobility/cognitive impairment prevents reaching toilet).'),
  bl('Pressure ulcers: ', 'Stage 1 (non-blanchable erythema) to Stage 4 (bone/muscle exposed); risk factors: immobility, malnutrition, moisture, reduced sensation.'),
  sp(),
  h2('7.2  HIV/AIDS'),
  bl('Primary seroconversion (2-6 weeks): ', 'Mononucleosis-like illness - fever, pharyngitis, lymphadenopathy, maculopapular rash, oral/genital ulcers, diarrhoea.'),
  bl('AIDS-defining conditions by CD4 count:'),
  sbl('CD4 <200/μL: PCP (exertional dyspnoea, dry cough, bilateral perihilar infiltrates, elevated LDH); oesophageal candidiasis (dysphagia, odynophagia).'),
  sbl('CD4 <100/μL: Toxoplasma encephalitis (ring-enhancing lesions, focal deficits, seizures); cryptococcal meningitis (raised ICP, India ink positive).'),
  sbl('CD4 <50/μL: CMV retinitis ("pizza pie" fundus); MAC (fever, night sweats, diarrhoea, hepatosplenomegaly).'),
  bl('AIDS malignancies: ', 'Kaposi\'s sarcoma (purple/brown lesions - skin, palate, GI tract; HIV-8 associated); CNS lymphoma (EBV-associated, periventricular lesions); HIV-associated neurocognitive disorder.'),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 8. RAPID REFERENCE TABLE
// ══════════════════════════════════════════════════════════════════════════════
const tblSection = [
  h1('8. Rapid Reference: Differentiating Clinical Features by System and Aetiology'),
  sp(),
  makeTable(
    ['System', 'Ischaemic/Vascular', 'Inflammatory/Autoimmune', 'Infectious', 'Neoplastic/Degenerative'],
    [
      ['Cardiac', 'Chest pain, diaphoresis, ECG changes; cardiogenic shock', 'Pleuritic pain, friction rub, pericardial effusion, troponin rise', 'Fever, viral prodrome, myocarditis', 'Cachexia, effusion; progressive cardiomyopathy'],
      ['Respiratory', 'Acute dyspnoea, pleurisy, haemoptysis (PE)', 'Wheeze, eosinophilia, steroid-responsive (asthma)', 'Fever, productive cough, consolidation signs', 'Haemoptysis, clubbing, weight loss; basal Velcro crackles (IPF)'],
      ['Neurological', 'Sudden focal deficit; thunderclap headache (SAH)', 'Relapsing-remitting; optic neuritis, INO', 'Fever + meningism + purpuric rash', 'Progressive focal deficit; insidious cognitive decline, tremor, rigidity'],
      ['GI / Liver', 'Mesenteric ischaemia: severe periumbilical pain', 'Bloody diarrhoea, EIM, abdominal pain (IBD)', 'Fever, diarrhoea, jaundice (hepatitis)', 'Weight loss, altered bowel habit; cirrhosis stigmata, ascites, encephalopathy'],
      ['Renal', 'Pre-renal AKI: oliguria, reduced JVP', 'Haematuria, red cell casts, systemic features', 'Fever, dysuria, loin pain (pyelonephritis)', 'Painless haematuria; gradual GFR decline, uraemia'],
      ['Endocrine', 'N/A', 'Heat intolerance, tremor, AF (thyrotoxicosis)', 'Hypotension, adrenal crisis in sepsis', 'Hypercalcaemia (PTHrP); cold intolerance, bradycardia (hypothyroid)'],
      ['MSK', 'AVN: joint pain, steroid/alcohol history', 'Morning stiffness >1h, symmetric arthritis', 'Acute monoarthritis, fever (septic arthritis)', 'Bone pain, lytic lesions (myeloma); activity pain, crepitus (OA)'],
      ['Haematological', 'Hyperviscosity syndrome', 'AIHA, ITP, autoimmune cytopenias', 'Fever, neutropenia, splenomegaly', 'Anaemia, thrombocytopenia, lymphadenopathy (leukaemia/lymphoma)'],
    ]
  ),
  sp(), pb(),
];

// ══════════════════════════════════════════════════════════════════════════════
// 9. GERIATRIC PRINCIPLES
// ══════════════════════════════════════════════════════════════════════════════
const geriatricPrinciples = [
  h1('9. Core Principles: Disease Presentation in the Geriatric Population'),
  body('The geriatric population consistently manifests disease differently from younger adults. Understanding these principles is essential for accurate diagnosis and appropriate management.'),
  sp(),
  bl('Atypical Presentations: ', 'Classic symptoms are frequently absent. Confusion, falls, or functional decline may be the only manifestation of ACS, sepsis, stroke, or pulmonary embolism. A high index of suspicion and low threshold for investigation across all systems is essential.'),
  bl('Polypharmacy Effects: ', 'Multiple medications contribute to drug interactions and adverse effects that mask true disease or mimic illness (e.g., anticholinergic burden causing cognitive impairment; beta-blockers masking hypoglycaemia; diuretics precipitating dehydration and falls).'),
  bl('Reduced Physiological Reserve: ', 'The inflammatory response is blunted - absence of fever and leucocytosis is common even in severe sepsis. Renal clearance, hepatic metabolism, and cardiac reserve are all reduced. Recovery from acute illness is slower and complications more frequent.'),
  bl('Multimorbidity: ', 'Multiple co-existing conditions complicate diagnosis and management. A presenting complaint may have several simultaneous aetiologies. Treating one condition may exacerbate another (e.g., fluid replacement in AKI causing pulmonary oedema in co-existing heart failure).'),
  bl('Geriatric Giants: ', 'Instability (falls), Immobility, Intellectual decline (dementia/delirium), and Incontinence are the four classic geriatric syndromes that frequently represent the final common pathway of multiple underlying diseases across all organ systems.'),
  bl('Cognitive Impairment as a Confounder: ', 'Dementia impairs symptom reporting. Proxy history from carers, collateral from family members, and careful clinical observation are essential to accurate diagnosis.'),
  bl('Delirium vs. Dementia: ', 'Delirium is acute and fluctuating (hours to days onset); dementia is insidious and progressive (months to years). Delirium superimposed on dementia is common and carries poor prognosis. Hypoactive delirium (withdrawn, drowsy) is the most common and most frequently missed subtype.'),
  sp(),
];

// ── Assemble ──────────────────────────────────────────────────────────────────
const doc = new Document({
  title: 'Clinical Features of Multi-System Disease - Adult and Geriatric Population',
  sections: [{
    headers: {
      default: new Header({
        children: [
          new Paragraph({
            children: [new TextRun({ text: 'Clinical Features of Multi-System Disease  |  Adult & Geriatric Population', size: 17, font: 'Calibri', color: BLACK, italics: true })],
            alignment: AlignmentType.CENTER,
          }),
        ],
      }),
    },
    footers: {
      default: new Footer({
        children: [
          new Paragraph({
            children: [
              new TextRun({ text: 'Page ', size: 17, font: 'Calibri', color: BLACK }),
              new TextRun({ children: [PageNumber.CURRENT], size: 17, font: 'Calibri' }),
              new TextRun({ text: ' of ', size: 17, font: 'Calibri', color: BLACK }),
              new TextRun({ children: [PageNumber.TOTAL_PAGES], size: 17, font: 'Calibri' }),
            ],
            alignment: AlignmentType.CENTER,
          }),
        ],
      }),
    },
    children: [
      ...titlePage,
      ...cardio,
      ...resp,
      ...neuro,
      ...gi,
      ...renalEndo,
      ...mskHaem,
      ...geriatricInf,
      ...tblSection,
      ...geriatricPrinciples,
    ],
  }],
});

Packer.toBuffer(doc).then(buf => {
  fs.writeFileSync('/home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary_BW.docx', buf);
  console.log('Done.');
});
Running Command

cd /home/daytona/workspace/multisystem-summary && node generate_bw.js 2>&1

Running Command

python3 -c " import zipfile, os f = '/home/daytona/workspace/multisystem-summary/MultiSystem_Disease_Summary_BW.docx' print('Valid DOCX:', zipfile.is_zipfile(f)) print('Size:', os.path.getsize(f), 'bytes (', round(os.path.getsize(f)/1024,1), 'KB)') "

Your Word file is ready.

MultiSystem Disease Summary BW

Word Document · DOCX

  • Fully black and white
  • No references, no sources - topic headings and clinical discussion only
  • Same 9-section structure as the PDF
  • Includes the rapid reference table, page numbers, and a running header
  • Editable in Microsoft Word or Google Docs
This is a shared conversation. Sign in to Orris to start your own chat.