Make notes with new guidelines and harrison but content should be in chronological way ( definition , etiology, risk factor pathophysiology, investigation , treatment and prevention),add relevent images, types of heart failure, classification of heart failure ,

Asking for Preferences
Reading File
Finding Sources
Searching PubMed

"heart failure" AND "guidelines"

Finding Sources
Searching PubMed

"heart failure" AND "AHA" AND "ACC"

Reading File
Searching PubMed

"heart failure" AND "management" AND "guideline"

Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/heart-failure-notes && ls /home/daytona/workspa…

Writing File

~/heart-failure-notes/create_hf_notes.js

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

// Helper to download image as buffer
function downloadImage(url) {
  return new Promise((resolve, reject) => {
    const proto = url.startsWith('https') ? https : http;
    proto.get(url, (res) => {
      const chunks = [];
      res.on('data', chunk => chunks.push(chunk));
      res.on('end', () => resolve(Buffer.concat(chunks)));
      res.on('error', reject);
    }).on('error', reject);
  });
}

function heading1(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_1,
    spacing: { before: 400, after: 200 },
    shading: { type: ShadingType.CLEAR, fill: "1B4F8A", color: "1B4F8A" },
  });
}

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

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

function para(text, bold = false, color = "000000") {
  return new Paragraph({
    children: [new TextRun({ text, bold, color, size: 22, font: "Calibri" })],
    spacing: { before: 80, after: 80 },
  });
}

function bullet(text, bold = false, level = 0) {
  return new Paragraph({
    bullet: { level },
    children: [new TextRun({ text, bold, size: 21, font: "Calibri" })],
    spacing: { before: 60, after: 60 },
  });
}

function boldBullet(label, text) {
  return new Paragraph({
    bullet: { level: 0 },
    children: [
      new TextRun({ text: label + ": ", bold: true, size: 21, font: "Calibri" }),
      new TextRun({ text, size: 21, font: "Calibri" }),
    ],
    spacing: { before: 60, after: 60 },
  });
}

function subBullet(text) {
  return bullet(text, false, 1);
}

function tableRow(cells, isHeader = false) {
  return new TableRow({
    children: cells.map(cell =>
      new TableCell({
        children: [new Paragraph({
          children: [new TextRun({ text: cell, bold: isHeader, size: isHeader ? 22 : 20, font: "Calibri", color: isHeader ? "FFFFFF" : "000000" })],
          alignment: AlignmentType.LEFT,
        })],
        shading: isHeader ? { type: ShadingType.CLEAR, fill: "1B4F8A" } : undefined,
        verticalAlign: VerticalAlign.CENTER,
        margins: { top: 80, bottom: 80, left: 100, right: 100 },
      })
    ),
  });
}

function makeTable(headers, rows) {
  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    rows: [
      tableRow(headers, true),
      ...rows.map(r => tableRow(r, false))
    ],
    margins: { top: 100, bottom: 100 },
  });
}

function figureCaption(text) {
  return new Paragraph({
    children: [new TextRun({ text, italics: true, size: 19, color: "444444", font: "Calibri" })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 60, after: 160 },
  });
}

function divider() {
  return new Paragraph({
    text: "",
    border: { bottom: { color: "1B4F8A", space: 1, style: BorderStyle.SINGLE, size: 6 } },
    spacing: { before: 100, after: 100 },
  });
}

