Please make detailed 1000 words explanation of each page, detail of each point written in this pdf, also add diagrams and slight large font size than usually small one, also do not repeat this pdf version, only give its detail of each page according to same number page, means page 5 should explained on page 5 and so on

Reading File
Running Command

cd /tmp/workspace/attachments/e8ac0bd2-387a-4c07-901f-ed942532d77e/ && python3 -c " import pdfplumber with pdfplumber.open('Block_N_Surgery_260721_185719.pdf') as pdf: print(f'Total pages: {len(pdf.pages)}') for i, page in enumerate(pdf.pages[:5]): print(f'\n--- PAGE {i+1} ---') text = page.extract_text() print(text[:2000] if text else 'No text found') "

Running Command

python3 -c " import pdfplumber all_pages = {} with pdfplumber.open('/tmp/workspace/attachments/e8ac0bd2-387a-4c07-901f-ed942532d77e/Block_N_Surgery_260721_185719.pdf') as pdf: print(f'Total pages: {len(pdf.pages)}') for i, page in enumerate(pdf.pages): text = page.extract_text() all_pages[i+1] = text if text else '' # Save all text to file import json with open('/tmp/workspace/pdf_content.json', 'w') as f: json.dump(all_pages, f) print('Saved all page content') for pg in range(1, 51): txt = all_pages[pg] print(f'Page {pg}: {len(txt)} chars') "

Running Command

python3 -c " import json with open('/tmp/workspace/pdf_content.json') as f: pages = json.load(f) # Print all pages content for pg in range(6, 26): print(f'\n========== PAGE {pg} ==========') print(pages[str(pg)]) "

Running Command

python3 -c " import json with open('/tmp/workspace/pdf_content.json') as f: pages = json.load(f) for pg in range(26, 51): print(f'\n========== PAGE {pg} ==========') print(pages[str(pg)]) "

Running Command

mkdir -p /tmp/workspace/surgery-explained && ls /tmp/workspace/surgery-explained/

Writing File

~/surgery-explained/build_pdf.py

"""
Build a detailed explanatory PDF for Block N Surgery notes.
~1000 words per page, same page numbers as original, larger font, with diagrams.
"""

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

# ── Colour palette ────────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1a3a5c")
MED_BLUE    = colors.HexColor("#2563a8")
LIGHT_BLUE  = colors.HexColor("#dbeafe")
ACCENT      = colors.HexColor("#f97316")   # orange highlight
GREEN       = colors.HexColor("#16a34a")
LIGHT_GREEN = colors.HexColor("#dcfce7")
RED         = colors.HexColor("#dc2626")
LIGHT_RED   = colors.HexColor("#fee2e2")
YELLOW      = colors.HexColor("#fef9c3")
GREY_BG     = colors.HexColor("#f1f5f9")
WHITE       = colors.white
BLACK       = colors.black

# ── Document setup ────────────────────────────────────────────────────────────
OUTPUT = "/tmp/workspace/surgery-explained/Block_N_Surgery_EXPLAINED.pdf"
doc = SimpleDocTemplate(
    OUTPUT, pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2.2*cm, bottomMargin=2.2*cm,
    title="Block N Surgery – Detailed Explanations"
)

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

# ── Styles ────────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

def S(name, **kw):
    return ParagraphStyle(name, **kw)

BASE = 13   # base font size (slightly larger than default 10-11)

title_style   = S("DocTitle",   fontName="Helvetica-Bold",   fontSize=26, textColor=WHITE,
                   spaceAfter=6, alignment=TA_CENTER, backColor=DARK_BLUE, borderPadding=10)
cover_sub     = S("CoverSub",   fontName="Helvetica",        fontSize=14, textColor=LIGHT_BLUE,
                   spaceAfter=4, alignment=TA_CENTER)
pg_header     = S("PgHeader",   fontName="Helvetica-Bold",   fontSize=18, textColor=WHITE,
                   backColor=DARK_BLUE, borderPadding=(6,8,6,8), spaceAfter=8, leading=22)
section_hdr   = S("SecHdr",     fontName="Helvetica-Bold",   fontSize=16, textColor=DARK_BLUE,
                   spaceAfter=4, spaceBefore=10, borderPadding=(4,0,4,0))
sub_hdr       = S("SubHdr",     fontName="Helvetica-Bold",   fontSize=14, textColor=MED_BLUE,
                   spaceAfter=3, spaceBefore=6)
body          = S("Body",       fontName="Helvetica",        fontSize=BASE, leading=20,
                   spaceAfter=5, alignment=TA_JUSTIFY)
bullet        = S("Bullet",     fontName="Helvetica",        fontSize=BASE, leading=20,
                   leftIndent=18, spaceAfter=3, bulletIndent=4)
bold_body     = S("BoldBody",   fontName="Helvetica-Bold",   fontSize=BASE, leading=20, spaceAfter=3)
highlight_box = S("HLBox",      fontName="Helvetica",        fontSize=BASE, leading=20,
                   backColor=YELLOW, borderPadding=8, spaceAfter=6)
kmu_box       = S("KMUBox",     fontName="Helvetica-BoldOblique", fontSize=BASE, leading=20,
                   textColor=RED, backColor=LIGHT_RED, borderPadding=6, spaceAfter=6)
green_box     = S("GreenBox",   fontName="Helvetica",        fontSize=BASE, leading=20,
                   backColor=LIGHT_GREEN, borderPadding=8, spaceAfter=6)
blue_box      = S("BlueBox",    fontName="Helvetica",        fontSize=BASE, leading=20,
                   backColor=LIGHT_BLUE, borderPadding=8, spaceAfter=6)
page_num_st   = S("PageNum",    fontName="Helvetica",        fontSize=11, textColor=MED_BLUE,
                   alignment=TA_RIGHT, spaceAfter=2)
diagram_cap   = S("DiagCap",    fontName="Helvetica-Oblique",fontSize=11, textColor=colors.grey,
                   alignment=TA_CENTER, spaceAfter=6)

# ── Helper functions ──────────────────────────────────────────────────────────
def page_tag(n):
    return [Paragraph(f"— Page {n} of 50 —", page_num_st)]

def h1(txt):
    return Paragraph(f"<b>{txt}</b>", pg_header)

def h2(txt):
    return Paragraph(f"<b>{txt}</b>", section_hdr)

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

def p(txt):
    return Paragraph(txt, body)

def pb(txt):
    return Paragraph(f"<b>{txt}</b>", bold_body)

def bl(items, symbol="•"):
    return [Paragraph(f"{symbol}  {it}", bullet) for it in items]

def kmu(txt):
    return Paragraph(f"🔥 <b>KMU High-Yield:</b>  {txt}", kmu_box)

def tip(txt):
    return Paragraph(f"💡 <b>Key Concept:</b>  {txt}", highlight_box)

def note(txt):
    return Paragraph(f"📝 <b>Note:</b>  {txt}", green_box)

def info(txt):
    return Paragraph(f"ℹ️  {txt}", blue_box)

def rule():
    return HRFlowable(width="100%", thickness=1, color=MED_BLUE, spaceAfter=6, spaceBefore=4)

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

# ── Simple box-diagram helpers ────────────────────────────────────────────────
def make_flow_table(rows, col_colors=None, col_widths=None):
    """rows = list of lists of strings; returns a Table"""
    if col_widths is None:
        col_widths = [W / len(rows[0])] * len(rows[0])
    ts = TableStyle([
        ('BACKGROUND', (0,0), (-1,0), DARK_BLUE),
        ('TEXTCOLOR',  (0,0), (-1,0), WHITE),
        ('FONTNAME',   (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE',   (0,0), (-1,-1), 12),
        ('ALIGN',      (0,0), (-1,-1), 'CENTER'),
        ('VALIGN',     (0,0), (-1,-1), 'MIDDLE'),
        ('ROWBACKGROUNDS', (0,1), (-1,-1), [LIGHT_BLUE, WHITE]),
        ('GRID',       (0,0), (-1,-1), 0.5, MED_BLUE),
        ('TOPPADDING', (0,0), (-1,-1), 7),
        ('BOTTOMPADDING',(0,0),(-1,-1), 7),
        ('LEFTPADDING', (0,0), (-1,-1), 6),
    ])
    t = Table(rows, colWidths=col_widths, repeatRows=1)
    t.setStyle(ts)
    return t

def make_two_col(left_items, right_items, left_title="", right_title="",
                 lbg=LIGHT_BLUE, rbg=LIGHT_GREEN):
    """Two-column comparison box"""
    def cell_paras(title, items, bg):
        inner = []
        if title:
            inner.append(Paragraph(f"<b>{title}</b>", sub_hdr))
        for it in items:
            inner.append(Paragraph(f"• {it}", bullet))
        return inner
    data = [[cell_paras(left_title, left_items, lbg),
             cell_paras(right_title, right_items, rbg)]]
    ts = TableStyle([
        ('VALIGN',     (0,0),(-1,-1),'TOP'),
        ('BACKGROUND', (0,0),(0,0), lbg),
        ('BACKGROUND', (1,0),(1,0), rbg),
        ('BOX',        (0,0),(-1,-1), 1, MED_BLUE),
        ('INNERGRID',  (0,0),(-1,-1), 0.5, MED_BLUE),
        ('TOPPADDING', (0,0),(-1,-1), 8),
        ('LEFTPADDING',(0,0),(-1,-1), 8),
    ])
    t = Table(data, colWidths=[W*0.5-2, W*0.5-2])
    t.setStyle(ts)
    return t

def phase_diagram(phases, colors_list=None):
    """Horizontal phase flow diagram"""
    if colors_list is None:
        colors_list = [DARK_BLUE, MED_BLUE, GREEN]
    n = len(phases)
    cw = W / n
    rows = [phases]
    data = [phases]
    ts = TableStyle([
        ('FONTNAME',    (0,0),(-1,-1),'Helvetica-Bold'),
        ('FONTSIZE',    (0,0),(-1,-1), 12),
        ('ALIGN',       (0,0),(-1,-1),'CENTER'),
        ('VALIGN',      (0,0),(-1,-1),'MIDDLE'),
        ('TOPPADDING',  (0,0),(-1,-1), 12),
        ('BOTTOMPADDING',(0,0),(-1,-1),12),
        ('TEXTCOLOR',   (0,0),(-1,-1), WHITE),
    ])
    for i in range(n):
        c = colors_list[i % len(colors_list)]
        ts.add('BACKGROUND', (i,0),(i,0), c)
    t = Table(data, colWidths=[cw]*n)
    t.setStyle(ts)
    return t

# ──────────────────────────────────────────────────────────────────────────────
# PAGE CONTENT
# ──────────────────────────────────────────────────────────────────────────────
story = []

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 1 – COVER
# ═══════════════════════════════════════════════════════════════════════════════
story += [
    sp(60),
    Paragraph("HIGH-YIELD CLINICAL NOTES", title_style),
    sp(10),
    Paragraph("SURGERY – BLOCK N", title_style),
    sp(20),
    Paragraph("Detailed Explanatory Guide", cover_sub),
    Paragraph("Final Year MBBS · KMU Exam Preparation", cover_sub),
    sp(10),
    rule(),
    sp(10),
    Paragraph("This document provides a <b>~1000-word page-by-page expansion</b> of every topic covered in the "
              "Block N Surgery notes, with explanatory diagrams, clinical context, and exam-focused highlights. "
              "Each explanation page corresponds to the same page number as the original PDF.", body),
    sp(10),
    Paragraph("<b>Sections Covered:</b>", bold_body),
] + bl([
    "Part I  – General Surgery & Foundation-III (Perioperative Care)",
    "Part II – Musculoskeletal-III (ERAS & Perioperative Pain Management)",
    "Part III – Plastic Surgery & Burns",
]) + [
    sp(20),
    Paragraph("Made by Haroon  |  Expanded & Illustrated Edition", cover_sub),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 2 – Table of Contents explanation
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(2) + [
    h1("PAGE 2 – INTRODUCTION & TABLE OF CONTENTS"),
    sp(4),
    h2("Understanding This Document and Its Structure"),
    p("These notes are a <b>High-Yield Clinical Consolidation for Surgery Block N</b>, specifically tailored to Final "
      "Year MBBS students preparing for KMU (Khyber Medical University) professional examinations. The content "
      "synthesizes three major subject areas: <b>General Surgery</b>, <b>Plastic Surgery (Burns)</b>, and "
      "<b>Surgical Foundation</b>, which together contribute <b>15 MCQs</b> out of the 120-MCQ total paper."),
    sp(4),
    h3("KMU Paper Blueprint for Surgery Block N"),
    make_flow_table([
        ["Foundation Topic", "MCQs Allocated"],
        ["Foundation-III (Patient Safety, Consent, Incisions & Perioperative Care)", "10"],
        ["Musculoskeletal-III (Plastic Surgery, Burns & ERAS)", "5"],
        ["Block N Total", "15"],
    ], col_widths=[W*0.75, W*0.25]),
    sp(8),
    p("Understanding the blueprint is the first step in smart exam preparation. With only 15 MCQs from this entire "
      "block, you should focus on the <b>highest-yield facts</b> — those tagged with 🔥 symbols throughout the "
      "document. These are directly sourced from past KMU, KMC, AMC, GMC, WMC, RMC, and NWSM papers from "
      "2023–2025."),
    sp(6),
    h3("How to Use These Notes"),
    p("The document is divided into <b>three parts</b> and <b>fourteen sections</b>. Each section corresponds to a "
      "KMU Learning Outcome (LO), which is the official exam specification. The notes are structured from most "
      "frequently tested (Section 1 – Patient Safety) to more specialized (Section 14 – Burn Complications)."),
    sp(6),
    p("The <b>Table of Contents</b> maps directly to:</p>"),
] + bl([
    "<b>Part I:</b> General Surgery and Perioperative Care (Sections 1–8) — 10 MCQs",
    "<b>Part II:</b> ERAS and Pain Management (Sections 9–10) — tested within Part I allocation",
    "<b>Part III:</b> Plastic Surgery and Burns (Sections 11–14) — 5 MCQs",
]) + [
    sp(6),
    tip("Every section begins with the specific KMU Learning Outcome (LO number) it addresses. This lets you "
        "cross-check your preparation against the official syllabus."),
    sp(6),
    p("The notes are synthesized from <b>General Surgery textbooks</b>, <b>Past KMU Papers (2023–2025)</b>, and "
      "<b>Pre-Professional Questions</b>. Important exam answers are marked with 🔥 and tagged with the source "
      "institution and year (e.g., [KMU - 2024], [KMC - 2024])."),
    sp(6),
    h3("Why This Format Works"),
    p("Rather than reading entire textbook chapters, these notes condense the most testable information into "
      "memorable, exam-ready bullet points. Each 'Top MCQ Pointer' section at the end of major segments "
      "functions like a rapid review checklist — re-reading these pointers in the final days before the exam "
      "dramatically improves recall of high-yield facts."),
    kmu("Block N Surgery contributes exactly 15 MCQs to the 120-question KMU paper. This document covers all "
        "testable LOs for that allocation."),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 3 – Section 1: WHO Checklist & Patient Safety
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(3) + [
    h1("PAGE 3 – SECTION 1: PATIENT SAFETY & WHO SURGICAL SAFETY CHECKLIST"),
    sp(4),
    h2("1. WHO Surgical Safety Checklist"),
    p("The <b>WHO Surgical Safety Checklist</b> was introduced globally in 2008 as part of the 'Safe Surgery Saves "
      "Lives' initiative. It is a standardized tool used in operating theatres worldwide to reduce preventable "
      "perioperative errors, improve communication, and enhance teamwork. Its implementation has been shown to "
      "reduce in-hospital complications and mortality by up to 47% in some studies."),
    sp(4),
    p("The checklist is applied by the <b>entire surgical team</b> — surgeons, anaesthetists, and nurses — and is "
      "not the responsibility of any single individual. Its primary purpose, which is frequently tested in KMU "
      "exams, is to <b>improve communication and teamwork</b> within the operating theatre."),
    sp(6),
    h3("Three Phases of the WHO Checklist"),
    phase_diagram(["SIGN IN\n(Before Anaesthesia)", "TIME OUT\n(Before Incision)", "SIGN OUT\n(Before Patient Leaves OR)"],
                  [DARK_BLUE, MED_BLUE, GREEN]),
    sp(6),
] + bl([
    "<b>Sign In (Before Anaesthesia Induction):</b> The anaesthesia team verifies patient identity, "
      "confirms allergies, confirms anaesthesia machine is checked, and assesses airway/aspiration risk. "
      "The patient has not yet been anaesthetized at this point.",
    "<b>Time Out (Between Anaesthesia Induction and Skin Incision):</b> The ENTIRE team pauses. They verbally "
      "confirm patient identity, the operative site (with marking confirmed), the planned procedure, and "
      "anticipated critical steps. Antibiotics and imaging are confirmed. This is the most tested phase.",
    "<b>Sign Out (Before Patient Leaves OR):</b> The scrub nurse confirms the procedure performed, instrument "
      "and sponge counts are complete, specimens are labelled, and any equipment problems are noted.",
]) + [
    sp(6),
    kmu("The primary purpose of the WHO checklist is to improve COMMUNICATION and TEAMWORK. [KMC - 2024]"),
    kmu("The TIME OUT phase occurs between anaesthesia induction and the first skin incision. [AMC - 2024]"),
    sp(4),
    h2("2. Patient Safety and Error Prevention"),
    p("Patient safety refers to the prevention of harm to patients during healthcare delivery. Medication errors, "
      "wrong-site surgery, and patient misidentification are among the most common and preventable adverse events "
      "in surgical practice. Recognizing and reporting these errors is a shared institutional responsibility."),
    sp(4),
    h3("Hierarchy of Patient Safety Responsibility"),
    make_flow_table([
        ["Level", "Role", "Responsibility"],
        ["Frontline", "Bedside nurses, junior doctors", "Identify & report incidents at point of care"],
        ["Clinical Management", "Senior clinicians, consultants", "Review & implement corrective policies"],
        ["Executive", "Hospital administrators, board", "Build a culture of safety, resource allocation"],
    ], col_widths=[W*0.18, W*0.37, W*0.45]),
    sp(6),
    p("The single most important step in preventing <b>medication errors</b> is to <b>double-check the patient's "
      "identification bracelet</b> before any medication administration or invasive procedure. This simple step "
      "prevents the majority of wrong-patient errors."),
    kmu("Patient safety reporting is the shared responsibility of front-line caregivers, clinical managers, AND "
        "facility executives — not just one group. [KMU - 2024]"),
    kmu("The most important step to prevent medication errors: check the patient ID bracelet TWICE. [KMC - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 4 – Informed Consent
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(4) + [
    h1("PAGE 4 – PRINCIPLES OF INFORMED CONSENT"),
    sp(4),
    h2("What is Informed Consent?"),
    p("Informed consent is not simply a signature on a form — it is a <b>dynamic communication process</b> "
      "between a clinician and patient, through which the patient is given sufficient information to make a "
      "voluntary, informed decision about their care. It is the legal and ethical cornerstone of patient "
      "autonomy in surgical practice."),
    sp(4),
    h3("Who Is Responsible for Obtaining Consent?"),
    p("The <b>operating surgeon</b> — the person who will actually perform the procedure — bears the direct "
      "legal and ethical responsibility to obtain informed consent. They cannot delegate this duty to a junior "
      "colleague who is not performing the operation, as they are the only person with full knowledge of the "
      "technical risks involved."),
    sp(4),
    p("The operating surgeon must personally explain:"),
] + bl([
    "The <b>diagnosis</b> and why surgery is recommended",
    "The <b>nature and technique</b> of the proposed procedure",
    "The <b>expected benefits</b> of the operation",
    "The <b>material risks and complications</b> (both common and serious)",
    "<b>Alternative treatment options</b> (including non-surgical management)",
    "What will happen if the patient chooses <b>not to have surgery</b>",
    "Answers to any patient questions",
]) + [
    sp(6),
    h3("Ethical Basis of Informed Consent"),
    info("The fundamental ethical principle underpinning informed consent is <b>Respect for Patient Autonomy "
         "and Self-Determination</b> — the right of a competent adult to make decisions about their own body."),
    kmu("The ethical basis of consent = Respect for patient autonomy [AMC - 2024]"),
    sp(4),
    h3("Specific Disclosures — Laparoscopic Conversion"),
    p("If there is a possibility that a planned laparoscopic procedure may need conversion to open surgery, "
      "this <b>must be discussed and documented before the operation</b>. For example: a patient consenting for "
      "laparoscopic cholecystectomy must be informed of the possibility of conversion to open cholecystectomy "
      "in case of bleeding, anatomical difficulty, or bile duct injury."),
    sp(4),
    h3("Sensitive Examinations"),
    p("Examinations of sensitive body regions — such as breast, genitalia, or rectum — require:"),
] + bl([
    "Explicit <b>verbal consent</b> from the patient before beginning the examination",
    "Presence of a <b>female chaperone</b> when a male clinician examines a female patient",
    "Documentation in the clinical record",
]) + [
    sp(6),
    h3("Emergency Exception — Implied Consent"),
    make_two_col(
        ["Patient is unconscious or incapacitated",
         "No legal surrogate decision-maker available",
         "Immediate threat to life or limb",
         "Life-saving surgery cannot be delayed"],
        ["Consent is legally IMPLIED by the emergency",
         "Surgeon proceeds without explicit consent",
         "Document the reasoning clearly in notes",
         "Notify family as soon as possible post-op"],
        "Conditions for Implied Consent", "Legal Basis & Action",
        LIGHT_RED, LIGHT_GREEN
    ),
    sp(4),
    kmu("Implied consent applies in TRUE emergencies — unconscious patient, life-threatening situation, no "
        "surrogate available. [KMC - 2024]"),
    kmu("Chaperone is MANDATORY for sensitive exams (e.g., breast examination). [NWSM - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 5 – Langer's Lines & Incision Principles
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(5) + [
    h1("PAGE 5 – SECTION 2: PRINCIPLES OF SKIN INCISIONS"),
    sp(4),
    h2("1. Langer's Lines (Cleavage Lines)"),
    p("Langer's lines, also known as <b>skin tension lines</b> or <b>cleavage lines</b>, are topographical lines "
      "on the surface of the skin that represent the principal direction of orientation of the <b>collagen "
      "fibers in the dermis</b>. They were first described by the Austrian anatomist Karl Langer in 1861."),
    sp(4),
    p("These lines are clinically significant because the collagen fibers run in specific directions depending "
      "on the underlying muscle forces and habitual skin movements. On the face, they tend to run horizontally "
      "(perpendicular to the underlying facial muscles). On the trunk, they have predictable orientations."),
    sp(6),
    h3("Surgical Relevance of Langer's Lines"),
    make_two_col(
        ["Incision parallel to Langer's lines",
         "Collagen fibers are not disrupted transversely",
         "Wound edges not pulled apart by muscle forces",
         "Result: NARROW, flat, cosmetically superior scar",
         "Preferred for all elective skin incisions"],
        ["Incision perpendicular to Langer's lines",
         "Collagen fibers are cut across their orientation",
         "Muscle forces pull the wound edges apart",
         "Result: WIDE, hypertrophic, unsightly scar",
         "Unavoidable in some emergency/anatomical cases"],
        "✅ Parallel to Langer's Lines", "❌ Perpendicular to Langer's Lines",
        LIGHT_GREEN, LIGHT_RED
    ),
    sp(6),
    kmu("Incisions PARALLEL to Langer's lines heal with minimal scarring (narrow, cosmetically superior). "
        "Perpendicular incisions produce wide, hypertrophic scars. [KMU - 2024]"),
    sp(6),
    h2("General Principles of Incision Planning"),
    p("Every surgical incision requires careful planning that balances four competing goals: adequate surgical "
      "access, extensibility for unexpected findings, preservation of neurovascular structures, and optimal "
      "healing. No single incision is perfect — the choice is always a clinical compromise."),
    sp(4),
] + bl([
    "<b>Adequate Exposure:</b> The incision must give direct, safe visualization of the target organ. An "
      "incision that is too small forces dangerous 'blind' dissection and increases the risk of inadvertent "
      "organ or vessel injury.",
    "<b>Extensibility:</b> Intraoperative findings may require greater access than anticipated (e.g., unexpected "
      "adhesions, bleeding, or tumor extension). The incision must be designed to allow safe extension without "
      "compromising blood supply or creating new problems.",
    "<b>Nerve and Vessel Preservation:</b> Incisions should run parallel to major nerves and blood vessels "
      "wherever anatomically possible. Cutting a motor nerve leads to permanent muscle denervation and atrophy; "
      "cutting a major vessel causes hemorrhage.",
    "<b>Muscle-Splitting vs. Muscle-Cutting:</b> Muscle-splitting techniques (separating muscle fibers along "
      "their natural axis without cutting them) are strongly preferred over muscle-cutting. Splitting preserves "
      "the muscle's tensile strength and blood supply, reducing postoperative pain and herniation risk. "
      "Examples: McBurney's Gridiron incision for appendectomy (muscle-splitting).",
]) + [
    sp(4),
    tip("Muscle-SPLITTING (along fiber axes) = strong closure, low hernia risk. "
        "Muscle-CUTTING = more pain, higher hernia risk."),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 6 – Abdominal Incision Types
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(6) + [
    h1("PAGE 6 – TYPES OF ABDOMINAL INCISIONS (CONTINUED)"),
    sp(4),
    h2("2. Abdominal Incisions — Detailed Overview"),
    p("The choice of abdominal incision depends on the urgency of the procedure, the specific organ being "
      "operated upon, the patient's build and prior scars, and the anticipated intraoperative requirements. "
      "Each incision has a distinct anatomical basis, advantage profile, and risk pattern."),
    sp(6),
    h3("Anatomical Overview of the Anterior Abdominal Wall"),
    p("The anterior abdominal wall is composed of (from superficial to deep): skin → subcutaneous fat → "
      "three layers of flat muscles (external oblique, internal oblique, transversus abdominis) → "
      "<b>transversalis fascia</b> → extraperitoneal fat → <b>peritoneum</b>. The midline contains the "
      "<b>linea alba</b> — a relatively avascular fibrous raphe formed by fusion of the aponeuroses of all "
      "three flat muscles."),
    sp(6),
    h3("Key Abdominal Incisions"),
    make_flow_table([
        ["Incision", "Direction & Anatomy", "Primary Indication", "Key Feature"],
        ["Midline\n(Laparotomy)", "Vertical; along linea alba", "Emergency / Trauma / Exploration",
         "Fastest; highest hernia risk 🔥"],
        ["Paramedian", "Vertical; 2–5 cm lateral to midline", "Cholecystectomy / Splenectomy",
         "Rectus muscle retracts laterally; shutter effect"],
        ["Kocher's\n(Subcostal)", "Oblique; below costal margin", "Biliary surgery / Liver resection",
         "Muscle-cutting; painful; good upper access"],
        ["Gridiron\n(McBurney's)", "Oblique at McBurney's point, RIF", "Open appendectomy",
         "Muscle-SPLITTING; low hernia risk"],
        ["Lanz", "Transverse, RIF", "Appendectomy", "Cosmetically superior; follows Langer's lines"],
        ["Pfannenstiel", "Transverse curved, suprapubic", "C-Section / Gynaecological surgery",
         "Cosmetically hidden; very strong; low hernia"],
    ], col_widths=[W*0.15, W*0.25, W*0.25, W*0.35]),
    sp(8),
    h3("Detailed Notes on Individual Incisions"),
] + bl([
    "<b>Midline (Laparotomy):</b> Cuts through the linea alba only — no muscle is cut, making it fast "
      "(under 2 minutes from skin to peritoneum). However, the linea alba has a poor blood supply, making "
      "it prone to ischaemic wound failure, resulting in the <b>highest rate of incisional hernia</b> of all "
      "abdominal incisions (up to 15–20%).",
    "<b>Kocher's (Subcostal):</b> Named after the Swiss surgeon Emil Theodor Kocher. On the right it provides "
      "excellent access to the gallbladder and bile ducts. On the left (reverse Kocher) it accesses the "
      "spleen. It cuts the rectus abdominis and the anterior rectus sheath, causing significant postoperative "
      "pain and risk of intercostal nerve damage.",
    "<b>Gridiron (McBurney's):</b> The McBurney's point is located 1/3 of the way from the anterior superior "
      "iliac spine (ASIS) to the umbilicus — this is the surface marking of the base of the appendix. The "
      "muscle fibers of external oblique, internal oblique, and transversus abdominis are split (not cut) in "
      "the direction of their fibers, producing a very strong, self-healing closure.",
    "<b>Pfannenstiel:</b> The curved transverse incision 2–3 cm above the pubic symphysis is placed in a "
      "natural skin crease and hidden by underwear. The fascia is cut transversely but the rectus muscles are "
      "separated in the midline vertically, giving vertical access to the pelvis while providing a "
      "cosmetically excellent horizontal scar.",
]) + [
    kmu("Midline incision = fastest access, highest hernia risk. [KMU - 2024]"),
    kmu("Gridiron/McBurney's = muscle-SPLITTING = very low hernia rate. Used for appendectomy."),
    PageBreak(),
]

print("Pages 1-6 written to story")
print(f"Story length so far: {len(story)} elements")
Writing File

~/surgery-explained/build_pdf_part2.py

"""
Continuation: Pages 7-50 content for the surgery PDF
Run AFTER build_pdf.py has defined all styles/helpers and the initial story list.
"""

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 7 – Surgical Positions + Summary table
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(7) + [
    h1("PAGE 7 – ABDOMINAL INCISION SUMMARY & SURGICAL POSITIONS"),
    sp(4),
    h2("Summary: Choosing the Right Incision"),
    p("The selection of a surgical incision is one of the first and most critical decisions a surgeon makes. "
      "Factors considered include: urgency (emergency vs. elective), target organ location, anticipated "
      "difficulty, patient body habitus, previous scars (which alter blood supply and increase adhesion risk), "
      "and cosmetic requirements of the patient."),
    sp(4),
    tip("Emergency surgery almost always uses the MIDLINE incision because speed is paramount and cosmesis "
        "is secondary. Elective operations use the most anatomically appropriate and cosmetically favourable "
        "approach."),
    sp(6),
    h2("3. Surgical Patient Positioning"),
    p("Patient positioning in the operating theatre serves multiple functions: it optimizes the surgeon's "
      "access and visibility, ensures safe anaesthetic management, and must protect the patient from "
      "pressure-related injuries to nerves, skin, and bony prominences throughout the procedure."),
    sp(4),
    p("Improper positioning can cause serious complications including <b>peripheral nerve palsies</b> "
      "(e.g., common peroneal nerve compression in lithotomy), <b>brachial plexus injuries</b> (arm "
      "abducted >90°), <b>pressure sores</b>, <b>compartment syndrome</b> (legs in lithotomy >2 hours), "
      "and <b>air embolism</b> (beach chair position with head elevation)."),
    sp(6),
    h3("Key Surgical Positions and Their Indications"),
    make_flow_table([
        ["Position", "Key Feature", "Operations Performed"],
        ["Rose's Position", "Neck hyperextension", "Thyroidectomy, parathyroidectomy, laryngoscopy"],
        ["Supine (Standard)", "Lying flat on back", "Laparotomy, hernia repair, vascular surgery"],
        ["Lithotomy", "Legs raised & abducted in stirrups", "Pelvic surgery, cystoscopy, vaginal procedures"],
        ["Lateral Decubitus", "Lying on one side", "Nephrectomy, splenectomy, thoracotomy"],
        ["Prone", "Face down", "Posterior spine surgery, pilonidal sinus"],
        ["Beach Chair (Semi-sitting)", "Head-up, semi-reclined", "Shoulder arthroscopy, ENT procedures"],
        ["Trendelenburg", "Head-down tilt 15–30°", "Pelvic laparoscopy (improves bowel retraction)"],
        ["Reverse Trendelenburg", "Head-up tilt", "Upper abdominal laparoscopy (cholecystectomy)"],
    ], col_widths=[W*0.22, W*0.28, W*0.50]),
    sp(8),
    h3("Rose's Position — Detailed"),
    p("Rose's position is defined by <b>maximum hyperextension of the neck</b>, achieved by placing a "
      "sandbag or shoulder roll beneath the shoulders and allowing the head to fall back with the neck "
      "fully extended. A head ring stabilizes the occiput."),
] + bl([
    "<b>Indication:</b> Thyroidectomy — hyperextension exposes the entire anterior neck from the sternal notch "
      "to the chin, allowing full access to the thyroid gland, parathyroid glands, and recurrent laryngeal "
      "nerves.",
    "<b>Benefits:</b> Tenses the skin of the anterior neck, making the trachea and thyroid cartilage more "
      "superficial and easier to palpate and dissect.",
    "<b>Risk:</b> Excessive hyperextension can cause cervical spine injury in patients with pre-existing "
      "cervical spondylosis or rheumatoid arthritis — always check neck movements preoperatively.",
]) + [
    sp(4),
    kmu("Rose's Position = Neck HYPEREXTENSION, used for THYROIDECTOMY. [GKMC - 2024]"),
    sp(4),
    h3("Pressure Area Protection"),
    p("Regardless of position, all bony prominences must be padded with gel pads or foam: heels, sacrum, "
      "occiput, elbows, and lateral knee. Eyes must be taped shut under anaesthesia to prevent corneal "
      "abrasion from surgical drapes. Arms should not be abducted beyond 90° to prevent brachial plexus "
      "stretch injury."),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 8 – Section 3: Wound Healing
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(8) + [
    h1("PAGE 8 – SECTION 3: WOUND CLOSURE, HEALING, AND DIATHERMY"),
    sp(4),
    h2("1. Principles of Wound Healing"),
    p("Wound healing is one of the most complex biological processes in human physiology, involving a "
      "precisely coordinated sequence of cellular events, growth factor releases, and matrix remodelling. "
      "The three principal pathways of healing are classified by how the wound is managed clinically."),
    sp(6),
    phase_diagram(
        ["PRIMARY INTENTION\n(Clean, closed wound)", "SECONDARY INTENTION\n(Open, granulating wound)",
         "TERTIARY INTENTION\n(Delayed primary closure)"],
        [DARK_BLUE, RED, MED_BLUE]
    ),
    sp(8),
    h3("Primary Intention"),
    p("Occurs when a <b>clean wound with minimal tissue loss</b> is surgically closed, bringing the edges "
      "into direct apposition with sutures, staples, or skin glue. Examples include a clean excision biopsy "
      "closed with Prolene sutures, or a surgical incision from an elective operation."),
] + bl([
    "Minimal contamination and dead space",
    "Healing occurs by direct fibrous union — very little granulation tissue needed",
    "Results in a thin, neat scar",
    "Best cosmetic and functional outcome",
]) + [
    sp(4),
    h3("Secondary Intention"),
    p("Occurs when a wound has <b>significant tissue loss, contamination, or infection</b> and cannot be "
      "primarily closed. The wound is left open and heals by <b>granulation tissue formation</b> (capillary "
      "ingrowth from the wound edges), <b>wound contraction</b> (myofibroblasts pull the edges together), "
      "and <b>re-epithelialization</b> (keratinocytes migrate from the wound margins). Examples: diabetic "
      "foot ulcers, large infected wounds, pilonidal abscess left open after drainage."),
] + bl([
    "Slower healing process (days to weeks)",
    "More granulation tissue and contraction",
    "Results in a wider, less aesthetic scar",
    "Higher risk of scar contracture",
]) + [
    sp(4),
    h3("Tertiary Intention (Delayed Primary Closure)"),
    p("A hybrid strategy used for <b>contaminated wounds</b> that cannot be primarily closed due to infection "
      "risk but that are eventually clean enough to close surgically. Classic example: In a <b>Hartmann's "
      "procedure</b> for a perforated sigmoid colon, the deep fascia is closed but the skin and subcutaneous "
      "tissue are left open, managed with dressings over several days, and then surgically closed once "
      "active infection has resolved."),
    kmu("Delayed primary closure = Tertiary intention. Fascia closed immediately; skin/subcutaneous left open "
        "and closed later. [GMC - 2024]"),
    sp(4),
    h3("Cellular Dynamics of Wound Healing"),
    make_flow_table([
        ["Time Post-Injury", "Dominant Cell Type", "Primary Function"],
        ["0–48 hours", "Neutrophils (PMNs)", "Phagocytosis of bacteria; débridement"],
        ["Day 2 onwards", "Macrophages", "Débridement; release of growth factors for repair"],
        ["Day 4–14", "Fibroblasts", "Collagen synthesis and matrix production"],
        ["Weeks–months", "Myofibroblasts", "Wound contraction"],
    ], col_widths=[W*0.25, W*0.35, W*0.40]),
    sp(4),
    kmu("By Day 2, MACROPHAGES become the predominant cell type in a healing closed wound (replacing "
        "neutrophils). [KMC - 2024]"),
    kmu("LOCAL TISSUE INFECTION is the most common LOCAL cause of impaired wound healing. [RMC - 2025]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 9 – Sutures, Drains, Clavien-Dindo
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(9) + [
    h1("PAGE 9 – SUTURES, DRAIN MANAGEMENT & POSTOPERATIVE COMPLICATIONS GRADING"),
    sp(4),
    h2("2. Surgical Suture Techniques and Materials"),
    p("Suture selection is critical to wound healing outcomes. A suture must match the tissue being repaired "
      "in terms of tensile strength, handling properties, and the duration of support needed. Sutures are "
      "classified as <b>absorbable</b> or <b>non-absorbable</b>, and as <b>natural</b> or <b>synthetic</b>."),
    sp(4),
    make_flow_table([
        ["Suture", "Type", "Absorption", "Primary Use"],
        ["Vicryl (Polyglactin 910)", "Synthetic absorbable", "60–90 days (hydrolysis)", "Fascial closure, peritoneum, bowel"],
        ["Catgut (plain)", "Natural absorbable", "10–14 days (enzymatic)", "Mucosal layers (less common now)"],
        ["PDS (Polydioxanone)", "Synthetic absorbable", "180+ days", "Fascial closure, long support needed"],
        ["Prolene (Polypropylene)", "Synthetic non-absorbable", "Permanent", "Vascular, skin (cosmetic)"],
        ["Nylon (Ethilon)", "Synthetic non-absorbable", "Very slow degradation", "Skin closure, ophthalmic"],
        ["Silk", "Natural non-absorbable", "Slowly absorbed over years", "Ties, securing drains"],
    ], col_widths=[W*0.27, W*0.22, W*0.22, W*0.29]),
    sp(6),
    h3("Vicryl — The Most Tested Suture Material"),
    p("Vicryl (Polyglactin 910) is a <b>braided, synthetic, absorbable suture</b> that degrades by "
      "<b>hydrolysis</b> (absorption of water that breaks the polymer chains). It is completely absorbed "
      "within <b>60–90 days</b>. It maintains approximately 75% of its tensile strength at 2 weeks and "
      "50% at 3 weeks. It is the most widely used suture in abdominal surgery."),
    kmu("Vicryl = synthetic ABSORBABLE suture; degraded by HYDROLYSIS; absorbed in 60–90 days. [GKMC - 2024]"),
    sp(6),
    h3("Vertical Mattress Suture"),
    p("The vertical mattress suture is a full-thickness suture technique that provides two important benefits: "
      "(1) <b>excellent tension distribution</b> across the wound (reducing the risk of wound dehiscence in "
      "high-tension closures), and (2) <b>wound edge eversion</b> (the edges are turned outward, which is "
      "critical for optimal scar formation as inverted wound edges heal with a depressed, aesthetically poor "
      "scar). It is the technique of choice for laparotomy closure in obese patients."),
    kmu("Vertical Mattress Suture = best for laparotomy in OBESE patients — provides wound edge EVERSION and "
        "tension distribution. [KMC - 2024]"),
    sp(4),
    h2("3. Surgical Drain Management"),
    p("Surgical drains serve to evacuate fluid (blood, bile, serous fluid, lymph) from a dead space and "
      "provide early warning of complications (e.g., bile leak, anastomotic dehiscence). However, all drains "
      "act as <b>retrograde infection conduits</b> if left too long."),
] + bl([
    "<b>Redivac (closed suction drain):</b> Removed after 24 hours in uncomplicated elective procedures once "
      "output is minimal (<30 mL/day).",
    "<b>Corrugated drain:</b> Open passive drain, used in contaminated fields.",
    "<b>T-tube:</b> Placed in the common bile duct after exploration to decompress and allow cholangiography.",
]) + [
    sp(4),
    kmu("Redivac drain removed after 24 hours in simple elective surgery once drainage is minimal. [WMC - 2024]"),
    sp(4),
    h2("Clavien-Dindo Classification of Surgical Complications"),
    make_flow_table([
        ["Grade", "Definition", "Example"],
        ["I", "Deviation from normal, no pharmacological/surgical intervention", "Wound seroma, atelectasis"],
        ["II", "Requires pharmacological treatment (blood transfusion, TPN)", "UTI requiring antibiotics"],
        ["III", "Requires surgical, endoscopic, or radiological intervention", "Postop bleeding requiring re-op"],
        ["IV", "Life-threatening, ICU required", "Multi-organ failure"],
        ["V", "Death", "Fatal complication"],
    ], col_widths=[W*0.10, W*0.55, W*0.35]),
    sp(4),
    kmu("Active postoperative bleeding into drain requiring re-exploration = Clavien-Dindo Grade III. [GKMC - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 10 – Diathermy & Diagnostic Imaging
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(10) + [
    h1("PAGE 10 – SURGICAL DIATHERMY (ELECTROSURGERY) & IMAGING PHYSICS"),
    sp(4),
    h2("4. Principles of Surgical Diathermy"),
    p("Diathermy (also called electrosurgery) uses <b>high-frequency alternating electrical current</b> "
      "(typically 300 kHz to 3 MHz) to generate heat within biological tissues. This heat causes either "
      "controlled cellular vaporization (<b>cutting mode</b>) or protein coagulation (<b>coagulation mode</b>). "
      "It is one of the most important tools in modern surgery for simultaneous tissue cutting and haemostasis."),
    sp(4),
    make_two_col(
        ["Active electrode at surgical site",
         "Current travels THROUGH patient's body",
         "Returns via grounding pad (return electrode)",
         "Large body acts as a resistor; generates heat at tip only",
         "⚠️ RISK: Current can arc to pacemakers or metal implants"],
        ["Current flows ONLY between the two tips",
         "Instrument tips grip the target tissue",
         "Current does NOT travel through patient's body",
         "Safe for pacemaker patients",
         "✅ Preferred in patients with pacemakers or metal implants"],
        "MONOPOLAR Diathermy", "BIPOLAR Diathermy",
        LIGHT_RED, LIGHT_GREEN
    ),
    sp(6),
    h3("Monopolar Diathermy — Clinical Concerns"),
    p("In monopolar diathermy, the current must travel through the patient's entire body from the active "
      "electrode to the grounding pad. If the patient has a <b>cardiac pacemaker</b> or <b>implantable "
      "cardioverter-defibrillator (ICD)</b>, the electrical current can be sensed by the device, causing "
      "it to deliver inappropriate shocks, or can arc to the device/leads and cause malfunction or damage. "
      "Similarly, <b>metallic implants</b> (hip prostheses, internal fixation devices) can concentrate "
      "the current at the implant-tissue interface, causing thermal injury."),
    kmu("Monopolar diathermy is CONTRAINDICATED in patients with pacemakers, ICDs, or metallic implants. "
        "[GMC - 2024]"),
    kmu("BIPOLAR diathermy is the SAFE alternative for pacemaker patients — current stays localized. [RMC - 2025]"),
    sp(4),
    h3("Operating Modes of Diathermy"),
] + bl([
    "<b>Cutting Mode (continuous current):</b> Rapid cellular heating causes explosive vaporization, creating "
      "a precise cut. Produces less coagulation.",
    "<b>Coagulation Mode (interrupted/dampened current):</b> Slower, deeper heating causes protein "
      "denaturation and vessel wall coagulation without vaporization.",
    "<b>Blend Mode:</b> Combination of both, adjusting the ratio for different tissue types.",
]) + [
    sp(6),
    h2("5. Basic Physical Principles of Diagnostic Imaging"),
    h3("X-Ray Physics — Attenuation"),
    p("As X-rays pass through tissue, their intensity decreases via two mechanisms: <b>photoelectric "
      "absorption</b> (X-ray photon completely absorbed by an atom; predominant at lower energies) and "
      "<b>Compton scattering</b> (X-ray photon deflected with reduced energy). Dense tissues (bone, metal) "
      "attenuate more X-rays and appear white (radio-opaque) on film; air attenuates very little and appears "
      "black (radiolucent)."),
    kmu("X-ray intensity DECREASES as it passes through matter (due to absorption and scattering). [KMU - 2024]"),
    sp(4),
    h3("Radiation Dose Comparison"),
    make_flow_table([
        ["Modality", "Approximate Radiation Dose", "Equivalent Chest X-Rays"],
        ["Chest X-Ray", "0.02 mSv", "1"],
        ["Plain Abdominal X-Ray", "0.7 mSv", "35"],
        ["CT Abdomen/Pelvis", "10 mSv", "500"],
        ["Intravenous Urography", "2.5 mSv", "125"],
        ["Nuclear Bone Scan", "3–4 mSv", "150–200"],
    ], col_widths=[W*0.35, W*0.35, W*0.30]),
    sp(4),
    kmu("CT scan delivers the HIGHEST ionizing radiation dose among common diagnostic modalities. [WMC - 2025]"),
    sp(4),
    h3("Ultrasound — Piezoelectric Effect"),
    p("Ultrasound transducers contain a <b>piezoelectric crystal</b> (typically lead zirconate titanate). "
      "When an alternating electrical current is applied, the crystal rapidly changes shape (vibrates), "
      "generating high-frequency sound waves (2–20 MHz). These waves reflect off tissue interfaces; the "
      "returning echoes cause the crystal to vibrate, generating electrical signals that are processed "
      "into an image. Ultrasound uses NO ionizing radiation."),
    kmu("Ultrasound waves are generated by applying electrical current to a PIEZOELECTRIC crystal. [WMC - 2025]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 11 – Diathermy safety + Bipolar details
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(11) + [
    h1("PAGE 11 – DIATHERMY SAFETY STANDARDS & ELECTROSURGERY DETAILS"),
    sp(4),
    h2("Bipolar Diathermy — Safety Profile"),
    p("Bipolar diathermy is the safer electrosurgical modality because the electrical current is completely "
      "confined within the jaws of the bipolar forceps — it travels from one tip, through the captured "
      "tissue, and back through the other tip. The current does NOT enter the wider patient body. This means:"),
] + bl([
    "No risk of current arcing to pacemakers or implants",
    "No risk of burns at grounding pad sites",
    "Ideal for neurosurgery, ophthalmic surgery, and any patient with cardiac devices",
    "Current is more focused, giving precise haemostasis with less lateral thermal spread",
    "Cannot be used for tissue cutting (only coagulation)",
]) + [
    sp(4),
    kmu("Bipolar diathermy is the PREFERRED, SAFER option for patients with pacemakers or metallic implants. "
        "[RMC - 2025]"),
    sp(6),
    h2("Practical Safety Points for Theatre Use"),
    make_flow_table([
        ["Safety Issue", "Risk", "Prevention"],
        ["Pooling of spirit-based prep solution", "Fire/explosion from spark", "Allow to dry fully; blot pooled liquid"],
        ["Grounding pad placement (monopolar)", "Skin burns if not in full contact", "Flat contact over large muscle mass"],
        ["Bowel gas during colonoscopy", "Explosion risk", "Use bipolar or argon; use CO₂ insufflation"],
        ["Pacemaker interference", "Device malfunction, death", "Use bipolar; have magnet available; discuss with cardiologist"],
        ["Current spread in laparoscopy", "Capacitive coupling burns", "Monitor insulation; use lowest effective power"],
    ], col_widths=[W*0.28, W*0.32, W*0.40]),
    sp(6),
    h2("X-Ray Attenuation — Clinical Interpretation"),
    p("Understanding X-ray attenuation is fundamental to reading plain films. The four basic radiodensities "
      "from most to least attenuating are: <b>Metal > Bone (calcium) > Soft tissue (water density) > "
      "Fat > Air</b>. On a standard X-ray film (or digital display), the more a tissue attenuates, "
      "the whiter it appears."),
    sp(4),
    make_flow_table([
        ["Radiodensity", "Appearance on X-Ray", "Example"],
        ["Metal (highest)", "Brightest white", "Surgical clips, prostheses"],
        ["Bone (Calcium)", "White", "Cortical bone, calcified vessels"],
        ["Soft Tissue (Water)", "Grey", "Muscle, blood, liver, solid organs"],
        ["Fat", "Dark grey", "Retroperitoneal fat, subcutaneous fat"],
        ["Air (lowest)", "Black", "Lung parenchyma, pneumothorax, free air"],
    ], col_widths=[W*0.28, W*0.28, W*0.44]),
    sp(6),
    h2("Ultrasound Physics — Advanced Concepts"),
    p("Ultrasound images are built from the <b>time of flight</b> of echoes — the machine assumes sound "
      "travels at 1540 m/s in soft tissue and calculates depth from the echo return time. Different tissues "
      "have different acoustic impedances; at tissue interfaces, some sound is reflected (producing the "
      "image) and some is transmitted (allowing deeper structures to be visualized)."),
    sp(4),
] + bl([
    "<b>Anechoic (black):</b> Fluid-filled structures (cysts, blood vessels, bile) — no internal echoes",
    "<b>Hyperechoic (white):</b> Dense structures (fat, calculi, gas-tissue interfaces)",
    "<b>Hypoechoic (dark grey):</b> Solid organs (lymph nodes, many tumours)",
    "<b>Posterior acoustic enhancement:</b> Increased echoes deep to a fluid-filled cyst",
    "<b>Posterior acoustic shadowing:</b> Dark area deep to a calcification or gallstone",
]) + [
    sp(4),
    tip("Ultrasound has no ionizing radiation, is portable and cheap, but is operator-dependent and "
        "limited by obesity, gas, and bone."),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 12 – Section 4: Laparoscopy Principles
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(12) + [
    h1("PAGE 12 – SECTION 4: LAPAROSCOPIC AND ROBOTIC SURGERY"),
    sp(4),
    h2("1. Principles of Laparoscopy"),
    p("Laparoscopic surgery, also called <b>minimally invasive surgery (MIS)</b> or <b>keyhole surgery</b>, "
      "accesses the body's internal cavities through small port incisions (typically 5–12 mm) rather than "
      "a large open incision. A <b>laparoscope</b> (rigid camera-telescope) is inserted through one port "
      "to provide video visualization of the operative field, and surgical instruments are inserted through "
      "additional ports."),
    sp(4),
    h3("Creation of Pneumoperitoneum"),
    p("Before a laparoscope can be inserted into the abdominal cavity, a working space must be created. "
      "This is achieved by insufflating gas to expand the abdomen away from the underlying organs — "
      "creating a <b>pneumoperitoneum</b>. The Veress needle (a spring-loaded, blunt-tipped needle that "
      "self-sheathes once inside a cavity) is inserted at the umbilicus or Palmer's point to deliver gas."),
    sp(4),
    make_two_col(
        ["Non-combustible (safe for diathermy)",
         "Highly soluble in blood (rapidly eliminated)",
         "Minimizes risk of fatal CO₂ embolism",
         "Colourless, cheap, and readily available",
         "Rapidly exhaled by the lungs"],
        ["Not flammable — no explosion risk with diathermy",
         "Blood dissolves CO₂ quickly if embolism occurs",
         "Does not accumulate in body cavities",
         "Any institution can use it without special storage",
         "Breathed off via normal respiration post-op"],
        "CO₂ Properties", "Clinical Significance",
        LIGHT_BLUE, LIGHT_GREEN
    ),
    sp(4),
    kmu("CO₂ is the gas of choice for laparoscopy — NON-COMBUSTIBLE and HIGHLY SOLUBLE in blood. [WMC - 2024]"),
    kmu("Maximum safe insufflation pressure = 15 mmHg (maintained 12–15 mmHg). [WMC - 2025]"),
    sp(6),
    h3("Why 15 mmHg is the Maximum Safe Pressure"),
    p("The inferior vena cava (IVC) lies in the retroperitoneum at approximately 12–14 mmHg pressure. If "
      "intra-abdominal pressure exceeds 15 mmHg, it compresses the IVC, reducing venous return to the heart, "
      "causing decreased cardiac output and hypotension. Additionally, high pressure:"),
] + bl([
    "Splints the diaphragm, increasing peak airway pressures during ventilation",
    "Reduces renal perfusion, increasing risk of postoperative AKI",
    "Can cause CO₂ absorption and hypercarbia (raised PaCO₂)",
    "Increases risk of CO₂ embolism",
]) + [
    sp(6),
    h3("Laparoscopic Theatre Setup"),
    p("The standard laparoscopic setup includes: the camera (laparoscope connected to a camera head and "
      "light source), a <b>high-definition video screen</b> visible to the surgeon and assistant, an "
      "<b>insufflator</b> to maintain pneumoperitoneum, electrosurgical unit (diathermy), and "
      "<b>irrigation/suction</b> equipment. For complex cases, a second screen and video recorder are used."),
    note("The laparoscopic approach requires general anaesthesia because the pneumoperitoneum is painful "
         "and the Trendelenburg position impairs spontaneous breathing."),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 13 – Laparoscopy advantages, contraindications, complications
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(13) + [
    h1("PAGE 13 – LAPAROSCOPY: ADVANTAGES, CONTRAINDICATIONS & COMPLICATIONS"),
    sp(4),
    h2("2. Advantages and Disadvantages of Laparoscopic Surgery"),
    make_two_col(
        ["Reduced tissue trauma (smaller incisions)",
         "Less postoperative pain (reduced opioid need)",
         "Shorter hospital stay",
         "Faster return to normal activities",
         "Better cosmetic outcomes (small scars)",
         "Reduced wound infection rate",
         "Less intraoperative blood loss",
         "Reduced risk of incisional hernia"],
        ["Loss of tactile (haptic) feedback",
         "2D view on screen (loss of depth perception) in standard systems",
         "Limited range of instrument movement",
         "Steep and prolonged learning curve",
         "Risk of port-site hernia (small but real)",
         "Requires expensive dedicated equipment",
         "CO₂ pneumoperitoneum complications (hypercarbia, embolism)",
         "Not feasible in unstable emergency patients"],
        "✅ Advantages", "❌ Disadvantages",
        LIGHT_GREEN, LIGHT_RED
    ),
    sp(4),
    kmu("Main advantages of laparoscopy: reduced tissue trauma, smaller wounds, faster healing, shorter "
        "hospital stay. [AMC - 2024; GKMC - 2024]"),
    sp(6),
    h2("3. Indications and Absolute Contraindications"),
    h3("Common Laparoscopic Indications"),
] + bl([
    "<b>Elective:</b> Cholecystectomy, appendectomy, Nissen fundoplication, hiatal hernia repair, "
      "colorectal resection, splenectomy, adrenalectomy, nephrectomy, bariatric surgery",
    "<b>Gynaecological:</b> Salpingectomy, oophorectomy, hysterectomy, ovarian cystectomy, "
      "ectopic pregnancy",
    "<b>Diagnostic:</b> Staging laparoscopy for malignancy, evaluation of pelvic pain",
    "<b>Emergency:</b> Perforated peptic ulcer repair (in stable patients), ectopic pregnancy",
]) + [
    sp(4),
    h3("Absolute Contraindications"),
    p("<b>Uncontrolled coagulopathy</b> is an absolute contraindication to elective laparoscopy because "
      "trocar insertion into the abdominal wall and dissection carry risks of uncontrollable hemorrhage "
      "that cannot be managed through small laparoscopic ports."),
    p("Other absolute contraindications include:"),
] + bl([
    "Inability to tolerate general anaesthesia",
    "Severe cardiorespiratory compromise that cannot tolerate pneumoperitoneum",
    "Suspected abdominal aortic aneurysm (risk of catastrophic rupture during trocar insertion)",
]) + [
    sp(6),
    h2("4. Key Intraoperative Complications"),
    h3("Vagal-Induced Bradycardia During Insufflation"),
    p("Rapid distension of the parietal peritoneum by CO₂ gas stimulates <b>stretch receptors</b> in the "
      "peritoneum. Afferent signals travel via vagal pathways, triggering a reflex increase in vagal tone "
      "that can cause sudden, severe <b>bradycardia</b> or even <b>sinus arrest</b>. Management:"),
] + bl([
    "Immediately STOP insufflation and deflate the pneumoperitoneum (desufflation)",
    "Administer <b>IV Atropine</b> (anticholinergic) if bradycardia persists",
    "Consider restarting insufflation more slowly once rhythm normalizes",
]) + [
    kmu("Laparoscopic bradycardia = triggered by rapid peritoneal stretch activating vagal reflex. Treat "
        "with desufflation + IV Atropine. [RMC - 2025]"),
    sp(4),
    h3("Conversion to Open Surgery"),
    p("If continuous, uncontrollable hemorrhage occurs (e.g., from the falciform ligament, portal vein, or "
      "cystic artery during cholecystectomy), the <b>immediate safety standard</b> is conversion to open "
      "laparotomy. This is not a failure — it is the correct, safe clinical decision."),
    kmu("UNCONTROLLABLE bleeding during laparoscopy → IMMEDIATE conversion to open laparotomy. [NWSM - 2024]"),
    kmu("UNCONTROLLED COAGULOPATHY = absolute contraindication to elective laparoscopy. [GMC - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 14 – Robotic Surgery + MCQ Pointer Review for Sections 1-4
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(14) + [
    h1("PAGE 14 – ROBOTIC SURGERY & MCQ POINTERS REVIEW (SECTIONS 1–4)"),
    sp(4),
    h2("5. Robotic Surgery"),
    p("Robotic-assisted surgery represents the most technologically advanced platform for minimally invasive "
      "surgery. The current gold standard platform is the <b>da Vinci Surgical System</b> (Intuitive Surgical). "
      "It consists of three components: (1) a <b>surgeon console</b> where the operating surgeon sits, "
      "(2) a <b>patient-side robotic arm cart</b> that holds and manipulates the instruments, and "
      "(3) a <b>vision system</b> with a 3D high-definition camera."),
    sp(4),
    h3("Key Advantages of Robotic Surgery over Standard Laparoscopy"),
    make_flow_table([
        ["Feature", "Standard Laparoscopy", "Robotic Surgery"],
        ["Visualization", "2D standard or HD", "Full 3D, 10× magnified, HD"],
        ["Instrument movement", "4 degrees of freedom", "7 degrees of freedom (EndoWrist)"],
        ["Tremor filtration", "None", "Electronic tremor filtering"],
        ["Surgeon posture", "Standing at table", "Sitting at console (ergonomic)"],
        ["Learning curve", "Long", "Shorter for complex tasks"],
        ["Cost", "Moderate", "Very high (system + disposables)"],
    ], col_widths=[W*0.28, W*0.36, W*0.36]),
    sp(4),
    p("The <b>7 degrees of freedom</b> of the robotic EndoWrist instruments mimic the natural movement of "
      "the human hand and wrist, enabling suturing and dissection in very confined spaces (e.g., pelvis "
      "for prostatectomy) that are extremely difficult with standard laparoscopy. Tremor filtration "
      "eliminates the natural hand tremor that surgeons experience, allowing more precise movements."),
    kmu("Robotic surgery = most advanced minimally invasive technology; offers 3D vision, tremor filtration, "
        "7 degrees of freedom. [AMC - 2024]"),
    sp(6),
    h2("High-Yield MCQ Review — Sections 1 to 4"),
    make_flow_table([
        ["Topic", "The Answer"],
        ["WHO Checklist primary purpose", "Improve COMMUNICATION & TEAMWORK"],
        ["Time Out phase timing", "Between anaesthesia induction and skin incision"],
        ["Medication error prevention #1 step", "Double-check patient ID bracelet"],
        ["Consent responsibility", "The OPERATING SURGEON"],
        ["Consent ethical basis", "Respect for patient AUTONOMY"],
        ["Rose's position used for", "THYROIDECTOMY (neck hyperextension)"],
        ["Incision parallel to Langer's lines", "NARROW cosmetically superior scar"],
        ["Lowest hernia risk incision", "Gridiron/McBurney's (muscle-SPLITTING)"],
        ["Gas for pneumoperitoneum", "CO₂ — non-combustible, highly soluble"],
        ["Max safe laparoscopic pressure", "15 mmHg"],
        ["Laparoscopy bradycardia cause", "Vagal reflex from peritoneal stretch"],
        ["Absolute contraindication to laparoscopy", "Uncontrolled COAGULOPATHY"],
        ["Monopolar diathermy contraindicated in", "Pacemakers, ICDs, metallic implants"],
        ["Safer diathermy for pacemaker patients", "BIPOLAR diathermy"],
        ["Dominant wound cell Day 2+", "MACROPHAGES (replace neutrophils)"],
        ["Most common local cause poor healing", "LOCAL TISSUE INFECTION"],
    ], col_widths=[W*0.52, W*0.48]),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 15 – More MCQ Pointers (continuation from original pages 14-15)
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(15) + [
    h1("PAGE 15 – ADDITIONAL MCQ POINTERS: DIATHERMY, WOUND HEALING & IMAGING"),
    sp(4),
    p("This page continues the high-yield MCQ pointer review from the original document, covering key "
      "testable points from Sections 1 through 4. Each point below has been tested in KMU, KMC, AMC, GMC, "
      "WMC, RMC, or NWSM exams between 2023 and 2025."),
    sp(6),
    h2("Wound Closure & Healing — High-Yield Points"),
    make_flow_table([
        ["Concept", "Exam Fact"],
        ["Primary vs secondary intention determinant", "How closely wound edges are APPOSED"],
        ["Tertiary (delayed primary) closure example", "Hartmann's — fascia closed, skin left open, later closed"],
        ["Best suture for obese laparotomy closure", "Vertical Mattress Suture (wound edge eversion)"],
        ["Vicryl absorption mechanism", "HYDROLYSIS (not enzymatic)"],
        ["Vicryl complete absorption time", "60–90 days"],
        ["Redivac drain removal time", "24 hours in simple elective procedures"],
        ["Clavien-Dindo Grade III example", "Active drain bleeding requiring surgical re-exploration"],
        ["Post-op day 2 dominant wound cell", "MACROPHAGES (coordinate repair)"],
        ["Most common local cause poor healing", "LOCAL TISSUE INFECTION"],
    ], col_widths=[W*0.52, W*0.48]),
    sp(6),
    h2("Diathermy — High-Yield Points"),
    make_flow_table([
        ["Concept", "Exam Fact"],
        ["Monopolar contraindication", "Cardiac pacemakers, ICDs, metallic implants"],
        ["Mechanism of monopolar arcing risk", "Current travels through body → can arc to metal/device"],
        ["Safer option for pacemaker patients", "BIPOLAR diathermy"],
        ["Bipolar current pathway", "ONLY between the two forceps tips — not through patient"],
    ], col_widths=[W*0.52, W*0.48]),
    sp(6),
    h2("Imaging Physics — High-Yield Points"),
    make_flow_table([
        ["Concept", "Exam Fact"],
        ["X-ray intensity through matter", "DECREASES (absorption + scattering)"],
        ["Highest radiation dose modality", "CT scan"],
        ["Ultrasound generation mechanism", "Electrical current → PIEZOELECTRIC crystal → vibration → sound waves"],
        ["Ultrasound safety advantage", "No ionizing radiation"],
    ], col_widths=[W*0.52, W*0.48]),
    sp(6),
    h2("Laparoscopy — Additional High-Yield Points"),
] + bl([
    "<b>Laparoscopic advantages:</b> Reduced trauma, smaller wounds, faster healing, shorter stay. These are "
      "the MCQ answer — not 'better visualisation' (though that is also true).",
    "<b>Pneumoperitoneum CO₂ rationale:</b> NON-COMBUSTIBLE (safe with diathermy) + HIGHLY SOLUBLE IN BLOOD "
      "(minimizes fatal embolism risk). Both reasons are tested.",
    "<b>Bradycardia during insufflation:</b> Caused by RAPID peritoneal stretch → vagal surge. Treatment is "
      "DESUFFLATION first, then atropine if persistent.",
    "<b>Conversion to open:</b> The CORRECT response to uncontrollable laparoscopic hemorrhage. Not a failure.",
    "<b>Robotic surgery:</b> Distinguishes from laparoscopy by 3D HD vision, 7 degrees of freedom (EndoWrist), "
      "and tremor filtration.",
]) + [
    sp(6),
    kmu("Summary: Robotic surgery represents the most advanced stage of minimally invasive surgical "
        "technology. [AMC - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 16 – More MCQ continuation
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(16) + [
    h1("PAGE 16 – MCQ POINTERS REVIEW (CONTINUED) & SECTION TRANSITION"),
    sp(4),
    h2("Complete MCQ Review — Sections 1–4 Summary Table"),
    p("The following table consolidates ALL high-yield exam facts from the first four sections into a single "
      "rapid-review reference. Use this in the final 24–48 hours before the examination for active recall "
      "practice."),
    sp(6),
    make_flow_table([
        ["#", "Exam Question Theme", "The Correct Answer"],
        ["1", "WHO Checklist purpose", "Improve communication & teamwork"],
        ["2", "Time Out phase", "Between anaesthesia induction & skin incision"],
        ["3", "Safety reporting responsibility", "Shared: front-line, management & executives"],
        ["4", "Medication error prevention", "Double-check patient ID bracelet TWICE"],
        ["5", "Consent responsibility", "The OPERATING SURGEON"],
        ["6", "Ethical basis of consent", "Respect for patient autonomy"],
        ["7", "Laparoscopic consent extra disclosure", "Possible conversion to OPEN surgery"],
        ["8", "Implied consent applies when", "Life-threatening emergency, patient unconscious, no surrogate"],
        ["9", "Chaperone needed for", "Sensitive exams (e.g., breast) in female patients"],
        ["10", "Rose's position used in", "THYROIDECTOMY"],
        ["11", "Langer's lines → parallel incision", "Narrow, cosmetically superior scar"],
        ["12", "Langer's lines → perpendicular incision", "Wide, hypertrophic, poor scar"],
        ["13", "Muscle-splitting incision example", "Gridiron/McBurney's for appendectomy"],
        ["14", "Highest hernia risk incision", "MIDLINE (linea alba — avascular)"],
        ["15", "Lowest hernia risk incision", "Gridiron (muscle-splitting, self-closing)"],
        ["16", "Best incision for C-section", "Pfannenstiel (hidden, strong, cosmetically excellent)"],
        ["17", "Wound apposition primary intention", "Clean wound with closely apposed edges"],
        ["18", "Delayed primary closure type", "TERTIARY intention"],
        ["19", "Dominant cell Day 2 healing wound", "MACROPHAGES"],
        ["20", "Vertical mattress suture preferred in", "Obese patients for laparotomy (eversion)"],
        ["21", "Vicryl absorption days", "60–90 days by HYDROLYSIS"],
        ["22", "Redivac removal timing", "24 hours post-op, once drainage minimal"],
        ["23", "Clavien-Dindo Grade III", "Needs surgical/endoscopic/radiological intervention"],
        ["24", "Monopolar diathermy contraindicated", "Pacemakers, ICDs, metallic implants"],
        ["25", "Safer diathermy for pacemaker pt", "BIPOLAR"],
        ["26", "CO₂ for pneumoperitoneum reason", "Non-combustible + highly soluble in blood"],
        ["27", "Max safe insufflation pressure", "15 mmHg"],
        ["28", "Laparoscopy bradycardia cause", "Peritoneal stretch → vagal reflex"],
        ["29", "Laparoscopy absolute contraindication", "Uncontrolled COAGULOPATHY"],
        ["30", "Conversion to open indicated by", "Uncontrollable hemorrhage during laparoscopy"],
    ], col_widths=[W*0.06, W*0.55, W*0.39]),
    PageBreak(),
]

print("Pages 7-16 appended to story")
Writing File

~/surgery-explained/build_pdf_part3.py

"""
Pages 17-35 of the expanded surgery explanation PDF
"""

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 17 – Section 5: Informed Consent Deep Dive
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(17) + [
    h1("PAGE 17 – SECTION 5: SURGICAL INFORMED CONSENT (DEEP DIVE)"),
    sp(4),
    h2("1. Components and Legal Responsibilities"),
    p("Informed consent in surgery is not simply a bureaucratic formality — it is a <b>medico-legal "
      "requirement</b> and a fundamental ethical obligation. The consent process protects both the "
      "patient (by ensuring they understand what they agree to) and the surgeon (by documenting that "
      "the patient received adequate information before making their decision)."),
    sp(4),
    h3("Elements of a Valid Informed Consent"),
    make_flow_table([
        ["Element", "Description", "Clinical Importance"],
        ["Capacity", "Patient can understand, retain, weigh info, and communicate decision",
         "Must be assessed; varies with mental state, drugs, illness"],
        ["Voluntariness", "Decision made freely without coercion or undue influence",
         "Cannot be pressured by family, physician, or financial need"],
        ["Disclosure", "All material risks, benefits, alternatives explained",
         "Material = what a reasonable patient would want to know"],
        ["Understanding", "Patient can demonstrate they have understood the information",
         "Not just 'Do you understand?' — test comprehension"],
        ["Decision", "Patient makes and communicates a specific choice",
         "Can consent, refuse, or request more time"],
    ], col_widths=[W*0.18, W*0.45, W*0.37]),
    sp(6),
    h3("What the Operating Surgeon Must Explain"),
    p("The seven critical elements of surgical disclosure include:"),
] + bl([
    "<b>Diagnosis:</b> The confirmed or likely diagnosis that necessitates surgery",
    "<b>Nature of the procedure:</b> A plain-language description of what will be done surgically",
    "<b>Benefits:</b> Why surgery is recommended and what improvement is expected",
    "<b>Material risks:</b> Both common minor risks AND rare but serious risks",
    "<b>Alternative treatments:</b> Non-surgical and less invasive options",
    "<b>Consequences of not treating:</b> What happens if the patient declines surgery",
    "<b>Specific disclosures:</b> e.g., possible conversion to open, stoma formation, nerve injury",
]) + [
    sp(4),
    h3("The 'Montgomery Test' for Materiality of Risk"),
    p("A risk is considered 'material' (and must be disclosed) if a <b>reasonable patient in this patient's "
      "position</b> would want to know about it, even if the risk is rare. This is the current legal "
      "standard in most Commonwealth jurisdictions. For example: a 0.1% risk of vocal cord palsy after "
      "thyroidectomy is material for a professional singer and must be disclosed."),
    sp(4),
    h3("Exceptions to Standard Consent Processes"),
] + bl([
    "<b>Emergency exception:</b> Immediate threat to life, patient incapacitated, no surrogate — "
      "consent is LEGALLY IMPLIED. Must document reasoning.",
    "<b>Therapeutic privilege:</b> Historically, physicians could withhold information if it would "
      "harm the patient — now largely rejected; transparency is preferred.",
    "<b>Waiver:</b> Patient explicitly asks not to be told details — patient's autonomous choice to "
      "waive the right to information.",
    "<b>Incompetent adult:</b> Requires a legally authorized surrogate decision-maker (next of kin, "
      "legal guardian, or court order).",
]) + [
    sp(4),
    kmu("Consent for laparoscopic cholecystectomy MUST include possible conversion to open surgery. "
        "[GMC - 2024]"),
    kmu("Implied consent applies ONLY in TRUE life-threatening emergencies. [KMC - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 18 – Consent exceptions + MCQ Review Section 5
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(18) + [
    h1("PAGE 18 – CONSENT EXCEPTIONS, ETHICS & MCQ REVIEW"),
    sp(4),
    h2("2. Exceptions to Informed Consent — Detailed Analysis"),
    h3("Emergency Exception (Implied Consent) — Clinical Scenarios"),
    p("The most commonly tested scenario involves an <b>unconscious patient</b> brought to the emergency "
      "department with a life-threatening condition. Because the patient cannot consent and no surrogate "
      "is available, the law implies that a reasonable person in this situation would want life-saving "
      "treatment. The surgeon is legally protected in proceeding."),
    sp(4),
    make_flow_table([
        ["Scenario", "Consent Required?", "Rationale"],
        ["Alert patient, elective surgery", "YES — explicit, written", "Patient has capacity and time"],
        ["Unconscious trauma patient, bleeding",
         "NO — implied consent applies", "Life-threatening emergency, no surrogate"],
        ["Incapacitated patient, surrogate present",
         "YES — surrogate gives consent", "Surrogate must be legal decision-maker"],
        ["Minor child, elective surgery",
         "YES — parental consent required", "Child lacks legal capacity"],
        ["Minor child, life-threatening emergency, no parents",
         "NO — doctor proceeds in best interest", "Implied consent / best interest principle"],
        ["Adult who refuses emergency surgery",
         "RESPECT refusal if competent", "Autonomy overrides clinician judgment"],
    ], col_widths=[W*0.38, W*0.28, W*0.34]),
    sp(6),
    h3("Special Documentation Requirements"),
] + bl([
    "All consent discussions should be <b>documented in the medical record</b> with date, time, "
      "what was discussed, and who was present.",
    "If a patient refuses consent for a recommended procedure, their refusal and your discussion "
      "of consequences must be documented.",
    "Emergency procedures performed without consent must have a clear note explaining why consent "
      "was not possible.",
    "If conversion to open surgery becomes necessary intraoperatively, this should have been "
      "anticipated and discussed preoperatively.",
]) + [
    sp(6),
    h2("Top MCQ Pointers — Section 5 (Surgical Informed Consent)"),
    make_flow_table([
        ["#", "Question Theme", "Correct Answer"],
        ["1", "Who obtains informed consent?", "The OPERATING SURGEON performing the procedure"],
        ["2", "Ethical basis of consent", "Respect for patient AUTONOMY & self-determination"],
        ["3", "What to disclose for lap chole?", "Possibility of CONVERSION TO OPEN surgery"],
        ["4", "When does implied consent apply?", "Life-threatening emergency, patient incapacitated, no surrogate"],
        ["5", "Sensitive exam requirements", "Verbal consent + female CHAPERONE present"],
        ["6", "Legal standard for risk disclosure", "Risk that a reasonable PATIENT would want to know"],
    ], col_widths=[W*0.05, W*0.48, W*0.47]),
    sp(6),
    h3("Ethical Principles Underlying Consent"),
    make_flow_table([
        ["Principle", "Description", "Consent Relevance"],
        ["Autonomy", "Patient's right to make their own decisions", "Core basis of informed consent"],
        ["Beneficence", "Act in patient's best interest", "Justify surgical recommendation"],
        ["Non-maleficence", "Do no harm", "Disclose risks to avoid uninformed harm"],
        ["Justice", "Fair, equal treatment", "No discrimination in consent process"],
    ], col_widths=[W*0.22, W*0.42, W*0.36]),
    sp(4),
    info("Note: The PRIMARY ethical principle of informed consent is AUTONOMY, not beneficence. This is "
         "a commonly tested distinction in MCQs."),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 19 – Section 6: Perioperative Fluids
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(19) + [
    h1("PAGE 19 – SECTION 6: PERIOPERATIVE FLUID & ELECTROLYTE THERAPY"),
    sp(4),
    h2("1. Fluid Status Assessment and Requirements"),
    p("Managing fluid balance in the perioperative period is one of the most critical and nuanced skills "
      "in surgical practice. Both <b>under-resuscitation</b> (causing tissue hypoperfusion and organ "
      "failure) and <b>over-resuscitation</b> (causing pulmonary oedema, anastomotic oedema, and ileus) "
      "carry serious risks."),
    sp(4),
    h3("Body Fluid Compartments — Surgical Perspective"),
    make_flow_table([
        ["Compartment", "% Body Weight", "Clinical Significance"],
        ["Total Body Water (TBW)", "60% (men), 55% (women)", "Total reservoir of body fluids"],
        ["Intracellular Fluid (ICF)", "40% BW", "Cannot be directly replaced — follows osmotic gradients"],
        ["Extracellular Fluid (ECF)", "20% BW", "Can be replaced with crystalloids"],
        ["Intravascular (plasma)", "5% BW (~3.5 L)", "Directly expanded by IV fluids"],
        ["Interstitial", "15% BW", "Expands with crystalloids via Starling forces"],
    ], col_widths=[W*0.33, W*0.22, W*0.45]),
    sp(6),
    h3("Common Causes of Perioperative ECF Deficit"),
] + bl([
    "<b>Blood loss:</b> Intraoperative hemorrhage, GI bleeding",
    "<b>Gastrointestinal losses:</b> Vomiting, diarrhoea, nasogastric drainage, fistula output",
    "<b>Third-space losses:</b> Fluid shifts into the gut wall, peritoneum, and interstitium "
      "(especially after bowel surgery or major trauma)",
    "<b>Inadequate preoperative intake:</b> Prolonged fasting, poor oral intake due to illness",
    "<b>Insensible losses:</b> Fever, tachypnoea, open abdominal cavity exposure",
]) + [
    sp(4),
    kmu("Extracellular Fluid (ECF) deficit is the COMMONEST perioperative fluid disorder. [RMC - 2025]"),
    sp(6),
    h3("Ringer's Lactate (Hartmann's Solution) — Properties"),
    p("Ringer's Lactate is a <b>balanced crystalloid</b> designed to closely mimic the electrolyte "
      "composition of plasma. It is the preferred resuscitation fluid for:"),
] + bl([
    "<b>Severe dehydration</b> with electrolyte imbalance",
    "<b>Hemorrhagic shock</b> (before blood products) — restores circulating volume rapidly",
    "<b>Major burns</b> — the Parkland formula uses Ringer's Lactate exclusively",
    "<b>Post-surgical third-space losses</b>",
]) + [
    sp(4),
    make_flow_table([
        ["Component", "Ringer's Lactate", "Normal Saline (0.9% NaCl)", "Plasma (approx)"],
        ["Na⁺", "130 mEq/L", "154 mEq/L", "142 mEq/L"],
        ["Cl⁻", "109 mEq/L", "154 mEq/L", "103 mEq/L"],
        ["K⁺", "4 mEq/L", "0 mEq/L", "4.5 mEq/L"],
        ["Ca²⁺", "3 mEq/L", "0 mEq/L", "2.5 mEq/L"],
        ["Lactate/HCO₃⁻", "28 mEq/L", "0", "27 mEq/L"],
        ["Osmolality", "~273 mOsm/L", "308 mOsm/L", "285–295 mOsm/L"],
    ], col_widths=[W*0.22, W*0.26, W*0.26, W*0.26]),
    sp(4),
    kmu("Ringer's Lactate CONTAINS potassium (4 mEq/L); Normal Saline contains NONE. [WMC - 2025]"),
    kmu("Large-volume Normal Saline causes HYPERCHLOREMIC metabolic acidosis (excess Cl⁻). [GMC - 2024]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 20 – Electrolyte Disorders
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(20) + [
    h1("PAGE 20 – ACID-BASE AND ELECTROLYTE DISORDERS"),
    sp(4),
    h2("2. Perioperative Electrolyte Disorders"),
    h3("Normal Anion Gap (Hyperchloremic) Metabolic Acidosis"),
    p("The <b>anion gap</b> = Na⁺ − (Cl⁻ + HCO₃⁻). Normal = 8–12 mEq/L. A normal anion gap metabolic "
      "acidosis means bicarbonate is lost and chloride is retained to maintain electroneutrality — "
      "the anion gap doesn't change because the lost HCO₃⁻ is replaced by Cl⁻."),
    sp(4),
    p("Most common surgical cause: <b>Severe diarrhoea</b> — the intestinal secretion is rich in "
      "bicarbonate (up to 40 mEq/L), and massive loss depletes the body's bicarbonate buffer. "
      "The kidney compensates by retaining chloride."),
    kmu("Severe DIARRHOEA → normal anion gap (hyperchloremic) metabolic ACIDOSIS. [GMC - 2024]"),
    sp(6),
    h3("Hypochloremic Metabolic Alkalosis"),
    p("Caused by loss of hydrochloric acid from the stomach via persistent vomiting or nasogastric "
      "suction. As Cl⁻ and H⁺ are lost, plasma HCO₃⁻ rises (metabolic alkalosis). The kidneys "
      "initially retain Na⁺ by exchanging K⁺ (hypokalemia). Paradoxically, the kidneys excrete acid "
      "urine despite systemic alkalosis — this is 'paradoxical aciduria'."),
    make_flow_table([
        ["Cause", "Lost Substance", "Resulting Disorder"],
        ["Persistent vomiting", "HCl (H⁺ + Cl⁻)", "Hypochloremic metabolic alkalosis + hypokalemia"],
        ["Nasogastric suction", "HCl (H⁺ + Cl⁻)", "Same as above"],
        ["Severe diarrhoea", "HCO₃⁻ (bicarbonate-rich fluid)", "Normal anion gap metabolic acidosis"],
        ["Large-volume Normal Saline", "Excess Cl⁻ infused", "Hyperchloremic metabolic acidosis"],
    ], col_widths=[W*0.30, W*0.28, W*0.42]),
    sp(4),
    kmu("Vomiting/NG suction → hypochloremic metabolic ALKALOSIS (due to HCl loss). [GMC - 2024]"),
    sp(6),
    h3("Postoperative Hyponatremia — SIADH"),
    p("Surgical stress triggers ADH (antidiuretic hormone) release from the posterior pituitary. "
      "Excess ADH causes inappropriate water retention (SIADH — Syndrome of Inappropriate ADH). "
      "The retained water dilutes the serum sodium (dilutional hyponatremia). In <b>asymptomatic, "
      "stable</b> patients (Na⁺ > 125 mEq/L, no seizures or confusion), the initial management "
      "is <b>fluid restriction</b> (1–1.5 L/day) to allow sodium to normalize."),
    kmu("SIADH postoperative hyponatremia → initial management = FREE WATER RESTRICTION. [RMC - 2024]"),
    sp(6),
    h3("Hyperkalemia — Emergency Management"),
    p("Severe hyperkalemia (K⁺ > 6.5 mEq/L or any level with ECG changes) is immediately life-threatening "
      "due to cardiac arrhythmia risk. ECG findings include:"),
] + bl([
    "<b>Peaked T-waves</b> — earliest change (K⁺ ~5.5–6.5 mEq/L)",
    "<b>Prolonged PR interval and wide QRS</b> — K⁺ > 6.5 mEq/L",
    "<b>Sine wave pattern, ventricular fibrillation</b> — K⁺ > 8 mEq/L",
]) + [
    sp(4),
    p("The <b>immediate first-line treatment</b> for hyperkalemia with ECG changes (peaked T-waves, "
      "widened QRS) is <b>IV Calcium Gluconate 10%</b>. This drug does NOT lower serum potassium — "
      "it acts as a cardiac membrane stabilizer, raising the threshold potential of cardiac muscle "
      "cells and protecting against arrhythmia while other measures (insulin + dextrose, salbutamol, "
      "dialysis) are instituted to actually lower potassium."),
    kmu("10% IV Calcium Gluconate = first-line for hyperkalemia with ECG changes. It STABILIZES the "
        "myocardium but does NOT lower serum K⁺. [RMC - 2024; KMU - 2024; KMU - 2025]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 21 – Hyperkalemia ECG + MCQ summary
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(21) + [
    h1("PAGE 21 – HYPERKALEMIA ECG CHANGES & FLUID MCQ SUMMARY"),
    sp(4),
    h2("Hyperkalemia — Progressive ECG Changes"),
    p("The ECG changes in hyperkalemia follow a predictable progression as serum potassium rises. "
      "Recognizing these changes is a life-saving skill:"),
    sp(4),
    make_flow_table([
        ["K⁺ Level", "ECG Change", "Clinical Significance"],
        ["5.5–6.0 mEq/L", "Peaked/tall T-waves", "Earliest sign — increased rate of repolarization"],
        ["6.0–6.5 mEq/L", "Prolonged PR interval, flattened P waves", "AV conduction slowing"],
        ["6.5–7.5 mEq/L", "Wide QRS complex, 'Smeared'", "Ventricular conduction delay"],
        [">7.5 mEq/L", "Sine wave pattern", "Pre-terminal — QRS and T merge"],
        [">8.0 mEq/L", "VF or asystole", "Cardiac arrest"],
    ], col_widths=[W*0.22, W*0.35, W*0.43]),
    sp(6),
    h3("Full Treatment Ladder for Hyperkalemia"),
    make_flow_table([
        ["Step", "Drug/Intervention", "Mechanism", "Time to Effect"],
        ["1 — Cardiac Protection", "IV Calcium Gluconate 10%", "Stabilizes cardiac membrane", "Minutes"],
        ["2 — K⁺ Shift into Cells", "Insulin + 50% Dextrose", "K⁺ enters cells with glucose", "30 min"],
        ["3 — K⁺ Shift into Cells", "Salbutamol (nebulized)", "β2 activation → K⁺ uptake", "30 min"],
        ["4 — Remove K⁺ from Body", "Calcium Resonium (oral)", "GI K⁺ binding", "Hours"],
        ["5 — Definitive Removal", "Haemodialysis", "Removes K⁺ from circulation", "Immediate"],
    ], col_widths=[W*0.22, W*0.27, W*0.27, W*0.24]),
    sp(4),
    kmu("Calcium Gluconate: STABILIZES myocardium; does NOT reduce K⁺. This is the exam distinction. "
        "[RMC - 2024; KMU - 2025]"),
    sp(6),
    h2("Section 6 MCQ Summary"),
    make_flow_table([
        ["#", "Key Fact", "Answer"],
        ["1", "Commonest perioperative fluid disorder", "ECF (extracellular fluid) deficit"],
        ["2", "Preferred fluid for hemorrhagic shock", "Ringer's Lactate"],
        ["3", "Na⁺ and Cl⁻ concentration of Normal Saline", "154 mEq/L each"],
        ["4", "Risk of large-volume Normal Saline", "Hyperchloremic metabolic ACIDOSIS"],
        ["5", "Ringer's Lactate vs Normal Saline — K⁺", "RL has K⁺ (4 mEq/L); NS has NONE"],
        ["6", "Severe diarrhoea → acid-base disorder", "Normal anion gap metabolic ACIDOSIS"],
        ["7", "Vomiting/NG suction → acid-base disorder", "Hypochloremic metabolic ALKALOSIS"],
        ["8", "Postop hyponatremia (SIADH) — first Rx", "FLUID RESTRICTION"],
        ["9", "Hyperkalemia with ECG changes — first drug", "10% IV Calcium Gluconate"],
        ["10", "Calcium gluconate mechanism in hyperkalemia", "Cardiac membrane STABILIZATION (not K⁺ reduction)"],
    ], col_widths=[W*0.06, W*0.55, W*0.39]),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 22 – Section 7: Nutritional Support
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(22) + [
    h1("PAGE 22 – SECTION 7: NUTRITIONAL SUPPORT AND COMPLICATIONS"),
    sp(4),
    h2("1. Enteral Nutrition"),
    p("The gastrointestinal tract is the most physiologically appropriate and safest route for delivering "
      "nutrition. <b>Enteral nutrition (EN)</b> — feeding via the GI tract — is always preferred over "
      "parenteral nutrition whenever the gut is functional. This is encapsulated in the surgical aphorism: "
      "<b>'If the gut works, use it.'</b>"),
    sp(4),
    make_two_col(
        ["Preserves gut mucosal integrity",
         "Prevents intestinal villous atrophy",
         "Maintains the gut as an immunological barrier",
         "Reduces bacterial translocation from bowel",
         "Physiological hormonal responses preserved",
         "Lower cost",
         "Fewer serious complications"],
        ["Aspiration pneumonia",
         "Nasal/pharyngeal irritation from NG tube",
         "Diarrhoea (from hyperosmolar feeds or antibiotics)",
         "Tube misplacement",
         "Requires at least partial gut function"],
        "✅ Advantages of Enteral Nutrition", "⚠️ Risks/Limitations",
        LIGHT_GREEN, LIGHT_RED
    ),
    sp(4),
    h3("Feeding Jejunostomy — When to Use"),
    p("A feeding jejunostomy involves the surgical placement of a feeding tube directly into the "
      "<b>jejunum</b> (the second part of the small intestine), bypassing the stomach and oesophagus. "
      "This is used when nasogastric or nasoduodenal feeding is contraindicated because of oesophageal "
      "or gastric pathology."),
    p("Key indications:"),
] + bl([
    "<b>Corrosive oesophageal burns:</b> The oesophagus is inflamed and fragile — passing a NG tube "
      "risks perforation of the damaged mucosa.",
    "<b>Obstructing oesophageal carcinoma:</b> The NG tube cannot be passed through the tumour; "
      "attempting to do so risks perforation.",
    "<b>After major oesophageal or gastric surgery:</b> To provide nutrition while the anastomosis heals.",
]) + [
    sp(4),
    kmu("Feeding JEJUNOSTOMY (not NG tube) is used in corrosive oesophageal burns and oesophageal "
        "carcinoma — NG tube risks perforation. [GMC - 2025; KMU - 2023]"),
    sp(4),
    h3("Contraindications to Enteral Feeding"),
] + bl([
    "<b>Active severe GI bleeding:</b> Feeding could worsen haemorrhage or mask the severity of "
      "the bleeding; gut is not in a state to absorb nutrients effectively.",
    "<b>High-output proximal enteric fistulas:</b> Enteral feeding dramatically increases fistula "
      "output, making fluid/electrolyte management impossible and preventing fistula healing.",
    "Prolonged gut paralysis/obstruction",
    "Severe haemodynamic instability where splanchnic blood flow is compromised",
]) + [
    kmu("Active severe GI bleeding and high-output proximal fistulas = contraindications to enteral "
        "feeding. [NWSM - 2024; KMU - 2025]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 23 – TPN
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(23) + [
    h1("PAGE 23 – TOTAL PARENTERAL NUTRITION (TPN)"),
    sp(4),
    h2("2. Total Parenteral Nutrition (TPN)"),
    p("TPN delivers <b>all required nutrients intravenously</b> — glucose, amino acids, lipids, "
      "electrolytes, vitamins, and trace elements — via a <b>central venous catheter (CVC)</b>. "
      "It is used when the gut cannot be used for an adequate period of time."),
    sp(4),
    h3("Indications for TPN"),
    p("TPN is indicated when the gastrointestinal tract is:"),
] + bl([
    "<b>Non-functional:</b> Paralytic ileus, severe gut inflammation (Crohn's disease), radiation "
      "enteritis",
    "<b>Inaccessible:</b> Cannot pass a feeding tube past an obstruction",
    "<b>Requires complete rest:</b> High-output enteric fistulas, severe short bowel syndrome after "
      "major resection",
]) + [
    sp(4),
    kmu("TPN is indicated for short bowel syndrome and high-output fistulas (GI tract cannot be used). "
        "[NWSM - 2024; GKMC - 2024; KMU - 2025]"),
    sp(4),
    h3("TPN Composition"),
    make_flow_table([
        ["Component", "Proportion", "Purpose"],
        ["Dextrose (Glucose)", "~70% of non-protein calories", "Primary energy source"],
        ["Amino Acids", "~10% (protein)", "Nitrogen source for protein synthesis"],
        ["Lipid Emulsion", "~20% of calories", "Essential fatty acids + calorie density"],
        ["Electrolytes", "Added individually", "Na⁺, K⁺, Mg²⁺, PO₄³⁻, Ca²⁺"],
        ["Vitamins", "Added (daily multi-vitamin)", "Fat + water soluble"],
        ["Trace Elements", "Copper, zinc, selenium, manganese", "Enzyme cofactors"],
    ], col_widths=[W*0.25, W*0.28, W*0.47]),
    sp(4),
    kmu("TPN typical composition: 70% dextrose / 10% amino acids / 20% lipid emulsion. [KMU - 2025]"),
    sp(4),
    h3("TPN Monitoring"),
    p("During the early phase of TPN (especially the first week), close monitoring is required to "
      "detect metabolic complications early:"),
] + bl([
    "<b>Daily:</b> Complete blood count, urea, electrolytes, glucose, phosphate",
    "<b>Every 2–3 days:</b> Liver function tests, triglycerides",
    "<b>Weekly:</b> Zinc, copper, selenium (trace elements)",
]) + [
    kmu("Monitor CBC, serum urea, and electrolytes DAILY during early TPN therapy. [GMC - 2025]"),
    sp(4),
    h3("Absolute Contraindication"),
    p("<b>Active uncontrolled systemic infection (sepsis)</b> is an absolute contraindication to "
      "starting TPN. The hyperglycemia induced by TPN feeds the bacteria and worsens sepsis. "
      "Enteral nutrition can be maintained during controlled infection; TPN cannot be used."),
    kmu("Active sepsis = absolute contraindication to TPN. [KMU - 2023]"),
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 24 – TPN complications + Refeeding
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(24) + [
    h1("PAGE 24 – COMPLICATIONS OF NUTRITIONAL SUPPORT"),
    sp(4),
    h2("3. Complications of Nutritional Support"),
    h3("Complications of Central Venous Catheter (CVC) Insertion for TPN"),
    make_flow_table([
        ["Complication", "Mechanism", "Diagnosis", "Treatment"],
        ["Pneumothorax 🔥", "Lung puncture by needle", "CXR (air in pleural space)", "Aspiration or chest drain"],
        ["Haemothorax", "Subclavian/jugular vessel injury", "CXR + pleural blood", "Chest drain + blood replacement"],
        ["Arterial puncture", "Common carotid or subclavian", "Pulsatile bright red blood", "Firm pressure; vascular review"],
        ["Air embolism", "Air enters vein during insertion", "Sudden haemodynamic collapse", "Left lateral decubitus, aspiration via CVC"],
        ["Catheter malposition", "Tip not in SVC", "CXR", "Reposition or remove"],
        ["Line infection (CLABSI)", "Biofilm on CVC", "Fever, bacteraemia", "Remove CVC, systemic antibiotics"],
    ], col_widths=[W*0.22, W*0.26, W*0.24, W*0.28]),
    sp(4),
    kmu("Sudden dyspnea + chest pain after CVC insertion → suspect PNEUMOTHORAX → confirm with CHEST X-RAY. "
        "[KMC - 2024; KMU - 2024]"),
    sp(6),
    h3("Refeeding Syndrome"),
    p("<b>Refeeding syndrome</b> is a potentially fatal metabolic complication that occurs when nutrition "
      "— particularly carbohydrates — is rapidly reintroduced after a prolonged period of starvation or "
      "severe malnutrition. It is one of the most dangerous and under-recognized complications in "
      "hospitalized patients."),
    sp(4),
    h3("Pathophysiology"),
    p("In starvation, the body depletes intracellular stores of phosphate, magnesium, and potassium but "
      "serum levels remain relatively normal (as ions shift out of cells). When carbohydrates are "
      "reintroduced, insulin secretion surges, driving a massive cellular uptake of glucose along with "
      "phosphate, potassium, and magnesium. This causes sudden, profound drops in serum levels."),
    sp(4),
    make_flow_table([
        ["Electrolyte", "Normal Range", "Refeeding Level", "Clinical Consequences"],
        ["Phosphate", "0.8–1.4 mmol/L", "↓↓ (Hypophosphataemia)", "Respiratory muscle weakness, haemolysis, seizures, cardiac failure"],
        ["Potassium", "3.5–5.0 mEq/L", "↓↓ (Hypokalaemia)", "Cardiac arrhythmias, muscle weakness"],
        ["Magnesium", "0.7–1.0 mmol/L", "↓↓ (Hypomagnesaemia)", "Arrhythmias, seizures, tetany"],
    ], col_widths=[W*0.18, W*0.20, W*0.22, W*0.40]),
    sp(4),
    kmu("Refeeding syndrome = HYPOPHOSPHATAEMIA + HYPOKALAEMIA + HYPOMAGNESAEMIA after rapid refeeding of "
        "malnourished patient."),
    sp(4),
    h3("Prevention of Refeeding Syndrome"),
] + bl([
    "Identify at-risk patients (BMI <18.5, minimal intake for >5 days, chronic alcoholism, anorexia nervosa)",
    "Start nutrition SLOWLY — 10 kcal/kg/day initially, increasing over 4–7 days",
    "Replace phosphate, potassium, and magnesium BEFORE starting feeds",
    "Monitor electrolytes daily during the first week",
    "Supplement with thiamine (B1) — glucose refeeding depletes thiamine, causing Wernicke's encephalopathy",
]) + [
    PageBreak(),
]

# ═══════════════════════════════════════════════════════════════════════════════
# PAGE 25 – Nutrition MCQ Summary
# ═══════════════════════════════════════════════════════════════════════════════
story += page_tag(25) + [
    h1("PAGE 25 – NUTRITIONAL SUPPORT MCQ POINTERS & SUMMARY"),
    sp(4),
    h2("Section 7 High-Yield MCQ Pointer Review"),
    p("The following points represent the most commonly tested aspects of surgical nutrition. "
      "Each point is sourced directly from past examination questions."),
    sp(6),
    make_flow_table([
        ["#", "Key Concept", "Exam Answer"],
        ["1", "Why enteral > parenteral nutrition?", "Preserves gut integrity & prevents intestinal atrophy"],
        ["2", "Route in oesophageal carcinoma?", "Feeding JEJUNOSTOMY (not NG tube)"],
        ["3", "Route in corrosive oesophageal burn?", "Feeding JEJUNOSTOMY (NG tube risks perforation)"],
        ["4", "Contraindication to enteral feeding", "Active severe GI bleeding OR high-output proximal fistula"],
        ["5", "TPN indication (examples)", "Short bowel syndrome, high-output fistula"],
        ["6", "TPN absolute contraindication", "Active uncontrolled SEPSIS"],
        ["7", "TPN composition (dextrose %)", "~70% dextrose, 10% amino acids, 20% lipids"],
        ["8", "Daily TPN monitoring tests", "CBC, serum urea, ELECTROLYTES"],
        ["9", "Post-CVC insertion complication", "Pneumothorax — diagnose with CHEST X-RAY"],
        ["10", "Refeeding syndrome electrolyte triad", "Hypophosphataemia + Hypokalaemia + Hypomagnesaemia"],
    ], col_widths=[W*0.06, W*0.50, W*0.44]),
    sp(8),
    h2("Approach to Selecting Nutritional Route — Decision Algorithm"),
    make_flow_table([
        ["Question", "Yes → Action", "No → Next Step"],
        ["Is the GI tract functional?", "Use ENTERAL route", "Consider TPN"],
        ["Is the oesophagus/stomach accessible?", "NG tube or PEG", "Feeding Jejunostomy"],
        ["Is there active sepsis?", "DELAY TPN; treat sepsis first", "TPN is acceptable"],
        ["Is the patient malnourished?", "Check refeeding risk; supplement electrolytes first", "Standard protocol"],
        ["CVC inserted for TPN?", "Confirm position with CXR before use", "—"],
    ], col_widths=[W*0.35, W*0.33, W*0.32]),
    sp(6),
    h3("Nutritional Requirements — Reference Values"),
    make_flow_table([
        ["Nutrient", "Daily Requirement (Adult)", "Note"],
        ["Energy (calories)", "25–30 kcal/kg/day", "Higher in burns, sepsis, major surgery"],
        ["Protein (nitrogen)", "1.0–1.5 g/kg/day", "Up to 2 g/kg in severe catabolism"],
        ["Glucose", "3–5 g/kg/day (max 5 g/kg)", "Excess → fatty liver, hyperglycemia"],
        ["Lipid", "0.7–1.5 g/kg/day", "Includes essential fatty acids (linoleic acid)"],
    ], col_widths=[W*0.28, W*0.30, W*0.42]),
    sp(6),
    tip("Always prefer enteral > parenteral. If you must use TPN, monitor electrolytes daily, check "
        "CXR after line insertion, and always treat sepsis before starting."),
    PageBreak(),
]

print("Pages 17-25 appended")
This is a shared conversation. Sign in to Orris to start your own chat.