async function buildDoc() {
  // Download images
  console.log("Downloading images...");
  let img1, img2, img3, img4, img5;
  try {
    img1 = await downloadImage("https://cdn.orris.care/cdss_images/cbba550454c02d166253fee2fcb04fa6bb76a592c807e3a2642298b9a07cdb85.png");
    console.log("img1 done");
  } catch(e) { console.log("img1 failed:", e.message); }
  try {
    img2 = await downloadImage("https://cdn.orris.care/cdss_images/890c7a4845b6a5fb382cfa357249fa72f8241b1afe0b9cf13f4147a4a6f46b86.png");
    console.log("img2 done");
  } catch(e) { console.log("img2 failed:", e.message); }
  try {
    img3 = await downloadImage("https://cdn.orris.care/cdss_images/aba0d5980eee4ffb5a0c568899104a414e9fe7ad25af5a69fb4bfeb9aad1a8cf.png");
    console.log("img3 done");
  } catch(e) { console.log("img3 failed:", e.message); }
  try {
    img4 = await downloadImage("https://cdn.orris.care/cdss_images/1ea1d184c591360aeab2a1464781df114cc4bcdb7597bda494398bac4004c328.png");
    console.log("img4 done");
  } catch(e) { console.log("img4 failed:", e.message); }

  const children = [];

  // === TITLE ===
  children.push(new Paragraph({
    children: [new TextRun({ text: "HEART FAILURE", bold: true, size: 56, color: "1B4F8A", font: "Calibri" })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 400, after: 100 },
  }));
  children.push(new Paragraph({
    children: [new TextRun({ text: "Comprehensive Clinical Notes", size: 30, color: "444444", italics: true, font: "Calibri" })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 60, after: 60 },
  }));
  children.push(new Paragraph({
    children: [new TextRun({ text: "Sources: Harrison's Principles of Internal Medicine 22E (2025) | Braunwald's Heart Disease | AHA/ACC/HFSA Guidelines 2022 | 2021 ESC Guidelines", size: 19, color: "666666", font: "Calibri" })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 80, after: 80 },
  }));
  children.push(new Paragraph({
    children: [new TextRun({ text: "Date: July 2026", size: 19, color: "666666", font: "Calibri" })],
    alignment: AlignmentType.CENTER,
    spacing: { before: 60, after: 400 },
  }));
  children.push(divider());

  // ============================================================
  // 1. DEFINITION
  // ============================================================
  children.push(heading1("1. DEFINITION"));
  children.push(para(
    "Heart failure (HF) is a common final pathway for most chronic cardiovascular diseases including hypertension, coronary artery disease, and valvular heart disease.",
    false
  ));

  children.push(heading2("AHA/ACC/HFSA Definition (2022)"));
  children.push(para(
    "HF is a complex clinical syndrome with symptoms and signs that result from any structural or functional impairment of ventricular filling or ejection of blood."
  ));

  children.push(heading2("ESC Definition (2021)"));
  children.push(para(
    "HF is a clinical syndrome in which cardinal symptoms (breathlessness, ankle swelling, fatigue) may be accompanied by signs (elevated jugular venous pressure, pulmonary crackles, peripheral edema) due to a structural and/or functional cardiac abnormality resulting in elevated intracardiac pressures and/or inadequate cardiac output at rest and/or during exercise."
  ));

  children.push(heading2("Universal Definition (Bozkurt et al., 2021)"));
  children.push(para(
    "HF is a clinical syndrome with symptoms and/or signs caused by a structural and/or functional cardiac abnormality and corroborated by elevated natriuretic peptide levels and/or objective evidence of cardiogenic pulmonary or systemic congestion."
  ));

  // Universal definition image
  if (img1) {
    children.push(new Paragraph({
      children: [new ImageRun({ data: img1, transformation: { width: 580, height: 320 } })],
      alignment: AlignmentType.CENTER,
      spacing: { before: 120, after: 60 },
    }));
    children.push(figureCaption("FIGURE 1: Universal Definition of Heart Failure (Harrison's 22E, Fig. 264-1). A conceptually comprehensive definition with near universal applicability, prognostic and therapeutic validity, and acceptable sensitivity and specificity."));
  }

  children.push(heading2("Key Terminology"));
  children.push(boldBullet("Chronic HF", "Longstanding (months to years) symptoms/signs of HF treated with medical/device therapy. When stable, prefer 'remission' rather than 'stable HF'."));
  children.push(boldBullet("Acute HF (Acute Decompensated HF)", "Rapid onset or worsening of HF symptoms. ~80% are worsening of chronic HF; ~20% are new-onset (ACS, acute valvular dysfunction, hypertensive urgency, postcardiotomy syndrome)."));
  children.push(boldBullet("Acute Pulmonary Edema", "Rapidly worsening signs/symptoms of pulmonary congestion due to severe elevation of left heart filling pressures."));
  children.push(boldBullet("Cardiomyopathy / LV Dysfunction", "More general terms for disorders of myocardial structure/function that may lead to HF."));
  children.push(divider());

  // ============================================================
  // 2. EPIDEMIOLOGY
  // ============================================================
  children.push(heading1("2. EPIDEMIOLOGY"));
  children.push(boldBullet("US Prevalence", "~6.7 million American adults treated for HF; >600,000 new cases/year. Expected to rise to 8.5 million by 2030."));
  children.push(boldBullet("Global", "~56.2 million people worldwide living with HF."));
  children.push(boldBullet("Age", "Prevalence: 1-2% in ages 40-49 years; >10% in adults >80 years. Lifetime risk: ~24% (one in four persons)."));
  children.push(boldBullet("Mortality", "Overall 5-year survival after HF diagnosis: ~50%. 1-year mortality in severe HF: up to 40%. 1 in 8 deaths in the US list HF on death certificate."));
  children.push(boldBullet("Racial disparities", "Black individuals have highest HF risk, followed by Hispanic, White, and Chinese Americans, driven by disparities in cardiometabolic risk factors and social determinants of health."));

  if (img2) {
    children.push(new Paragraph({
      children: [new ImageRun({ data: img2, transformation: { width: 500, height: 280 } })],
      alignment: AlignmentType.CENTER,
      spacing: { before: 120, after: 60 },
    }));
    children.push(figureCaption("FIGURE 2: Heart Failure Prevalence by Age (NHANES 2017-2020). Prevalence rises steeply with age, exceeding 10% in adults >80 years. (Harrison's 22E, Fig. 264-2)"));
  }
  children.push(divider());

  // ============================================================
  // 3. ETIOLOGY
  // ============================================================
  children.push(heading1("3. ETIOLOGY"));
  children.push(para("HF can result from any cardiovascular disease. The most common cause worldwide is coronary artery disease. Hypertension remains the highest population attributable risk factor for HF occurrence."));

  children.push(heading2("HFrEF (Systolic HF) Causes"));
  children.push(bullet("Coronary artery disease / Ischemic cardiomyopathy (most common in Western nations)", true));
  children.push(bullet("Dilated cardiomyopathy (idiopathic, genetic, viral myocarditis, peripartum, alcoholic)"));
  children.push(bullet("Hypertension (chronic pressure overload)"));
  children.push(bullet("Valvular heart disease (AR, MR causing volume overload; AS causing pressure overload)"));
  children.push(bullet("Cardiotoxins (anthracyclines, trastuzumab, radiation, methamphetamine)"));
  children.push(bullet("Metabolic/endocrine: thyrotoxicosis, hypothyroidism, diabetes, acromegaly"));
  children.push(bullet("Infiltrative: amyloidosis, sarcoidosis, hemochromatosis"));
  children.push(bullet("Tachycardia-induced cardiomyopathy"));
  children.push(bullet("Chagas disease (endemic regions)"));

  children.push(heading2("HFpEF (Diastolic HF) Causes"));
  children.push(bullet("Hypertension (most common - leads to LV hypertrophy and diastolic dysfunction)", true));
  children.push(bullet("Obesity and metabolic syndrome"));
  children.push(bullet("Diabetes mellitus"));
  children.push(bullet("Atrial fibrillation"));
  children.push(bullet("Advanced age"));
  children.push(bullet("Cardiac amyloidosis (ATTR most common infiltrative cause)"));
  children.push(bullet("Hypertrophic cardiomyopathy"));
  children.push(bullet("Pericardial disease (constrictive pericarditis)"));

  children.push(heading2("Right Heart Failure Causes"));
  children.push(bullet("Left heart failure (most common cause of right HF)"));
  children.push(bullet("Pulmonary arterial hypertension"));
  children.push(bullet("Right ventricular myocardial infarction"));
  children.push(bullet("Pulmonary embolism"));
  children.push(bullet("Cor pulmonale (chronic lung disease)"));
  children.push(divider());

  // ============================================================
  // 4. TYPES OF HEART FAILURE
  // ============================================================
  children.push(heading1("4. TYPES OF HEART FAILURE"));

  children.push(heading2("4a. Based on Ejection Fraction (EF)"));
  children.push(makeTable(
    ["Type", "EF", "Former Name", "Key Features"],
    [
      ["HFrEF", "< 40%", "Systolic HF", "Reduced pump function; neurohormonal activation; responds well to RAAS/BB/SGLT-2i"],
      ["HFmrEF", "40-49%", "Mid-range EF", "Mixed features; may improve to HFpEF or deteriorate to HFrEF; SGLT-2i show benefit"],
      ["HFpEF", "≥ 50%", "Diastolic HF", "Preserved systolic function; abnormal relaxation/compliance; driven by HTN, obesity, age"],
      ["HFrecEF", "Previously <40%, now ≥40%", "Recovered EF", "Due to effective therapy; still requires ongoing treatment; risk of relapse if therapy stopped"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));
  children.push(para("Note: HFmrEF and HFrecEF were added in the 2021 ESC Guidelines and 2022 AHA/ACC/HFSA Guidelines as distinct phenotypes.", false));

  children.push(heading2("4b. Based on Time Course"));
  children.push(boldBullet("Acute HF", "New onset or rapid decompensation. Includes acute pulmonary edema, cardiogenic shock, ADHF."));
  children.push(boldBullet("Chronic HF", "Persistent symptoms for months to years. Subdivided into 'stable' (in remission) and 'decompensated'."));
  children.push(boldBullet("Chronic HF with Acute Decompensation (ADHF)", "Most common HF hospitalization type (~80%). Triggered by precipitating factors."));

  children.push(heading2("4c. Based on Side of Heart"));
  children.push(boldBullet("Left-sided HF", "Pulmonary congestion dominant: orthopnea, PND, pulmonary edema, crackles. Caused by LV dysfunction."));
  children.push(boldBullet("Right-sided HF", "Systemic venous congestion: JVD, peripheral edema, hepatomegaly, ascites. Often secondary to left HF or pulmonary disease."));
  children.push(boldBullet("Biventricular HF", "Both ventricles involved; features of both left and right HF."));

  children.push(heading2("4d. Based on Hemodynamic Profile"));
  children.push(makeTable(
    ["Profile", "Wet/Dry", "Warm/Cold", "Management"],
    [
      ["Warm & Wet (most common)", "Volume overloaded", "Good perfusion", "Diuretics, vasodilators"],
      ["Warm & Dry", "Euvolemic", "Good perfusion", "Optimize medications"],
      ["Cold & Wet", "Volume overloaded", "Poor perfusion", "Inotropes + diuretics"],
      ["Cold & Dry", "Euvolemic", "Poor perfusion", "Volume challenge + inotropes"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));
  children.push(divider());

  // ============================================================
  // 5. CLASSIFICATION OF HEART FAILURE
  // ============================================================
  children.push(heading1("5. CLASSIFICATION OF HEART FAILURE"));

  children.push(heading2("5a. NYHA Functional Classification (Symptom-Based)"));
  children.push(makeTable(
    ["Class", "Description", "Symptoms"],
    [
      ["Class I", "No limitation", "No symptoms with ordinary physical activity"],
      ["Class II", "Slight limitation", "Comfortable at rest; symptoms with moderate exertion"],
      ["Class III", "Marked limitation", "Comfortable at rest; symptoms with minimal exertion"],
      ["Class IV", "Symptoms at rest", "Unable to carry out any physical activity without discomfort; symptoms at rest"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));

  children.push(heading2("5b. AHA/ACC Staging (Disease Progression-Based, 2022)"));
  children.push(para("This staging emphasizes prevention and reflects the progressive nature of HF. Stage can only advance, not regress."));
  children.push(makeTable(
    ["Stage", "Description", "Examples"],
    [
      ["Stage A\n(At Risk)", "Risk factors for HF; no symptoms, no structural disease", "HTN, DM, obesity, CAD, family history of cardiomyopathy, cardiotoxin exposure"],
      ["Stage B\n(Pre-HF)", "Structural heart disease OR abnormal cardiac biomarkers; NO symptoms ever", "Asymptomatic LV dysfunction, LVH, prior MI, elevated BNP without symptoms"],
      ["Stage C\n(HF)", "Structural heart disease WITH current or prior symptoms of HF", "Symptomatic HF - includes all patients with NYHA I-IV with structural disease"],
      ["Stage D\n(Advanced HF)", "Refractory HF requiring advanced therapies", "Recurrent hospitalizations, LVAD candidates, transplant candidates, palliative care"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));
  children.push(para("Key Point: Stages A and B represent opportunities for prevention. Stage D patients need advanced interventions such as LVAD, heart transplant, or palliative care.", false));

  children.push(heading2("5c. Killip Classification (Post-AMI Setting)"));
  children.push(makeTable(
    ["Class", "Features", "Approximate Mortality"],
    [
      ["Class I", "No signs of HF", "5%"],
      ["Class II", "Mild HF: S3, basal crackles", "10%"],
      ["Class III", "Acute pulmonary edema", "40%"],
      ["Class IV", "Cardiogenic shock", "80-90%"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));
  children.push(divider());

  // ============================================================
  // 6. RISK FACTORS
  // ============================================================
  children.push(heading1("6. RISK FACTORS"));

  children.push(heading2("Modifiable Risk Factors"));
  children.push(bullet("Hypertension (highest population attributable risk)", true));
  children.push(bullet("Coronary artery disease / Ischemic heart disease"));
  children.push(bullet("Diabetes mellitus (10-40% prevalence in ambulatory HF cohorts)"));
  children.push(bullet("Obesity (obesity paradox: obese HF patients have better short-term prognosis)"));
  children.push(bullet("Dyslipidemia"));
  children.push(bullet("Smoking"));
  children.push(bullet("Excessive alcohol use"));
  children.push(bullet("Cardiotoxin exposure (anthracyclines, trastuzumab, cocaine, methamphetamine)"));
  children.push(bullet("Valvular heart disease"));

  children.push(heading2("Non-Modifiable Risk Factors"));
  children.push(bullet("Advanced age (strongest single risk factor)"));
  children.push(bullet("Male sex (higher incidence, but women have higher prevalence of HFpEF)"));
  children.push(bullet("Black race (highest risk, especially for HFrEF)"));
  children.push(bullet("Genetic predisposition (familial dilated cardiomyopathy, ATTR amyloidosis - Val122Ile variant in Black individuals)"));
  children.push(bullet("Prior myocardial infarction"));

  children.push(heading2("Independent Predictors of Mortality in HF"));
  children.push(bullet("LVEF < 25%"));
  children.push(bullet("NYHA Class IV"));
  children.push(bullet("BUN > 43 mg/dL"));
  children.push(bullet("Creatinine > 2.75 mg/dL"));
  children.push(bullet("Low systolic BP < 115 mmHg"));
  children.push(bullet("Elevated cardiac biomarkers (troponin, BNP/NT-proBNP)"));
  children.push(bullet("6-min walk test < 300 m"));
  children.push(bullet("Peak VO2 < 10-14 mL/kg/min"));
  children.push(bullet("QRS duration > 120 ms (LBBB)"));
  children.push(bullet("Hyponatremia, anemia, iron deficiency"));
  children.push(bullet("Depression (independent predictor, especially older women)"));
  children.push(divider());

  // ============================================================
  // 7. PATHOPHYSIOLOGY
  // ============================================================
  children.push(heading1("7. PATHOPHYSIOLOGY"));

  children.push(heading2("7a. Cardiac Remodeling"));
  children.push(para(
    "Ventricular remodeling is the hallmark of progressive HF. Chronic hemodynamic stimuli (pressure and volume overload, neurohormonal activation, inflammatory cytokines, and oxidative stress) lead to progressive changes in ventricular size, shape, and function."
  ));
  children.push(bullet("Pressure overload (HTN, AS) → concentric hypertrophy → diastolic dysfunction → HFpEF"));
  children.push(bullet("Volume overload (AR, MR) → eccentric hypertrophy → dilated cardiomyopathy → HFrEF"));
  children.push(bullet("Loss of cardiomyocytes (MI, myocarditis) → compensatory hypertrophy of remaining myocytes"));
  children.push(bullet("Myocyte changes: reexpression of fetal contractile/calcium handling proteins, apoptosis, fibrosis"));
  children.push(bullet("The remodeled heart is spherical, dilated, and thin-walled → increased wall stress → further impaired function (vicious cycle)"));

  if (img3) {
    children.push(new Paragraph({
      children: [new ImageRun({ data: img3, transformation: { width: 540, height: 300 } })],
      alignment: AlignmentType.CENTER,
      spacing: { before: 120, after: 60 },
    }));
    children.push(figureCaption("FIGURE 3: Remodeling Stimuli in Heart Failure. Pressure/volume overload leads to ventricular remodeling through increases in wall stress, inflammatory cytokines, neuroendocrine signals, and oxidative stress. Maladaptive changes cause further dysfunction in a vicious cycle. (Harrison's 22E, Fig. 264-6)"));
  }

  children.push(heading2("7b. Neurohormonal Activation"));
  children.push(para("The neurohormonal model of HF is the basis for modern pharmacotherapy. Two key systems are activated:"));

  children.push(heading3("Sympathetic Nervous System (SNS) Activation"));
  children.push(bullet("Initially compensatory: increases HR, BP, contractility, maintains CO"));
  children.push(bullet("Chronically: excessive vasoconstriction, volume retention, baroreceptor dysfunction"));
  children.push(bullet("Direct myocardial toxicity, pro-arrhythmic effects"));
  children.push(bullet("Elevated norepinephrine levels = independent mortality predictor"));
  children.push(bullet("β-blockers counteract this pathway → mortality benefit"));

  children.push(heading3("RAAS Activation"));
  children.push(bullet("Low CO → decreased renal perfusion → renin release → angiotensin II → aldosterone"));
  children.push(bullet("Angiotensin II: vasoconstriction, sodium retention, myocardial fibrosis, sympathetic potentiation"));
  children.push(bullet("Aldosterone: sodium/water retention, potassium loss, myocardial and vascular fibrosis"));
  children.push(bullet("RAAS blockade (ACEi/ARB/ARNI + MRA) is cornerstone of HFrEF therapy"));

  children.push(heading3("Natriuretic Peptide System (Counter-regulatory)"));
  children.push(bullet("BNP released by ventricular myocytes in response to wall stress"));
  children.push(bullet("ANP released by atria in response to volume overload"));
  children.push(bullet("Actions: natriuresis, vasodilation, anti-fibrotic, anti-remodeling"));
  children.push(bullet("Sacubitril (neprilysin inhibitor) prevents BNP degradation → amplifies beneficial effects"));
  children.push(bullet("NT-proBNP: inactive cleavage product, better diagnostic/prognostic marker"));

  children.push(heading2("7c. Hemodynamic Abnormalities"));
  children.push(bullet("Reduced stroke volume → reduced CO → compensatory HR increase and peripheral vasoconstriction"));
  children.push(bullet("Increased preload (LVEDP) → elevated PCWP → pulmonary venous hypertension → dyspnea"));
  children.push(bullet("Increased afterload (SVR) → further reduces SV → worsens CO"));
  children.push(bullet("Frank-Starling mechanism: initially preserves CO but eventually fails with extreme dilation"));
  children.push(bullet("Cardiorenal syndrome: reduced renal perfusion → sodium avidity → fluid retention → worsens preload"));

  children.push(heading2("7d. HFpEF Pathophysiology (Distinct Mechanisms)"));
  children.push(bullet("Impaired myocardial relaxation (lusitropy): abnormal calcium reuptake into SR via SERCA2a"));
  children.push(bullet("Increased ventricular stiffness: fibrosis, concentric LVH, impaired titin phosphorylation"));
  children.push(bullet("Microvascular inflammation: driven by comorbidities (HTN, obesity, DM) → nitrosative stress, reduced NO signaling"));
  children.push(bullet("Exercise intolerance due to chronotropic incompetence and impaired LV reserve"));
  children.push(bullet("Cardiometabolic contributions: insulin resistance, oxidative stress, adipokines"));
  children.push(bullet("Vascular stiffness: increased aortic impedance → acute pressure rises with exercise"));
  children.push(divider());

  // ============================================================
  // 8. CLINICAL FEATURES
  // ============================================================
  children.push(heading1("8. CLINICAL FEATURES"));

  children.push(heading2("Symptoms"));
  children.push(heading3("Left Heart Failure (Pulmonary Congestion)"));
  children.push(bullet("Dyspnea on exertion (earliest and most common)"));
  children.push(bullet("Orthopnea (dyspnea when lying flat; improves sitting up; measured in 'pillows')"));
  children.push(bullet("Paroxysmal nocturnal dyspnea (PND): wakes from sleep 1-3 hours after lying down; highly specific for HF"));
  children.push(bullet("Trepopnea: dyspnea in lateral decubitus position"));
  children.push(bullet("Platypnea: dyspnea upright, relieved by lying down (hepatopulmonary syndrome)"));
  children.push(bullet("Cardiac asthma (wheeze due to pulmonary edema)"));
  children.push(bullet("Acute pulmonary edema: severe dyspnea at rest, pink frothy sputum, cyanosis"));

  children.push(heading3("Right Heart Failure (Systemic Venous Congestion)"));
  children.push(bullet("Peripheral edema (bilateral, pitting, dependent)"));
  children.push(bullet("Nocturia (improved CO supine → increased renal perfusion)"));
  children.push(bullet("RUQ abdominal discomfort (hepatic congestion)"));
  children.push(bullet("Anorexia, nausea, abdominal bloating"));
  children.push(bullet("Ascites in severe/chronic right HF"));

  children.push(heading3("Low Output Symptoms"));
  children.push(bullet("Fatigue and weakness (reduced CO)"));
  children.push(bullet("Exercise intolerance"));
  children.push(bullet("Oliguria (advanced HF with severe renal hypoperfusion)"));
  children.push(bullet("Cold extremities, peripheral cyanosis"));
  children.push(bullet("Altered mental status (severe HF)"));
  children.push(bullet("Cardiac cachexia: unintentional edema-free weight loss >5% over 12 months; bitemporal/upper body muscle wasting"));

  children.push(heading2("Physical Examination"));
  children.push(heading3("Vital Signs"));
  children.push(bullet("BP: low (cardiogenic shock), normal, or high (hypertensive HF)"));
  children.push(bullet("Tachycardia (compensatory or AF)"));
  children.push(bullet("Pulsus alternans: alternating strong/weak pulse in severe LV dysfunction"));
  children.push(bullet("Narrow pulse pressure (reduced SV)"));

  children.push(heading3("JVP Assessment (KEY)"));
  children.push(bullet("Elevated JVP (>3 cm above sternal angle): indicates increased right atrial pressure and volume overload"));
  children.push(bullet("Abdominojugular reflux (HJR): sustained JVP elevation >3 cm with abdominal compression >10 sec"));
  children.push(bullet("Kussmaul's sign: paradoxical JVP rise with inspiration (constrictive pericarditis, severe RV failure)"));

  children.push(heading3("Cardiac Examination"));
  children.push(bullet("Displaced apex (laterally/inferiorly) in dilated LV"));
  children.push(bullet("S3 gallop (protodiastolic gallop): most specific for HF with elevated filling pressures; indicates systolic dysfunction"));
  children.push(bullet("S4 gallop: atrial gallop; indicates diastolic dysfunction/reduced LV compliance"));
  children.push(bullet("Mitral regurgitation murmur (functional, due to annular dilation)"));
  children.push(bullet("Tricuspid regurgitation (elevated RVSP)"));

  children.push(heading3("Respiratory"));
  children.push(bullet("Bilateral basal fine crepitations (pulmonary edema)"));
  children.push(bullet("Pleural effusion (especially right-sided or bilateral)"));
  children.push(bullet("Cheyne-Stokes respiration (crescendo-decrescendo pattern with apnea)"));

  children.push(heading3("Abdomen & Periphery"));
  children.push(bullet("Hepatomegaly (tender in acute right HF)"));
  children.push(bullet("Splenomegaly (chronic congestion)"));
  children.push(bullet("Ascites (shifting dullness)"));
  children.push(bullet("Bilateral pitting edema"));
  children.push(bullet("Scrotal edema (severe cases)"));
  children.push(divider());

  // ============================================================
  // 9. INVESTIGATIONS
  // ============================================================
  children.push(heading1("9. INVESTIGATIONS"));

  children.push(heading2("Biomarkers (Essential)"));
  children.push(makeTable(
    ["Biomarker", "Cut-off (Rule-in HF)", "Rule-out (Low Probability)", "Notes"],
    [
      ["BNP", ">100 pg/mL", "<35 pg/mL", "Best biomarker; elevated by volume/pressure overload; reduced by neprilysin inhibitors (sacubitril)"],
      ["NT-proBNP", ">900 pg/mL (age <75)\n>1800 pg/mL (≥75)", "<125 pg/mL", "More stable; age-adjusted cut-offs; not affected by neprilysin inhibitors"],
      ["hs-Troponin T/I", "Elevated", "-", "Indicates ongoing myocardial injury; elevated in ACS, ADHF, myocarditis"],
      ["Serum Creatinine / eGFR", "Monitor", "-", "Cardiorenal syndrome; prognostic; guides diuretic therapy"],
      ["Serum Na", "Monitor", "-", "Hyponatremia = poor prognosis"],
      ["Iron Studies", "Ferritin, TSAT", "-", "Iron deficiency (Ferritin <100 ng/mL or 100-299 + TSAT <20%): IV iron improves outcomes"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));

  children.push(heading2("ECG"));
  children.push(bullet("Not diagnostic alone, but guides management"));
  children.push(bullet("Sinus tachycardia (most common finding)"));
  children.push(bullet("LBBB (QRS >120 ms): CRT indication if NYHA II-IV + LVEF ≤35%"));
  children.push(bullet("Q waves: prior MI (ischemic cardiomyopathy)"));
  children.push(bullet("Atrial fibrillation: common trigger/comorbidity"));
  children.push(bullet("LVH: Sokolow-Lyon criteria (SV1 + RV5/V6 >35 mm)"));
  children.push(bullet("Low voltage + sinus rhythm: cardiac amyloidosis (voltage-mass discordance on echo)"));

  children.push(heading2("Chest X-Ray (CXR)"));
  children.push(bullet("Cardiomegaly (CTR >0.5)"));
  children.push(bullet("Upper lobe diversion / Cephalization"));
  children.push(bullet("Pulmonary vascular congestion, interstitial edema"));
  children.push(bullet("Kerley B lines (short horizontal lines at periphery in interstitial edema)"));
  children.push(bullet("Bat-wing/butterfly perihilar haziness (alveolar edema)"));
  children.push(bullet("Pleural effusions (typically right > left, or bilateral)"));
  children.push(bullet("'ABCDE' of CXR in HF: Alveolar edema, Kerley B lines, Cardiomegaly, Dilated vessels, Effusions"));

  children.push(heading2("Echocardiography (KEY investigation)"));
  children.push(para("Echocardiography is the most important diagnostic test in HF - provides structural and functional assessment."));
  children.push(heading3("Parameters"));
  children.push(bullet("LVEF: HFrEF <40%, HFmrEF 40-49%, HFpEF ≥50%"));
  children.push(bullet("LV size and wall thickness (dilated vs hypertrophic)"));
  children.push(bullet("Diastolic function grading (E/A ratio, E/e' ratio, LA volume index, TR velocity)"));
  children.push(subBullet("Grade I: Impaired relaxation (E/A <0.8, E/e' <9)"));
  children.push(subBullet("Grade II: Pseudonormalization (E/A 0.8-2, E/e' 9-14)"));
  children.push(subBullet("Grade III: Restrictive filling (E/A >2, E/e' >14)"));
  children.push(bullet("Valvular abnormalities"));
  children.push(bullet("Pericardial effusion"));
  children.push(bullet("Estimated RVSP / pulmonary hypertension"));
  children.push(bullet("Wall motion abnormalities (ischemic disease)"));
  children.push(bullet("Strain imaging (GLS <-20%): early detection of subclinical dysfunction"));

  children.push(heading2("Additional Investigations"));
  children.push(makeTable(
    ["Test", "Indication / Finding"],
    [
      ["Exercise Testing / Cardiopulmonary Exercise Test (CPET)", "Peak VO2 <14 mL/kg/min = advanced HF (LVAD/transplant threshold); VO2 <10 = very advanced disease"],
      ["Cardiac MRI", "Gold standard for LVEF; late gadolinium enhancement (LGE) characterizes myocardial fibrosis, amyloid, sarcoid, myocarditis; viability assessment"],
      ["Coronary Angiography / CT Coronary Angiography", "Rule out CAD as etiology (new HF without clear cause); guide revascularization"],
      ["Nuclear Imaging (PET/SPECT)", "Myocardial viability; cardiac amyloid (pyrophosphate scan for ATTR)"],
      ["Right Heart Catheterization (Swan-Ganz)", "Hemodynamic assessment in ADHF resistant to treatment, pre-transplant/LVAD evaluation, pulmonary HTN workup"],
      ["6-Min Walk Test", "Functional capacity assessment; <300 m = poor prognosis; serial monitoring of therapy response"],
      ["Holter / Device Monitoring", "Ventricular arrhythmias (ICD indication); AF burden"],
      ["Sleep Study", "Rule out obstructive/central sleep apnea (common comorbidity in HFrEF)"],
      ["Thyroid function tests", "Hypothyroidism/hyperthyroidism causing HF"],
      ["Genetic testing", "Familial dilated cardiomyopathy; ATTR amyloidosis"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));
  children.push(divider());

  // ============================================================
  // 10. TREATMENT
  // ============================================================
  children.push(heading1("10. TREATMENT"));
  children.push(para("Treatment goals: Relieve symptoms, reduce hospitalizations, prevent/reverse remodeling, prolong survival. Based on AHA/ACC/HFSA 2022 and ESC 2021 guidelines."));

  children.push(heading2("10a. General Measures (ALL HF Patients)"));
  children.push(bullet("Sodium restriction: <2 g/day in symptomatic HF"));
  children.push(bullet("Fluid restriction: 1.5-2 L/day in advanced HF with hyponatremia"));
  children.push(bullet("Daily weights: action if >2 kg gain in 2 days"));
  children.push(bullet("Exercise training: safe in stable HFrEF; improves QoL and functional capacity (HF-ACTION trial)"));
  children.push(bullet("Smoking cessation"));
  children.push(bullet("Alcohol restriction (<1-2 units/day); abstinence in alcoholic cardiomyopathy"));
  children.push(bullet("Vaccinations: annual influenza, pneumococcal (reduce HF exacerbations)"));
  children.push(bullet("Optimize comorbidities: diabetes, HTN, AF, sleep apnea, anemia, iron deficiency"));
  children.push(bullet("Avoid nephrotoxins (NSAIDs, COX-2 inhibitors), negative inotropes (most CCBs), thiazolidinediones"));

  children.push(heading2("10b. Pharmacotherapy for HFrEF (Class I Indications, 2022 Guidelines)"));
  children.push(para("The 'Fantastic Four' (Four Pillars of HFrEF therapy) - all have Class I, Level A recommendations:"));

  children.push(makeTable(
    ["Drug Class", "Agent", "Starting Dose", "Target Dose", "Mechanism / Key Points"],
    [
      ["1. ARNI\n(first-line over ACEi/ARB)", "Sacubitril-Valsartan\n(Entresto)", "49/51 mg BD", "97/103 mg BD", "Inhibits neprilysin (↑BNP/ANP) + blocks AT1 receptor. PARADIGM-HF: 20% ↓CV death/HHF vs enalapril. Start 36 hrs after last ACEi dose."],
      ["   ACEi\n(if ARNI not tolerated)", "Ramipril\nEnalapril\nLisinopril", "2.5 mg BD\n2.5 mg BD\n2.5-5 mg OD", "10 mg BD\n10-20 mg BD\n20-40 mg OD", "Inhibit ACE → ↓Ang II, aldosterone. First proven mortality benefit in HFrEF."],
      ["   ARB\n(if ACEi not tolerated - cough)", "Candesartan\nValsartan", "4-8 mg OD\n40 mg BD", "32 mg OD\n160 mg BD", "Block AT1 receptor. Use if ACEi-intolerant due to cough."],
      ["2. Beta-Blocker", "Carvedilol\nMetoprolol succinate\nBisoprolol", "3.125 mg BD\n12.5-25 mg OD\n1.25 mg OD", "25-50 mg BD\n200 mg OD\n10 mg OD", "Block SNS. ↓HR, BP, arrhythmias, reverse remodeling. Start low, titrate slow. AVOID in decompensated HF, bradycardia, severe bronchospasm."],
      ["3. MRA\n(Mineralocorticoid Receptor Antagonist)", "Spironolactone\nEplerenone", "12.5-25 mg OD\n25 mg OD", "50 mg OD\n50 mg OD", "Block aldosterone → ↓fibrosis, Na retention, K loss. RALES (spiro) & EPHESUS (eplerenone) trials. AVOID if K>5 mEq/L or creatinine >2.5 mg/dL."],
      ["4. SGLT-2 Inhibitor", "Empagliflozin\nDapagliflozin", "10 mg OD\n10 mg OD", "10 mg OD\n10 mg OD", "EMPEROR-Reduced & DAPA-HF: ↓CV death/HHF. Cardiorenal benefits. Works regardless of diabetes status. Also beneficial in HFpEF. EMPULSE: safe to initiate in hospital."],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));

  children.push(heading2("Additional HFrEF Pharmacotherapy"));
  children.push(makeTable(
    ["Drug", "Indication", "Notes"],
    [
      ["Loop Diuretics\n(Furosemide, Torasemide)", "Congestion - ALL symptomatic HF", "Symptom relief; no mortality benefit. Torasemide may be preferred (better bioavailability). Dose titrate to achieve euvolemia."],
      ["Ivabradine", "HR ≥70 bpm in sinus rhythm despite max β-blocker, LVEF ≤35%", "Reduces hospitalizations (SHIFT trial). Not for AF or symptomatic hypotension."],
      ["Hydralazine + Nitrates\n(H-ISDN)", "Black patients with HFrEF intolerant to RAAS blockade\nOR as add-on to ACEI/ARB", "A-HeFT trial: ↓mortality in Black patients. Use if ACEi/ARB contraindicated (severe renal failure)."],
      ["Digoxin", "Persistent symptoms on optimal therapy, AF with rapid ventricular rate", "Reduces hospitalizations, no mortality benefit (DIG trial). Risk of toxicity - monitor levels, electrolytes."],
      ["Soluble guanylate cyclase stimulator\n(Vericiguat)", "LVEF <45%, worsening HF despite GDMT", "VICTORIA trial: modest reduction in CV death/HHF. Class IIb."],
      ["IV Iron\n(Ferric Carboxymaltose)", "Iron deficiency (Ferritin <100 OR 100-299 + TSAT <20%)", "FAIR-HF2/IRONMAN: improves symptoms, QoL, reduces HF hospitalizations."],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));

  children.push(heading2("10c. Pharmacotherapy for HFpEF"));
  children.push(para("Historically limited evidence, but recent trials have changed practice:"));
  children.push(bullet("SGLT-2 inhibitors (Empagliflozin/Dapagliflozin): Now Class IIa for HFpEF (EMPEROR-Preserved, DELIVER trials) → reduces HHF"));
  children.push(bullet("Diuretics: For symptom relief of congestion"));
  children.push(bullet("Spironolactone: TOPCAT trial - modest benefit in Americas subgroup; currently Class IIb"));
  children.push(bullet("GLP-1 agonists (Semaglutide): STEP-HFpEF trial - improves symptoms and QoL in obese HFpEF; mortality data pending"));
  children.push(bullet("BP control: Target <130/80 mmHg"));
  children.push(bullet("AF rate/rhythm control"));
  children.push(bullet("Exercise training: Improves functional capacity and QoL"));
  children.push(bullet("Tafamidis: For ATTR cardiac amyloidosis (ATTR-ACT trial)"));

  children.push(heading2("10d. Device Therapy for HFrEF"));
  children.push(makeTable(
    ["Device", "Indication", "Evidence / Notes"],
    [
      ["ICD (Implantable Cardioverter-Defibrillator)", "LVEF ≤35% + NYHA II-III despite ≥3 months GDMT; primary prevention SCD", "SCD-HeFT, MADIT-II. Not within 40 days post-MI or 3 months after revascularization."],
      ["CRT (Cardiac Resynchronization Therapy)\nCRT-D or CRT-P", "LVEF ≤35% + LBBB + QRS ≥150 ms + NYHA II-IV\nor QRS 120-149 ms + LBBB", "COMPANION, CARE-HF. Reverse remodeling, ↑LVEF, ↓symptoms, ↓mortality."],
      ["LVAD (Left Ventricular Assist Device)", "Stage D HF as bridge-to-transplant (BTT) or destination therapy (DT)", "MOMENTUM 3: HeartMate 3 superior to HeartMate II; 2-year survival 79%."],
      ["Heart Transplantation", "End-stage HF (Stage D), no contraindications, after advanced therapy optimization", "Gold standard for end-stage HF; 1-year survival ~90%, 5-year ~75%. Limited by donor availability."],
      ["Transcatheter Mitral Valve Repair (MitraClip)", "Functional MR in HFrEF on GDMT, favorable anatomy", "COAPT trial: ↓HHF and mortality at 2 years."],
      ["CCM (Cardiac Contractility Modulation)", "LVEF 25-45%, NYHA III, not eligible for CRT", "Improves symptoms and QoL."],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));

  children.push(heading2("10e. Management of Acute Decompensated HF (ADHF)"));
  children.push(para("Key principle: Identify and address precipitating factors (non-adherence, ischemia, arrhythmia, infection, nephrotoxins)."));

  if (img4) {
    children.push(new Paragraph({
      children: [new ImageRun({ data: img4, transformation: { width: 560, height: 300 } })],
      alignment: AlignmentType.CENTER,
      spacing: { before: 120, after: 60 },
    }));
    children.push(figureCaption("FIGURE 4: Phenotypes of Acute Decompensated Heart Failure (ADHF) and Management. The Wet-Warm, Wet-Cold, Dry-Warm, and Dry-Cold profiles guide therapeutic targets. (Harrison's 22E, Fig. 265-2)"));
  }

  children.push(heading3("Pharmacological Management of ADHF"));
  children.push(makeTable(
    ["Drug Class", "Agent", "Indication"],
    [
      ["IV Loop Diuretics", "IV Furosemide (≥1.5x oral dose)", "First-line for volume overload; reassess at 6 hrs; guided by urine output"],
      ["Vasodilators", "IV Nitroglycerin, Nitroprusside, Nesiritide", "Hypertensive ADHF (Warm/Wet); reduces preload and afterload; monitor BP"],
      ["Inotropes", "Dobutamine (2-20 mcg/kg/min)\nMilrinone (0.1-0.75 mcg/kg/min)", "Low-output states (Cold/Wet or Cold/Dry); bridge to transplant/LVAD; palliative"],
      ["Vasopressors", "Norepinephrine, Vasopressin", "Cardiogenic shock with severe hypotension"],
      ["Opioids (Morphine)", "Low dose IV", "Anxiolysis, dyspnea relief; use with caution (associated with worse outcomes in registries)"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));
  children.push(bullet("Non-invasive ventilation (CPAP/BiPAP): Acute pulmonary edema, respiratory failure"));
  children.push(bullet("Pulmonary artery catheter: Resistant/refractory HF, cardiogenic shock, pre-LVAD/transplant evaluation (not routine)"));
  children.push(bullet("Early post-discharge follow-up: Within 7-14 days; reduces readmissions (STRONG-HF trial)"));
  children.push(bullet("Pre-discharge GDMT initiation: Sacubitril-valsartan (PIONEER-HF), SGLT-2i (EMPULSE) can be started before discharge"));

  children.push(heading2("10f. Advanced HF Therapies (Stage D)"));
  children.push(bullet("Continuous IV inotropic therapy (bridge or palliative)"));
  children.push(bullet("Temporary MCS: IABP, Impella, ECMO (cardiogenic shock)"));
  children.push(bullet("Durable LVAD: BTT or destination therapy"));
  children.push(bullet("Heart transplantation (gold standard)"));
  children.push(bullet("Palliative care / Hospice: End-stage disease, not candidate for advanced therapies"));

  children.push(divider());

  // ============================================================
  // 11. PREVENTION
  // ============================================================
  children.push(heading1("11. PREVENTION"));

  children.push(heading2("Primary Prevention (Stage A - Prevent HF Development)"));
  children.push(bullet("Blood pressure control: Target <130/80 mmHg (SPRINT trial: intensive BP control reduces HF incidence)"));
  children.push(bullet("Diabetes management: SGLT-2 inhibitors reduce incident HF in diabetic patients (EMPA-REG, CANVAS, DECLARE trials)"));
  children.push(bullet("Lipid management with statins: Reduce atherosclerotic CVD and subsequent ischemic cardiomyopathy"));
  children.push(bullet("Lifestyle: Weight loss, regular physical activity, dietary changes (Mediterranean diet), alcohol moderation, smoking cessation"));
  children.push(bullet("Cardioprotective strategies during chemotherapy: Cardio-oncology assessment before anthracyclines; prophylactic ACEi/BB in high-risk patients"));
  children.push(bullet("Screening and early treatment of valvular heart disease"));

  children.push(heading2("Secondary Prevention (Stage B - Prevent Symptomatic HF)"));
  children.push(bullet("ACEi/ARNI after MI (especially with reduced EF): SAVE, AIRE, TRACE trials"));
  children.push(bullet("Beta-blockers after MI"));
  children.push(bullet("SGLT-2 inhibitors in patients with asymptomatic LV dysfunction (DAPA-HF Stage B data)"));
  children.push(bullet("ICD for primary prevention in Stage B with LVEF ≤30% (MADIT-I, MUSTT)"));
  children.push(bullet("Revascularization for coronary disease with LV dysfunction (STICH trial: modest benefit in selected patients)"));
  children.push(bullet("Treatment of asymptomatic severe AS/AR before LV function deteriorates"));

  children.push(heading2("Tertiary Prevention (Stage C/D - Reduce Progression)"));
  children.push(bullet("GDMT optimization: Titrate all four pillars (ARNI, BB, MRA, SGLT-2i) to target doses"));
  children.push(bullet("Regular follow-up: Frequent visits, biomarker monitoring, medication titration"));
  children.push(bullet("Patient education: Medication adherence, daily weights, low-sodium diet, fluid restriction, symptom recognition"));
  children.push(bullet("Multidisciplinary HF programs: Reduce readmission rates by 30-50%"));
  children.push(bullet("Remote monitoring: Device-based and non-invasive hemodynamic monitoring (CardioMEMS device - pulmonary artery pressure monitoring reduces HHF by 37%)"));
  children.push(bullet("Cardiac rehabilitation: Structured exercise training for eligible HF patients"));
  children.push(divider());

  // ============================================================
  // 12. KEY GUIDELINES SUMMARY
  // ============================================================
  children.push(heading1("12. KEY GUIDELINES SUMMARY (2022 AHA/ACC/HFSA)"));
  children.push(makeTable(
    ["Stage/Type", "Class I Recommendation"],
    [
      ["All symptomatic HFrEF (LVEF ≤40%)", "ARNI (sacubitril-valsartan) or ACEi or ARB + beta-blocker + MRA + SGLT-2i"],
      ["Diuretics", "Loop diuretics for symptomatic volume overload (all HF types)"],
      ["Device: ICD", "LVEF ≤35% + NYHA II-III despite ≥3 months GDMT"],
      ["Device: CRT", "LVEF ≤35% + LBBB + QRS ≥150 ms + NYHA II-IV (ambulatory)"],
      ["ADHF - Pre-discharge", "Start or continue GDMT; early follow-up within 7-14 days"],
      ["HFpEF / HFmrEF", "SGLT-2i (empagliflozin/dapagliflozin) - Class IIa"],
      ["Iron deficiency in HFrEF", "IV ferric carboxymaltose/ferric derisomaltose if Ferritin <100 or TSAT <20%"],
      ["HFrecEF", "Continue GDMT indefinitely (discontinuation risks relapse)"],
    ]
  ));
  children.push(new Paragraph({ text: "", spacing: { before: 100, after: 100 } }));

  // ============================================================
  // 13. PROGNOSIS
  // ============================================================
  children.push(heading1("13. PROGNOSIS"));
  children.push(bullet("5-year survival: ~50% (overall), worse than many cancers"));
  children.push(bullet("Advanced HF (NYHA IV): 1-year mortality 40-50%"));
  children.push(bullet("Major causes of death: Sudden cardiac death (SCD), progressive pump failure, non-cardiovascular deaths"));
  children.push(bullet("Seattle HF Model / MAGGIC score: Validated prognostic tools"));
  children.push(bullet("Post-hospitalization: 30-day mortality 8-14%, 1-year mortality 26-37%"));
  children.push(bullet("GDMT has significantly improved prognosis: 'Fantastic Four' reduces relative mortality risk by 50-60% vs historical controls"));
  children.push(divider());

  // Footer info
  children.push(new Paragraph({
    children: [new TextRun({ text: "References: Harrison's Principles of Internal Medicine, 22nd Edition (2025) | 2022 AHA/ACC/HFSA Guideline for Management of Heart Failure | 2021 ESC Guidelines on Acute and Chronic Heart Failure | Braunwald's Heart Disease 12th Ed.", italics: true, size: 17, color: "666666", font: "Calibri" })],
    spacing: { before: 200, after: 100 },
    alignment: AlignmentType.CENTER,
  }));

  const doc = new Document({
    title: "Heart Failure - Comprehensive Clinical Notes",
    description: "Heart Failure notes based on Harrison's 22E and AHA/ACC/HFSA 2022 Guidelines",
    styles: {
      default: {
        heading1: {
          run: { font: "Calibri", size: 34, bold: true, color: "FFFFFF" },
          paragraph: { spacing: { before: 400, after: 200 }, shading: { type: ShadingType.CLEAR, fill: "1B4F8A", color: "1B4F8A" }, indent: { left: 200 } },
        },
        heading2: {
          run: { font: "Calibri", size: 28, bold: true, color: "1B4F8A" },
          paragraph: { spacing: { before: 300, after: 120 }, border: { bottom: { color: "1B4F8A", style: BorderStyle.SINGLE, size: 4 } } },
        },
        heading3: {
          run: { font: "Calibri", size: 24, bold: true, color: "2E6DA4" },
          paragraph: { spacing: { before: 200, after: 80 } },
        },
        document: {
          run: { font: "Calibri", size: 22 },
        },
      },
    },
    sections: [{ children }],
  });

  const buffer = await Packer.toBuffer(doc);
  fs.writeFileSync("/home/daytona/workspace/heart-failure-notes/Heart_Failure_Notes.docx", buffer);
  console.log("Document created successfully!");
}

buildDoc().catch(err => { console.error("Error:", err); process.exit(1); });
Running Command

cd /home/daytona/workspace/heart-failure-notes && node create_hf_notes.js 2>&1

Running Command

python3 /home/daytona/workspace/heart-failure-notes/../scripts/office/validate.p…

Running Command

python3 -c "import zipfile; z = zipfile.ZipFile('/home/daytona/workspace/heart-f…

Your comprehensive Heart Failure notes are ready:

Heart Failure Notes

Word Document · DOCX


What's Inside (Chronological Structure)

The document (32 KB, fully formatted with 4 embedded Harrison's figures) covers:
#SectionKey Content
1DefinitionAHA/ACC/HFSA 2022, ESC 2021, Universal Definition (Bozkurt 2021); Chronic vs Acute HF
2Epidemiology56.2 million global, 6.7 million US, age-prevalence data, racial disparities
3EtiologyHFrEF causes (CAD, dilated CM, toxins), HFpEF causes (HTN, obesity, amyloid), RV failure causes
4Types of HFBy EF (HFrEF/HFmrEF/HFpEF/HFrecEF), time course, laterality, hemodynamic profiles (Warm-Wet/Cold-Wet tables)
5ClassificationNYHA I-IV, AHA/ACC Stages A-D (2022), Killip classification (post-AMI)
6Risk FactorsModifiable (HTN, DM, obesity, cardiotoxins), non-modifiable; independent mortality predictors
7PathophysiologyCardiac remodeling, SNS/RAAS neurohormonal activation, natriuretic peptide system, HFpEF-specific mechanisms
8Clinical FeaturesSymptoms (left/right/low-output), physical exam (JVP, S3/S4, crackles, edema)
9InvestigationsBiomarkers (BNP/NT-proBNP cut-offs), ECG, CXR (ABCDE), Echo parameters, CPET, CMR, RHC
10TreatmentGeneral measures; "Fantastic Four" drugs for HFrEF (ARNI, BB, MRA, SGLT-2i) with doses/trials; HFpEF therapy; Device therapy (ICD/CRT/LVAD); ADHF management; Advanced HF
11PreventionPrimary (Stage A), Secondary (Stage B), Tertiary (Stage C/D)
12Guidelines Summary2022 AHA/ACC/HFSA Class I/IIa recommendations table
13Prognosis5-year survival, prognostic scores

Embedded Images (from Harrison's 22E)

  1. Universal Definition of HF flowchart (Fig. 264-1)
  2. HF Prevalence by Age bar chart (Fig. 264-2)
  3. Cardiac Remodeling Stimuli diagram (Fig. 264-6)
  4. ADHF Phenotypes and Management flowchart (Fig. 265-2)
Sources used: Harrison's Principles of Internal Medicine 22E (2025), AHA/ACC/HFSA 2022 Guidelines, ESC 2021 Guidelines, Braunwald's Heart Disease.
This is a shared conversation. Sign in to Orris to start your own chat.