attachment
attachment
attachment
attachment
attachment
attachment
attachment
attachment
attachment
attachment

I dont know anything about metabolic response to injury . provide me concept in simple, easy-to-understand language .Describe figures/diagrams from the screenshots .Export the result as a well-formatted PDF .

I'll analyze all your screenshots and create a comprehensive, easy-to-understand PDF on metabolic response to injury. Let me first read all the images and the PDF skill.
analyse_media
analyse_media
analyse_media
analyse_media
analyse_media
Reading File
I have all the image content. Now let me read the rest of the PDF skill and create the PDF.Now I'll create the comprehensive PDF using Python with ReportLab:
Running Command

mkdir -p /home/daytona/workspace/metabolic-injury && ls /home/daytona/workspace/

Writing File

~/metabolic-injury/create_pdf.py

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

OUTPUT = "/home/daytona/workspace/metabolic-injury/Metabolic_Response_to_Injury.pdf"

# ── Colour palette ────────────────────────────────────────────────────────────
DARK_ORANGE   = colors.HexColor("#C0560A")
LIGHT_ORANGE  = colors.HexColor("#FFF0E0")
MID_ORANGE    = colors.HexColor("#F4A261")
DARK_BLUE     = colors.HexColor("#1A3A5C")
LIGHT_BLUE    = colors.HexColor("#E8F4FD")
MID_BLUE      = colors.HexColor("#2980B9")
GREEN_BG      = colors.HexColor("#E8F8EE")
GREEN_BORDER  = colors.HexColor("#27AE60")
PURPLE_BG     = colors.HexColor("#F3E8FF")
PURPLE_BORDER = colors.HexColor("#8E44AD")
GREY_LINE     = colors.HexColor("#CCCCCC")
TEXT_DARK     = colors.HexColor("#2C2C2C")
WHITE         = colors.white

# ── Document setup ────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2.2*cm, bottomMargin=2.2*cm,
    title="Metabolic Response to Injury",
    author="Bailey & Love — Simplified Study Guide"
)

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

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

def S(name, **kw):
    """Create a named ParagraphStyle with keyword overrides."""
    base = kw.pop("parent", "Normal")
    ps = ParagraphStyle(name, parent=styles[base], **kw)
    return ps

TITLE_STYLE = S("DocTitle",
    fontSize=26, leading=32, textColor=WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER, spaceAfter=4)

SUBTITLE_STYLE = S("DocSubtitle",
    fontSize=13, leading=18, textColor=colors.HexColor("#FFD9AA"),
    fontName="Helvetica", alignment=TA_CENTER, spaceAfter=0)

H1 = S("H1",
    fontSize=15, leading=20, textColor=DARK_ORANGE,
    fontName="Helvetica-Bold", spaceBefore=14, spaceAfter=4,
    borderPad=0)

H2 = S("H2",
    fontSize=12, leading=16, textColor=DARK_BLUE,
    fontName="Helvetica-Bold", spaceBefore=10, spaceAfter=3)

H3 = S("H3",
    fontSize=10.5, leading=14, textColor=DARK_BLUE,
    fontName="Helvetica-Bold", spaceBefore=7, spaceAfter=2)

BODY = S("Body",
    fontSize=10, leading=15, textColor=TEXT_DARK,
    fontName="Helvetica", spaceAfter=5, alignment=TA_JUSTIFY)

BULLET = S("Bullet",
    fontSize=10, leading=14, textColor=TEXT_DARK,
    fontName="Helvetica", spaceAfter=3,
    leftIndent=14, firstLineIndent=-14)

BOX_TITLE = S("BoxTitle",
    fontSize=11, leading=15, textColor=DARK_ORANGE,
    fontName="Helvetica-Bold", spaceAfter=4)

BOX_BODY = S("BoxBody",
    fontSize=9.5, leading=14, textColor=TEXT_DARK,
    fontName="Helvetica", spaceAfter=3, alignment=TA_JUSTIFY)

BOX_BULLET = S("BoxBullet",
    fontSize=9.5, leading=13, textColor=TEXT_DARK,
    fontName="Helvetica", spaceAfter=2,
    leftIndent=12, firstLineIndent=-12)

FIG_CAPTION = S("FigCaption",
    fontSize=9, leading=13, textColor=colors.HexColor("#555555"),
    fontName="Helvetica-Oblique", spaceAfter=6,
    leftIndent=8, rightIndent=8)

LABEL = S("Label",
    fontSize=8.5, leading=11, textColor=colors.HexColor("#666666"),
    fontName="Helvetica-Bold", alignment=TA_CENTER)

# ── Helper builders ───────────────────────────────────────────────────────────
def orange_box(title, items, body_text=None):
    """Coloured summary box with bullet list."""
    inner = [Paragraph(title, BOX_TITLE)]
    if body_text:
        inner.append(Paragraph(body_text, BOX_BODY))
    for item in items:
        inner.append(Paragraph(f"•  {item}", BOX_BULLET))
    t = Table([[inner]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), LIGHT_ORANGE),
        ("BOX",        (0,0), (-1,-1), 1.5, DARK_ORANGE),
        ("LEFTPADDING",  (0,0), (-1,-1), 12),
        ("RIGHTPADDING", (0,0), (-1,-1), 12),
        ("TOPPADDING",   (0,0), (-1,-1), 10),
        ("BOTTOMPADDING",(0,0), (-1,-1), 10),
    ]))
    return t

def blue_box(title, items, body_text=None):
    inner = [Paragraph(title, S("BT2", parent="Normal",
        fontSize=11, leading=15, textColor=DARK_BLUE,
        fontName="Helvetica-Bold", spaceAfter=4))]
    if body_text:
        inner.append(Paragraph(body_text, BOX_BODY))
    for item in items:
        inner.append(Paragraph(f"•  {item}", BOX_BULLET))
    t = Table([[inner]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), LIGHT_BLUE),
        ("BOX",        (0,0), (-1,-1), 1.5, MID_BLUE),
        ("LEFTPADDING",  (0,0), (-1,-1), 12),
        ("RIGHTPADDING", (0,0), (-1,-1), 12),
        ("TOPPADDING",   (0,0), (-1,-1), 10),
        ("BOTTOMPADDING",(0,0), (-1,-1), 10),
    ]))
    return t

def green_box(title, items, body_text=None):
    inner = [Paragraph(title, S("GT", parent="Normal",
        fontSize=11, leading=15, textColor=GREEN_BORDER,
        fontName="Helvetica-Bold", spaceAfter=4))]
    if body_text:
        inner.append(Paragraph(body_text, BOX_BODY))
    for item in items:
        inner.append(Paragraph(f"•  {item}", BOX_BULLET))
    t = Table([[inner]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), GREEN_BG),
        ("BOX",        (0,0), (-1,-1), 1.5, GREEN_BORDER),
        ("LEFTPADDING",  (0,0), (-1,-1), 12),
        ("RIGHTPADDING", (0,0), (-1,-1), 12),
        ("TOPPADDING",   (0,0), (-1,-1), 10),
        ("BOTTOMPADDING",(0,0), (-1,-1), 10),
    ]))
    return t

def figure_box(fig_num, title, desc_paragraphs):
    """Diagram/figure description block."""
    inner = [Paragraph(f"Figure {fig_num}  |  {title}", S("FH", parent="Normal",
        fontSize=10, leading=14, textColor=PURPLE_BORDER,
        fontName="Helvetica-Bold", spaceAfter=5))]
    for p in desc_paragraphs:
        inner.append(Paragraph(p, BOX_BODY))
    t = Table([[inner]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), PURPLE_BG),
        ("BOX",        (0,0), (-1,-1), 1.5, PURPLE_BORDER),
        ("LEFTPADDING",  (0,0), (-1,-1), 12),
        ("RIGHTPADDING", (0,0), (-1,-1), 12),
        ("TOPPADDING",   (0,0), (-1,-1), 10),
        ("BOTTOMPADDING",(0,0), (-1,-1), 10),
    ]))
    return t

def section_rule():
    return HRFlowable(width="100%", thickness=1.5, color=DARK_ORANGE,
                      spaceAfter=4, spaceBefore=8)

def sub_rule():
    return HRFlowable(width="100%", thickness=0.5, color=GREY_LINE,
                      spaceAfter=4, spaceBefore=4)

def bullet(txt, style=BULLET):
    return Paragraph(f"•  {txt}", style)

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

# ── Cover page ────────────────────────────────────────────────────────────────
def cover_page():
    # Title banner as table
    banner_inner = [
        [Paragraph("Metabolic Response to Injury", TITLE_STYLE)],
        [Paragraph("A Simple, Step-by-Step Study Guide", SUBTITLE_STYLE)],
        [Paragraph("Source: Bailey & Love's Short Practice of Surgery — Chapter 1", SUBTITLE_STYLE)],
    ]
    banner = Table(banner_inner, colWidths=[W])
    banner.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,-1), DARK_BLUE),
        ("TOPPADDING",   (0,0), (-1,-1), 22),
        ("BOTTOMPADDING",(0,0), (-1,-1), 22),
        ("LEFTPADDING",  (0,0), (-1,-1), 16),
        ("RIGHTPADDING", (0,0), (-1,-1), 16),
    ]))

    lo_rows = [
        ["What you will learn in this guide"],
        ["How the body responds to accidental injury and surgery"],
        ["Physiological and biochemical changes during injury and recovery"],
        ["Mediators and pathways of the metabolic response"],
        ["What happens to body composition after injury"],
        ["Avoidable factors that make the response worse"],
        ["How surgeons use this knowledge to improve patient outcomes"],
    ]
    lo_data = [[Paragraph(r[0], S("LOT", parent="Normal",
        fontSize=10, leading=14, textColor=DARK_BLUE,
        fontName="Helvetica-Bold" if i == 0 else "Helvetica",
        spaceAfter=0))] for i, r in enumerate(lo_rows)]
    lo_table = Table(lo_data, colWidths=[W])
    lo_table.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (0,0), MID_ORANGE),
        ("BACKGROUND",   (0,1), (-1,-1), LIGHT_ORANGE),
        ("BOX",          (0,0), (-1,-1), 1.2, DARK_ORANGE),
        ("LINEBELOW",    (0,0), (0,0), 1, DARK_ORANGE),
        ("TOPPADDING",   (0,0), (-1,-1), 7),
        ("BOTTOMPADDING",(0,0), (-1,-1), 7),
        ("LEFTPADDING",  (0,0), (-1,-1), 14),
    ]))

    return [banner, sp(16), lo_table, PageBreak()]

# ── Content ───────────────────────────────────────────────────────────────────
story = []
story += cover_page()

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 1 – INTRODUCTION & HOMEOSTASIS
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("1. Introduction & Homeostasis", H1))
story.append(section_rule())

story.append(Paragraph(
    "When the body is injured — whether by an accident, a surgical operation, or an illness like sepsis — "
    "it launches a powerful, co-ordinated set of changes throughout the whole body. These changes are "
    "called the <b>metabolic response to injury</b>. Think of it as the body's emergency plan: everything "
    "is reorganised so the body can survive the crisis and start repairing itself.",
    BODY))

story.append(Paragraph("<b>What is homeostasis?</b>", H3))
story.append(Paragraph(
    "Homeostasis simply means keeping the internal environment of the body constant and stable so that "
    "every cell can work properly. Surgery, trauma, and infection all disrupt homeostasis. The body's "
    "goal after injury is to restore this balance as quickly as possible.",
    BODY))

story.append(Paragraph("<b>The two main phases after injury</b>", H3))
story.append(Paragraph(
    "The metabolic response is classically divided into two stages:", BODY))
story.append(bullet("<b>Catabolic (breakdown) phase</b> — starts at the moment of injury. "
    "The body breaks down its own tissues to release emergency energy and building blocks. "
    "Signs include low blood pressure, low body temperature, high blood sugar, and lactic acid buildup."))
story.append(bullet("<b>Anabolic (rebuilding) phase</b> — begins once the emergency is under control. "
    "The body uses the building blocks it gathered to repair damaged tissue. This phase can last "
    "for weeks after serious injuries."))
story.append(sp())

story.append(orange_box(
    "Key Concepts to Remember",
    [
        "Homeostasis is the foundation of normal physiology",
        "'Stress-free' perioperative care helps preserve homeostasis after elective surgery",
        "Resuscitation and critical care aim to restore the conditions needed for homeostasis",
        "The metabolic response profoundly affects recovery through catabolism, MODS, and impaired immunity",
    ]
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 2 – MAGNITUDE OF THE RESPONSE
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("2. The Magnitude of the Injury Response", H1))
story.append(section_rule())

story.append(Paragraph(
    "The bigger the injury, the bigger the response. A minor operation causes only a small, brief "
    "rise in metabolic activity. A major trauma, severe burns, or sepsis can trigger an extreme "
    "response that leads to Systemic Inflammatory Response Syndrome (SIRS), organ failure, or even death.",
    BODY))

story.append(Paragraph(
    "Individual genetics also play a role — some patients respond dramatically even to relatively "
    "small injuries, while others respond mildly to severe ones.",
    BODY))

story.append(sp(6))
story.append(KeepTogether([
    figure_box("1.1", "Graded Metabolic Response to Injury (Two-Graph Chart)", [
        "<b>What the figure shows:</b> Two stacked line graphs that share the same x-axis (time in days, 0–70).",
        "<b>Top graph — Resting Metabolic Rate (%):</b> The y-axis runs from ~80% to 140% of normal. Three curves are shown: "
        "(1) <b>Major trauma</b> — shoots up to ~130–135% within a few days, then slowly returns toward normal over 40–60 days. "
        "(2) <b>Minor trauma</b> — rises to about 110%, then returns to normal within ~20 days. "
        "(3) <b>Starvation</b> — falls below 100%, reaching about 85%, and stays low. "
        "The horizontal band marked 'Normal range' sits at 100%.",
        "<b>Bottom graph — Nitrogen Excretion (g/day):</b> Nitrogen in the urine is a proxy for muscle breakdown. "
        "Major trauma causes a peak of ~20–25 g/day nitrogen loss (equivalent to losing ~500 g of muscle daily). "
        "Minor trauma causes a smaller peak (~10–12 g/day). Normal range is shown at the bottom (~5 g/day). "
        "Both return toward normal over several weeks.",
        "<b>Simple message:</b> More severe injury = higher metabolic rate AND more muscle wasting, for a longer time.",
    ])
]))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 3 – MEDIATORS: TISSUE DAMAGE & INFLAMMATION
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("3. Mediators: Tissue Damage &amp; Inflammation", H1))
story.append(section_rule())

story.append(Paragraph(
    "How does the body 'know' it has been injured? The answer is chemical signals released from "
    "damaged cells.",
    BODY))

story.append(Paragraph("<b>Step 1 — DAMPs (Damage-Associated Molecular Patterns)</b>", H3))
story.append(Paragraph(
    "When cells are damaged, they release fragments of themselves — proteins, DNA, etc. — into "
    "surrounding tissue. These fragments act as 'danger signals' called <b>DAMPs</b> (or alarmins). "
    "Think of them as a burglar alarm going off inside your body.",
    BODY))

story.append(Paragraph("<b>Step 2 — Pattern Recognition Receptors (PRRs)</b>", H3))
story.append(Paragraph(
    "Immune cells (macrophages, neutrophils, dendritic cells) carry sensors called <b>Toll-like "
    "receptors</b> and <b>NOD-like receptors</b>. These sensors detect DAMPs and activate the "
    "immune cells — like security guards responding to the alarm.",
    BODY))

story.append(Paragraph("<b>Step 3 — Inflammasome Activation &amp; Cytokine Release</b>", H3))
story.append(Paragraph(
    "Activated immune cells form protein complexes called <b>inflammasomes</b>. These activate "
    "enzymes called caspases, which in turn switch on key inflammatory messenger chemicals "
    "(cytokines) including:",
    BODY))
story.append(bullet("<b>IL-1</b> — causes fever and activates more immune cells"))
story.append(bullet("<b>IL-6</b> — triggers acute-phase protein production in the liver"))
story.append(bullet("<b>IL-8</b> — recruits neutrophils to the site of injury"))
story.append(bullet("<b>TNF-alpha</b> — promotes inflammation, fever, and cell death"))
story.append(sp(4))
story.append(Paragraph(
    "If this inflammatory cascade becomes too large or prolonged, it leads to <b>SIRS</b> "
    "(Systemic Inflammatory Response Syndrome) and can damage the lungs, kidneys, liver, "
    "and other organs — potentially causing <b>MODS</b> (Multiple Organ Dysfunction Syndrome).",
    BODY))

story.append(sp(6))
story.append(orange_box(
    "Secondary Triggers That Amplify the Response (Table 1.1)",
    [
        "Sepsis (infection)", "Haemorrhage (bleeding)", "Massive blood transfusion",
        "Acidosis (too much acid in the blood)", "Surgery itself",
        "Crush syndrome (muscle crush injury)", "Ischaemia-reperfusion injury",
    ],
    body_text="These events can amplify or prolong the catabolic phase, leading to organ failure or immune dysfunction:"
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 4 – NEUROENDOCRINE RESPONSE
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("4. The Neuroendocrine Response to Injury", H1))
story.append(section_rule())

story.append(Paragraph(
    "At the same time that the immune system responds, the nervous system and hormone system "
    "launch their own emergency response. This is the <b>neuroendocrine response</b>.",
    BODY))

story.append(Paragraph("<b>The nerve pathway (fast response — seconds to minutes)</b>", H3))
story.append(Paragraph(
    "Pain signals from the injury travel up through afferent (sensory) nerves → spinal cord → "
    "thalamus → hypothalamus. The hypothalamus is the control centre for this response.",
    BODY))

story.append(Paragraph("<b>The hormone cascade (minutes to hours)</b>", H3))
for txt in [
    "Hypothalamus releases <b>CRF</b> (Corticotropin-Releasing Factor)",
    "CRF signals the pituitary gland to release <b>ACTH</b> (adrenocorticotropic hormone) and <b>Growth Hormone (GH)</b>",
    "ACTH travels to the adrenal glands, which release <b>cortisol</b> and <b>adrenaline</b>",
    "Hypothalamic activation of the sympathetic nervous system also releases <b>adrenaline (epinephrine)</b> from the adrenals",
    "The pancreas is signalled to release more <b>glucagon</b>",
    "Insulin, IGF-1, testosterone, and thyroid hormone (T3) all <b>decrease</b>",
]:
    story.append(bullet(txt))
story.append(sp(4))

story.append(Paragraph("<b>What do these hormones DO?</b>", H3))
story.append(Paragraph(
    "The 'counter-regulatory' hormones (cortisol, glucagon, adrenaline) work together to raise "
    "blood glucose by breaking down glycogen stores and fat. This provides emergency fuel for "
    "the brain, heart, and immune system.",
    BODY))

story.append(sp(6))
story.append(KeepTogether([
    figure_box("1.2", "Integrated Neuroendocrine Response to Surgical Injury (Pathway Diagram)", [
        "<b>What the figure shows:</b> A complex but logical flowchart linking the injury site to metabolic changes throughout the body. It has three main columns: Anatomy (left), Plasma hormones/cytokines (centre), and Metabolic effects (right).",
        "<b>Left side — The anatomy:</b> An 'Injury' starburst at the bottom sends signals in two directions: "
        "(1) Upward via <b>afferent nociceptive pathways</b> through the spinal cord to the hypothalamus/pituitary. "
        "(2) Across to the <b>innate immune system</b>, which communicates with the <b>adaptive immune system</b> (T and B cells).",
        "<b>Centre — Plasma changes:</b> The brain pathway stimulates the pituitary to release ACTH (up arrow) and GH (up arrow). "
        "These act on the adrenal glands, releasing <b>adrenaline</b> (up) and <b>cortisol</b> (up). The pancreas releases "
        "<b>glucagon</b> (up). The immune system produces cytokines (IL-1, TNF-alpha, IL-6, IL-8). Meanwhile, insulin, IGF-1, "
        "testosterone, and T3 all fall (down arrows).",
        "<b>Right side — Metabolic consequences:</b> "
        "ACTH/GH → Adipocyte lipolysis (fat breakdown). "
        "Cortisol/Adrenaline → Hepatic gluconeogenesis (liver makes new glucose) + Skeletal muscle protein degradation. "
        "Glucagon → Hepatic acute-phase protein synthesis. "
        "Cytokines → Pyrexia (fever) + Hypermetabolism (raised metabolic rate).",
        "<b>Simple message:</b> Injury triggers a cascade through the brain and immune system that mobilises every available energy source to keep the patient alive.",
    ])
]))
story.append(sp(6))

story.append(blue_box(
    "The Neuroendocrine Response is Biphasic (Summary Box 1.2)",
    [
        "Acute phase (hours): Elevated cortisol, glucagon, adrenaline — helpful for short-term survival",
        "Chronic phase (days): Hypothalamic suppression, low levels of target-organ hormones — may contribute to chronic wasting",
    ]
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 5 – METABOLIC CHANGES AFTER SURGERY & TRAUMA
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("5. Metabolic Changes After Surgery &amp; Trauma", H1))
story.append(section_rule())

story.append(Paragraph("<b>The catabolic (breakdown) phase (0–48 hours)</b>", H3))
for txt in [
    "Hypovolaemia (low circulating blood volume)",
    "Decreased cardiac output and basal metabolic rate",
    "Hypothermia (low body temperature)",
    "Lactic acidosis (buildup of lactic acid)",
    "Hyperglycaemia (high blood sugar) due to insulin resistance",
    "Key hormones: catecholamines, cortisol, and aldosterone",
]:
    story.append(bullet(txt))

story.append(Paragraph("<b>The flow phase / SIRS phase (hours to weeks)</b>", H3))
story.append(Paragraph(
    "After the initial shock is treated, the body switches to a 'hypermetabolic flow phase'. This is "
    "the body mobilising its energy stores for repair. Features include:",
    BODY))
for txt in [
    "Tissue oedema (fluid leaks into tissues — vasodilatation and capillary leakage)",
    "Hypermetabolism — metabolic rate raised 15–25% above normal",
    "Increased cardiac output and body temperature",
    "Leukocytosis (high white cell count)",
    "Increased gluconeogenesis (liver makes glucose from amino acids)",
    "Progressive muscle wasting as amino acids are diverted to the liver and immune system",
]:
    story.append(bullet(txt))

story.append(sp(6))
story.append(orange_box(
    "Key Characteristics of the Metabolic Response (Summary Box 1.3)",
    [
        "Rapid onset, driven by IL-1, IL-6, and TNF-alpha",
        "Severity broadly proportional to injury severity; worst in sepsis, burns, and major trauma",
        "Varies significantly between individuals (genetic factors)",
        "Causes catabolism, muscle breakdown, immunosuppression, and organ dysfunction",
        "Counterbalanced by an anti-inflammatory response (but balance may be imperfect)",
        "Prolonged by sepsis and secondary insults",
        "Associated with most late deaths from surgery or injury in developed countries",
    ]
))
story.append(sp(6))

story.append(blue_box(
    "Purpose of the Neuroendocrine Changes (Summary Box 1.4)",
    [
        "Provide essential substrates for survival from tissue breakdown",
        "Postpone anabolism (delay rebuilding until the acute crisis is over)",
        "Optimise host defence (support immune function)",
    ],
    body_text="These changes are helpful in the short term, but harmful in the long term — especially to the critically ill patient."
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 6 – MANAGING THE CATABOLIC STRESS RESPONSE
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("6. Managing the Catabolic Stress Response", H1))
story.append(section_rule())

story.append(Paragraph(
    "Not all tissues are broken down equally during the catabolic phase. The body uses a clever "
    "prioritisation system: it sacrifices 'peripheral' tissues to support 'central' vital ones.",
    BODY))

story.append(sp(6))
story.append(KeepTogether([
    figure_box("1.3", "Resource Reprioritisation During Injury (Arrow Diagram)", [
        "<b>What the figure shows:</b> A simple two-column diagram with arrows showing the direction of protein flow during the catabolic phase.",
        "<b>Left column (Peripheral — 'donor' tissues):</b> Three boxes stacked vertically: Muscle, Adipose tissue, Skin.",
        "<b>Centre — Arrow:</b> A large rightward arrow labelled 'Amino acids (especially Glutamine and Alanine)' — these are the building blocks released from muscle breakdown.",
        "<b>Right column (Central — 'recipient' tissues):</b> Three boxes stacked vertically: Liver, Immune system, Wound.",
        "<b>Simple message:</b> The body cannibalises muscle, fat, and skin to feed the liver (which makes glucose and protective proteins), the immune system (which fights infection), and the wound (which needs repair). This is why patients lose so much muscle during critical illness — it is intentional, not incidental.",
        "<b>Why glutamine and alanine?</b> These two amino acids are released in large amounts from muscle. They are used as fuel by immune cells and as building blocks for new glucose in the liver. The irreversible breakdown of branched-chain amino acids to make them is why muscle protein loss is so difficult to reverse with nutrition alone.",
    ])
]))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 7 – HYPERMETABOLISM & MUSCLE WASTING
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("7. Hypermetabolism &amp; Skeletal Muscle Protein Wasting", H1))
story.append(section_rule())

story.append(Paragraph("<b>Hypermetabolism</b>", H2))
story.append(Paragraph(
    "Most trauma patients burn <b>15–25% more energy</b> than their normal resting requirement. "
    "Burns patients can burn even more. This is driven by the sympathetic nervous system, "
    "proinflammatory cytokines, and the energy cost of wound healing. In practice, fever, "
    "high cardiac output, and high respiratory rate all reflect this elevated metabolic state.",
    BODY))

story.append(Paragraph("<b>Muscle Wasting</b>", H2))
story.append(Paragraph(
    "Normally, muscle protein is constantly being made and broken down, with a daily turnover of "
    "1–2%. After injury, breakdown <b>increases</b> and synthesis <b>decreases</b>. The main "
    "molecular pathway responsible is the <b>ubiquitin-proteasome system</b>.",
    BODY))

story.append(sp(6))
story.append(KeepTogether([
    figure_box("1.4", "The Ubiquitin-Proteasome Pathway (Molecular Diagram)", [
        "<b>What the figure shows:</b> A circular flowchart showing how the body tags muscle proteins for destruction and then grinds them into amino acids.",
        "<b>Step 1:</b> Muscle fibres (myofibrillar protein) are first partially damaged by enzymes called <b>Caspases, Cathepsins, and Calpains</b>. Think of these as 'scissors' that cut the muscle into smaller fragments.",
        "<b>Step 2 — Tagging:</b> A small protein called <b>Ubiquitin</b> is attached to the damaged protein fragment. This requires energy (ATP) and three enzymes: E1 (ubiquitin-activating), E2 (ubiquitin-conjugating), and E3 (ubiquitin ligase). The tagged protein is now called 'ubiquitinated protein'.",
        "<b>Step 3 — Shredding:</b> The tagged protein is fed into a large barrel-shaped molecular machine called the <b>26S Proteasome</b> (made of 19S + 20S + 19S units). This machine uses ATP to unfold and cleave the protein into small peptide fragments.",
        "<b>Step 4 — Recycling:</b> A peptidase called Tripeptidyl Peptidase breaks the peptides into individual <b>amino acids</b>, which are then released into the bloodstream.",
        "<b>Clinical relevance:</b> In severe sepsis, this pathway operates so fast that patients can lose up to 500 g of skeletal muscle per day. This cannot be stopped by feeding alone — treating the underlying infection is the only way to slow it.",
    ])
]))

story.append(sp(6))
story.append(orange_box(
    "Skeletal Muscle Wasting — Key Points (Summary Box 1.5)",
    [
        "Provides amino acids for the metabolic support of central organs and tissues",
        "Mediated mainly by the ubiquitin-proteasome pathway",
        "Inevitable to some degree, but prolonged by sepsis in particular",
        "Can cause immobility, prolonged recovery, hypostatic pneumonia, and death if excessive",
    ]
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 8 – HEPATIC ACUTE-PHASE RESPONSE & INSULIN RESISTANCE
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("8. Liver Changes: The Acute-Phase Protein Response", H1))
story.append(section_rule())

story.append(Paragraph(
    "The liver is a major beneficiary of the resource redistribution described above. Driven by "
    "IL-6 and other cytokines, it shifts its protein production priorities.",
    BODY))

story.append(Paragraph("<b>Positive acute-phase proteins (increase after injury)</b>", H3))
for txt in [
    "<b>C-reactive protein (CRP)</b> — activates complement, opsonises bacteria. The standard blood test marker of inflammation.",
    "<b>Fibrinogen</b> — essential for blood clotting",
    "Other complement proteins and protease inhibitors",
]:
    story.append(bullet(txt))

story.append(Paragraph("<b>Negative acute-phase proteins (decrease after injury)</b>", H3))
story.append(Paragraph(
    "The liver temporarily reduces production of 'housekeeping' proteins to free up resources:", BODY))
for txt in [
    "<b>Albumin</b> — the main blood protein; low albumin after injury is partly due to capillary leakage, not just reduced production",
    "Transferrin, prealbumin, and other transport proteins",
]:
    story.append(bullet(txt))

story.append(sp(6))
story.append(Paragraph("Insulin Resistance", H2))
story.append(Paragraph(
    "After surgery or trauma, patients develop a state similar to <b>Type 2 diabetes</b>. Blood "
    "glucose rises despite high glucose production because peripheral tissues (especially muscle) "
    "can no longer respond properly to insulin. This is caused by proinflammatory cytokines "
    "blocking insulin signalling.",
    BODY))
story.append(Paragraph(
    "After routine abdominal surgery, insulin resistance can last <b>~2 weeks</b>. After "
    "prolonged sepsis, it can persist much longer. In ICU patients, IV insulin infusions "
    "are used to maintain blood glucose in a safe range.",
    BODY))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 9 – BODY COMPOSITION CHANGES
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("9. Changes in Body Composition After Injury", H1))
story.append(section_rule())

story.append(KeepTogether([
    figure_box("1.5", "Normal Body Composition of a 70 kg Male (Stacked Bar Chart)", [
        "<b>What the figure shows:</b> A single vertical stacked bar representing total body mass (70 kg), divided into five segments from bottom to top.",
        "<b>Minerals (0–3 kg, green):</b> ~3 kg — mainly in bones (calcium, phosphate, etc.)",
        "<b>Extracellular water (3–17 kg, purple):</b> ~14 litres — the fluid outside cells (blood plasma, interstitial fluid). This compartment expands massively after injury due to leaky capillaries.",
        "<b>Intracellular water (17–45 kg, light blue):</b> ~28 litres — the fluid inside cells. The body's largest fluid compartment.",
        "<b>Protein (45–57 kg, orange):</b> ~12 kg — includes 4 kg skeletal muscle + 8 kg visceral protein. This is the reservoir that gets raided during catabolism.",
        "<b>Fat (57–70 kg, yellow):</b> ~13 kg — the main long-term energy store. Can be mobilised without serious functional loss (unlike protein).",
        "<b>Bracket on right:</b> The portion from minerals to protein is bracketed as 'FFM/LBM' (Fat-Free Mass / Lean Body Mass) = ~57 kg.",
        "<b>Simple message:</b> The body holds protein (~12 kg) and fat (~13 kg) as its reserves. Fat loss is better tolerated; excessive protein loss causes functional impairment.",
    ])
]))

story.append(sp(6))
story.append(KeepTogether([
    figure_box("1.6", "Changes in Body Weight Over Time (Line Graph)", [
        "<b>What the figure shows:</b> A single graph with a y-axis that goes both upward (weight gain %) and downward (weight loss %), with time in days (0–22) on the x-axis. Three curves are shown.",
        "<b>Red curve — Sepsis and multiorgan failure:</b> Paradoxically, body weight RISES initially (up to +15% at ~day 8). This is because massive fluid is given during resuscitation — the weight gain is water, not lean tissue. After day 8, weight falls rapidly as the extracellular fluid space is resolved.",
        "<b>Green curve — Uncomplicated major surgery:</b> Weight falls steadily to about -8% loss by day 10, then begins to recover. This reflects loss of body fat and protein after a controlled surgical insult.",
        "<b>Purple curve — Starvation:</b> Steadily progressive weight loss reaching ~-14% by day 22. Unlike surgery, this is not accompanied by the same degree of metabolic stress — the body adapts by lowering its metabolic rate.",
        "<b>Simple message:</b> Sepsis patients initially gain fluid weight, then crash. Surgical patients steadily lose weight then recover. Starvation patients lose weight gradually.",
    ])
]))
story.append(sp(6))

story.append(blue_box(
    "Changes in Body Composition After Major Surgery/Critical Illness (Summary Box 1.7)",
    [
        "Catabolism leads to a decrease in fat mass and skeletal muscle mass",
        "Body weight may paradoxically increase because of fluid expansion in the extracellular space",
    ]
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 10 – AVOIDABLE FACTORS
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("10. Avoidable Factors That Worsen the Response", H1))
story.append(section_rule())

story.append(Paragraph(
    "Several factors can make the metabolic response worse — and many are avoidable in clinical practice.",
    BODY))

story.append(sp(6))
story.append(KeepTogether([
    figure_box("1.7", "Factors That Exacerbate the Catabolic Stress Response (Flow Diagram)", [
        "<b>What the figure shows:</b> A horizontal flowchart with inputs on the left, a central processing pathway, effects in the middle, and outcomes on the right.",
        "<b>Top orange arrow:</b> 'Immobilisation' — bed rest independently drives muscle wasting through loss of the normal amino acid stimulus to protein synthesis.",
        "<b>Bottom orange arrow:</b> 'Starvation' — fasting (including inappropriate preoperative fasting) removes the fed-state suppression of catabolism.",
        "<b>Purple box (clinical stressors):</b> Wound, Hypothermia, Hypotension, Pain — these four inputs all activate the adreno-sympathetic system and cytokine cascade.",
        "<b>Central green boxes:</b> Two boxes: 'Adreno-sympathetic activation' and 'Cytokine cascade release', connected by a double-headed arrow (they stimulate each other).",
        "<b>Light blue effects box:</b> Pyrexia, Acute-phase response, Insulin resistance, Futile substrate cycling, Muscle protein degradation.",
        "<b>Right — Outcomes:</b> Two vertical columns: CATABOLISM (+) is increased; ANABOLISM (-) is suppressed.",
        "<b>Simple message:</b> Pain, cold, bed rest, and starvation all amplify catabolism and block recovery. Preventing these is a core surgical principle.",
    ])
]))
story.append(sp(6))

story.append(Paragraph("<b>The major avoidable culprits explained simply:</b>", H3))

culprits = [
    ("Volume Loss / Bleeding",
     "Baroreceptors detect low blood pressure and activate ADH and the renin-angiotensin-aldosterone system, causing salt and water retention. Excessive saline infusions cause oedema and prolong hospital stay."),
    ("Hypothermia",
     "Even mild hypothermia increases postoperative cardiac arrhythmias and catabolism 2-3 fold. Warm the patient during surgery with forced-air heating blankets."),
    ("Tissue Oedema",
     "Systemic inflammation makes capillaries leaky. Excess intravenous saline worsens this — it fills the extracellular space with water, impairing gut function, wound healing, and lung gas exchange."),
    ("Starvation",
     "Fasting forces the liver to make glucose from amino acids (gluconeogenesis). Modern guidelines allow clear fluids up to 2 hours before surgery. A pre-operative carbohydrate drink reduces postoperative insulin resistance."),
    ("Immobility",
     "Bed rest impairs the normal feeding-induced amino acid stimulus to protein synthesis in skeletal muscle. Early mobilisation is essential and is one of the most powerful tools to limit muscle wasting."),
    ("Systemic Inflammation / Tissue Underperfusion",
     "Uncontrolled inflammation and poor tissue blood flow create more DAMPs and extend the catabolic phase. Adequate resuscitation and sepsis control are the countermeasures."),
]
for title, text in culprits:
    story.append(Paragraph(f"<b>{title}</b>", H3))
    story.append(Paragraph(text, BODY))

story.append(sp(4))
story.append(orange_box(
    "Avoidable Factors During Elective Surgery (Summary Box 1.8)",
    [
        "Continuing haemorrhage / volume loss",
        "Hypothermia", "Tissue oedema", "Tissue underperfusion",
        "Starvation (including excessive preoperative fasting)", "Immobility",
    ]
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# SECTION 11 – ENHANCED RECOVERY (ERAS)
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("11. Enhanced Recovery After Surgery (ERAS)", H1))
story.append(section_rule())

story.append(Paragraph(
    "<b>ERAS</b> (Enhanced Recovery After Surgery) is a modern evidence-based approach that uses "
    "multiple simultaneous interventions to minimise the metabolic stress of surgery and speed up "
    "recovery. The key insight is: <i>if you reduce the injury, you reduce the response.</i>",
    BODY))

story.append(Paragraph("<b>Core ERAS principles:</b>", H3))
for txt in [
    "<b>Minimal access techniques</b> (laparoscopic surgery instead of open surgery) — smaller wounds = smaller inflammatory trigger",
    "<b>Blockade of afferent pain signals</b> (epidural analgesia, spinal anaesthesia, wound catheters) — less pain = less neuroendocrine activation",
    "<b>Minimal starvation</b> — carbohydrate drinks preoperatively, early enteral/oral feeding postoperatively",
    "<b>Early mobilisation</b> — prevents immobility-driven muscle wasting",
    "<b>Optimal fluid management</b> — avoid excess saline, maintain tissue perfusion without causing oedema",
]:
    story.append(bullet(txt))
story.append(sp(6))

story.append(KeepTogether([
    figure_box("1.8", "ERAS vs Traditional Care — Functional Recovery Graph (Line Graph)", [
        "<b>What the figure shows:</b> A line graph with 'Functional capacity' on the y-axis and time (Days to Weeks) on the x-axis. Two curves are compared after a 'Surgery' event marked on the x-axis.",
        "<b>Red solid line — Traditional care:</b> After surgery, functional capacity drops sharply into a deep, wide trough. It remains low for weeks before gradually recovering.",
        "<b>Red dashed line — Multimodal ERAS intervention:</b> After surgery, the drop in functional capacity is much shallower. The patient returns to baseline within days rather than weeks.",
        "<b>Simple message:</b> ERAS dramatically shortens the 'valley' of post-surgical dysfunction. Hospital stays after major surgery have been reduced by 30–50% using ERAS. The key is attacking all avoidable factors simultaneously — pain, starvation, immobility, excessive fluids.",
    ])
]))
story.append(sp(6))

story.append(green_box(
    "A Proactive ERAS Approach to Prevent Unnecessary Stress (Summary Box 1.9)",
    [
        "Minimal access techniques (laparoscopy, robotic surgery)",
        "Blockade of afferent painful stimuli (epidural, spinal, wound catheters)",
        "Minimal periods of starvation — early feeding",
        "Early mobilisation",
    ]
))
story.append(sp(10))

# ═══════════════════════════════════════════════════════════════════════════════
# FINAL SUMMARY TABLE
# ═══════════════════════════════════════════════════════════════════════════════
story.append(Paragraph("Quick Reference: The Complete Picture at a Glance", H1))
story.append(section_rule())

summary_data = [
    ["Phase", "Timing", "Key Features", "Hormones"],
    ["Catabolic Phase", "0–48 hours", "Low BP, low temp, low cardiac output, lactic acidosis, hyperglycaemia", "Catecholamines, Cortisol, Glucagon, Aldosterone"],
    ["Flow Phase / SIRS", "Days–weeks", "Hypermetabolism, fever, high cardiac output, muscle wasting, oedema", "All counter-regulatory hormones + cytokines"],
    ["Anabolic Phase", "Weeks", "Tissue repair, muscle rebuilding, weight regain", "Insulin, IGF-1, Growth Hormone"],
]

sum_table = Table(
    [[Paragraph(c, S("TH", parent="Normal",
        fontSize=9, leading=13,
        fontName="Helvetica-Bold" if r == 0 else "Helvetica",
        textColor=WHITE if r == 0 else TEXT_DARK,
        spaceAfter=0)) for c in row] for r, row in enumerate(summary_data)],
    colWidths=[3.5*cm, 2.8*cm, 6.8*cm, 4.6*cm],
    repeatRows=1,
)
sum_table.setStyle(TableStyle([
    ("BACKGROUND",   (0,0), (-1,0), DARK_BLUE),
    ("BACKGROUND",   (0,1), (-1,1), LIGHT_ORANGE),
    ("BACKGROUND",   (0,2), (-1,2), colors.HexColor("#FFF8F0")),
    ("BACKGROUND",   (0,3), (-1,3), LIGHT_BLUE),
    ("BOX",          (0,0), (-1,-1), 1, GREY_LINE),
    ("INNERGRID",    (0,0), (-1,-1), 0.5, GREY_LINE),
    ("TOPPADDING",   (0,0), (-1,-1), 6),
    ("BOTTOMPADDING",(0,0), (-1,-1), 6),
    ("LEFTPADDING",  (0,0), (-1,-1), 8),
    ("VALIGN",       (0,0), (-1,-1), "TOP"),
]))
story.append(sum_table)
story.append(sp(12))

# Hormone changes table
story.append(Paragraph("Hormone Changes During the Acute Injury Response", H2))
hormone_data = [
    ["Hormone / Mediator", "Direction", "Main Effect"],
    ["Cortisol", "INCREASES", "Gluconeogenesis, lipolysis, immunosuppression"],
    ["Adrenaline (Epinephrine)", "INCREASES", "Heart rate, glucose release, lipolysis"],
    ["Glucagon", "INCREASES", "Glycogenolysis, gluconeogenesis"],
    ["ACTH", "INCREASES", "Stimulates cortisol release from adrenal cortex"],
    ["Growth Hormone (GH)", "INCREASES", "Lipolysis, protein anabolism (paradoxically)"],
    ["IL-1, IL-6, TNF-alpha", "INCREASES", "Fever, acute-phase response, muscle wasting"],
    ["Insulin", "DECREASES", "Cells become resistant — hyperglycaemia results"],
    ["IGF-1", "DECREASES", "Reduced anabolic drive"],
    ["Testosterone", "DECREASES", "Reduced muscle synthesis"],
    ["T3 (Triiodothyronine)", "DECREASES", "Reduced thyroid drive (conserves energy?)"],
]
h_table = Table(
    [[Paragraph(c, S("HTH", parent="Normal",
        fontSize=9, leading=13,
        fontName="Helvetica-Bold" if r == 0 else "Helvetica",
        textColor=WHITE if r == 0 else TEXT_DARK,
        spaceAfter=0)) for c in row] for r, row in enumerate(hormone_data)],
    colWidths=[5.5*cm, 3.0*cm, 9.2*cm],
    repeatRows=1,
)
h_table.setStyle(TableStyle([
    ("BACKGROUND",   (0,0),  (-1,0),  DARK_ORANGE),
    ("BACKGROUND",   (0,1),  (-1,5),  LIGHT_ORANGE),
    ("BACKGROUND",   (0,6),  (-1,6),  colors.HexColor("#FFF0E0")),
    ("BACKGROUND",   (0,7),  (-1,-1), LIGHT_BLUE),
    ("BOX",          (0,0),  (-1,-1), 1, GREY_LINE),
    ("INNERGRID",    (0,0),  (-1,-1), 0.4, GREY_LINE),
    ("TOPPADDING",   (0,0),  (-1,-1), 5),
    ("BOTTOMPADDING",(0,0),  (-1,-1), 5),
    ("LEFTPADDING",  (0,0),  (-1,-1), 8),
    ("VALIGN",       (0,0),  (-1,-1), "TOP"),
    ("TEXTCOLOR",    (1,1),  (1,6),   colors.HexColor("#C0560A")),
    ("FONTNAME",     (1,1),  (1,6),   "Helvetica-Bold"),
    ("TEXTCOLOR",    (1,7),  (1,-1),  MID_BLUE),
    ("FONTNAME",     (1,7),  (1,-1),  "Helvetica-Bold"),
]))
story.append(h_table)
story.append(sp(10))

# ── Footer note ───────────────────────────────────────────────────────────────
story.append(sub_rule())
story.append(Paragraph(
    "<i>Source: Bailey &amp; Love's Short Practice of Surgery — Chapter 1: Metabolic Response to Injury. "
    "This document provides a simplified educational summary for study purposes.</i>",
    FIG_CAPTION))

# ── Build ─────────────────────────────────────────────────────────────────────
doc.build(story)
print(f"PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/metabolic-injury && python create_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/metabolic-injury/Metabolic_Response_to_Injury.pdf

The PDF was created successfully (32 KB). Let me mark the task complete and give you the full summary.Your PDF is ready for download:

Metabolic Response to Injury

PDF Document · PDF


Here is a summary of everything covered in plain language, exactly as structured in the PDF:

What is "Metabolic Response to Injury"?

When your body is injured - by surgery, trauma, sepsis, or burns - it launches an organised emergency programme. Every organ and hormone system shifts its priorities from normal function to survival and repair. This programme is the metabolic response to injury.

The 11 Sections in Your PDF

1. Introduction & Homeostasis

  • The body normally keeps a stable internal environment (homeostasis). Injury disrupts it.
  • The response has two phases: a catabolic (breakdown) phase, then an anabolic (rebuilding) phase.

2. The Magnitude of the Response

  • Figure 1.1 explained: Two graphs showing that more severe injury = higher metabolic rate + more urinary nitrogen loss (= more muscle breakdown). Major trauma peaks at 130–135% of normal metabolic rate. Starvation alone actually LOWERS the metabolic rate.

3. Tissue Damage & Inflammation

  • Damaged cells release DAMPs (danger signals). Immune cells detect them via Toll-like receptors.
  • This activates inflammasomes → caspases → cytokines (IL-1, IL-6, TNF-alpha, IL-8).
  • Unchecked, this becomes SIRS → MODS (organ failure, 25% mortality).

4. The Neuroendocrine Response

  • Figure 1.2 explained: A pathway diagram showing injury → nerve signals → hypothalamus → pituitary → cortisol + adrenaline + glucagon. Simultaneously, immune cytokines rise and insulin/IGF-1/testosterone/T3 all fall.
  • The result is an emergency fuel mobilisation system.

5. Metabolic Changes After Surgery & Trauma

  • Catabolic phase (0–48 hours): low BP, low temperature, high blood sugar, lactic acid.
  • Flow phase (days–weeks): hypermetabolism, fever, muscle wasting, fluid leakage into tissues.
  • The whole response is driven by IL-1, IL-6, and TNF-alpha.

6. Managing the Catabolic Stress Response

  • Figure 1.3 explained: An arrow diagram showing that the body deliberately transfers amino acids (especially glutamine and alanine) FROM muscle/fat/skin TO the liver, immune system, and wound. Muscle wasting is intentional — it is the body funding its repair programme.

7. Hypermetabolism & Muscle Wasting

  • Trauma patients burn 15–25% more energy than normal.
  • Figure 1.4 explained: A circular molecular diagram of the ubiquitin-proteasome system — the "shredder" that breaks muscle proteins into amino acids in steps: cut (caspases/calpains) → tag with ubiquitin (E1/E2/E3 enzymes + ATP) → feed into 26S proteasome → release amino acids. In severe sepsis, this destroys up to 500 g of muscle per day.

8. Liver Changes & Insulin Resistance

  • The liver switches from making albumin to making CRP, fibrinogen, and complement proteins.
  • Insulin resistance develops (like Type 2 diabetes) — cells ignore insulin, blood sugar stays high.

9. Body Composition Changes

  • Figure 1.5 explained: A stacked bar showing that a 70 kg man has ~13 kg fat, ~12 kg protein, ~42 L water, ~3 kg minerals. The protein (muscle) reserve is what gets raided during catabolism.
  • Figure 1.6 explained: Three curves showing different weight trajectories: sepsis patients gain fluid weight first then crash; surgical patients lose weight then recover; starvation patients steadily lose weight.

10. Avoidable Factors

  • Figure 1.7 explained: A flowchart showing that pain, hypothermia, immobility, starvation, bleeding, and low blood pressure all amplify the catabolic response by activating the sympathetic system and cytokine cascade simultaneously. Fix these = better survival.

11. Enhanced Recovery After Surgery (ERAS)

  • Figure 1.8 explained: Two recovery curves showing that ERAS (minimal access surgery + epidural pain control + early feeding + early mobilisation) produces a much shallower dip in functional capacity and recovery in days instead of weeks. Hospital stay reduced by 30–50%.

The PDF includes two colour-coded reference tables at the end: one summarising the three phases of the response, and one listing every hormone with its direction and effect.

Quick reference pdf of this

I dont know about Metabolic response to injury. I want to easily understand about this topic in easy language with flowsheet and with diagram also. Provide me a pdf that contains all the topic along with diagram and flowsheet diagram

I'll create a comprehensive PDF with flowcharts and diagrams built directly into it using ReportLab's drawing tools. Let me build this now.
Writing File

~/metabolic-injury/quick_ref_pdf.py

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

OUTPUT = "/home/daytona/workspace/metabolic-injury/Metabolic_Response_QuickRef.pdf"

# ── Colour Palette ────────────────────────────────────────────────────────────
C_ORANGE_DARK  = colors.HexColor("#C0560A")
C_ORANGE_MID   = colors.HexColor("#E07020")
C_ORANGE_LIGHT = colors.HexColor("#FFF0E0")
C_ORANGE_BG    = colors.HexColor("#FDE8D0")
C_BLUE_DARK    = colors.HexColor("#1A3A5C")
C_BLUE_MID     = colors.HexColor("#2980B9")
C_BLUE_LIGHT   = colors.HexColor("#E8F4FD")
C_BLUE_BG      = colors.HexColor("#D0E8F8")
C_GREEN_DARK   = colors.HexColor("#1A6B3A")
C_GREEN_MID    = colors.HexColor("#27AE60")
C_GREEN_LIGHT  = colors.HexColor("#E8F8EE")
C_RED_DARK     = colors.HexColor("#8B0000")
C_RED_MID      = colors.HexColor("#C0392B")
C_RED_LIGHT    = colors.HexColor("#FDECEA")
C_PURPLE_DARK  = colors.HexColor("#5B2C8D")
C_PURPLE_MID   = colors.HexColor("#8E44AD")
C_PURPLE_LIGHT = colors.HexColor("#F3E8FF")
C_YELLOW_DARK  = colors.HexColor("#8B6914")
C_YELLOW_MID   = colors.HexColor("#F39C12")
C_YELLOW_LIGHT = colors.HexColor("#FEF9E7")
C_TEAL_DARK    = colors.HexColor("#0E6655")
C_TEAL_MID     = colors.HexColor("#17A589")
C_TEAL_LIGHT   = colors.HexColor("#E8F8F5")
C_GREY         = colors.HexColor("#95A5A6")
C_GREY_LIGHT   = colors.HexColor("#F2F3F4")
C_WHITE        = colors.white
C_BLACK        = colors.HexColor("#2C2C2C")
C_DARK_BG      = colors.HexColor("#1C2833")

# ── Document ──────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT, pagesize=A4,
    leftMargin=1.5*cm, rightMargin=1.5*cm,
    topMargin=1.8*cm, bottomMargin=1.8*cm,
    title="Metabolic Response to Injury — Quick Reference Guide",
)
PW = A4[0] - 3*cm  # usable page width

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

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

ST_MAIN_TITLE = PS("MT", fontSize=22, leading=28, textColor=C_WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER, spaceAfter=2)
ST_MAIN_SUB   = PS("MS", fontSize=11, leading=16, textColor=colors.HexColor("#FFD9AA"),
    fontName="Helvetica", alignment=TA_CENTER)
ST_H1 = PS("H1", fontSize=14, leading=19, textColor=C_ORANGE_DARK,
    fontName="Helvetica-Bold", spaceBefore=12, spaceAfter=3)
ST_H2 = PS("H2", fontSize=11.5, leading=16, textColor=C_BLUE_DARK,
    fontName="Helvetica-Bold", spaceBefore=8, spaceAfter=2)
ST_H3 = PS("H3", fontSize=10, leading=14, textColor=C_BLUE_DARK,
    fontName="Helvetica-Bold", spaceBefore=5, spaceAfter=2)
ST_BODY = PS("BD", fontSize=9.5, leading=14, textColor=C_BLACK,
    fontName="Helvetica", spaceAfter=4, alignment=TA_JUSTIFY)
ST_BULLET = PS("BU", fontSize=9.5, leading=13, textColor=C_BLACK,
    fontName="Helvetica", spaceAfter=2, leftIndent=14, firstLineIndent=-10)
ST_SMALL = PS("SM", fontSize=8.5, leading=12, textColor=colors.HexColor("#555"),
    fontName="Helvetica", spaceAfter=2, alignment=TA_JUSTIFY)
ST_CAP = PS("CA", fontSize=8, leading=11, textColor=C_PURPLE_DARK,
    fontName="Helvetica-Oblique", spaceAfter=4, alignment=TA_CENTER)
ST_TH = PS("TH", fontSize=9, leading=12, textColor=C_WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER)
ST_TD = PS("TD", fontSize=9, leading=13, textColor=C_BLACK,
    fontName="Helvetica", alignment=TA_LEFT)
ST_TD_C = PS("TDC", fontSize=9, leading=13, textColor=C_BLACK,
    fontName="Helvetica", alignment=TA_CENTER)
ST_BADGE = PS("BG", fontSize=8, leading=10, textColor=C_WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER)

def sp(n=6): return Spacer(1, n)
def hr(color=C_ORANGE_DARK, t=1.5): return HRFlowable(width="100%", thickness=t, color=color, spaceAfter=4, spaceBefore=6)
def b(txt, s=ST_BULLET): return Paragraph(f"• {txt}", s)

# ── Coloured Box helper ───────────────────────────────────────────────────────
def cbox(content_items, bg=C_ORANGE_LIGHT, border=C_ORANGE_DARK, width=None, padding=10):
    w = width or PW
    inner = []
    for item in content_items:
        if isinstance(item, str):
            inner.append(Paragraph(item, ST_SMALL))
        else:
            inner.append(item)
    t = Table([[inner]], colWidths=[w])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), bg),
        ("BOX",           (0,0),(-1,-1), 1.5, border),
        ("TOPPADDING",    (0,0),(-1,-1), padding),
        ("BOTTOMPADDING", (0,0),(-1,-1), padding),
        ("LEFTPADDING",   (0,0),(-1,-1), padding),
        ("RIGHTPADDING",  (0,0),(-1,-1), padding),
    ]))
    return t

# ══════════════════════════════════════════════════════════════════════════════
# DRAWING HELPERS — build ReportLab Graphics
# ══════════════════════════════════════════════════════════════════════════════

def arrow_right(d, x, y, length=30, color=C_GREY):
    """Draw a rightward arrow."""
    d.add(Line(x, y, x+length-8, y, strokeColor=color, strokeWidth=2))
    d.add(Polygon([x+length-8, y+5, x+length, y, x+length-8, y-5],
                  fillColor=color, strokeColor=color, strokeWidth=0))

def arrow_down(d, x, y, length=25, color=C_GREY):
    d.add(Line(x, y, x, y-length+7, strokeColor=color, strokeWidth=2))
    d.add(Polygon([x-5, y-length+7, x, y-length, x+5, y-length+7],
                  fillColor=color, strokeColor=color, strokeWidth=0))

def rounded_box(d, x, y, w, h, bg, border, radius=6):
    d.add(Rect(x, y, w, h, rx=radius, ry=radius,
               fillColor=bg, strokeColor=border, strokeWidth=1.5))

def label_in_box(d, x, y, w, h, lines, font="Helvetica-Bold", size=8,
                 color=C_BLACK, bg=None, border=None, radius=5):
    if bg:
        d.add(Rect(x, y, w, h, rx=radius, ry=radius,
                   fillColor=bg, strokeColor=border or bg, strokeWidth=1.2))
    cx = x + w/2
    total_h = len(lines)*size*1.3
    start_y = y + h/2 + total_h/2 - size*0.9
    for i, line in enumerate(lines):
        d.add(String(cx, start_y - i*size*1.3, line,
                     fontSize=size, fontName=font,
                     fillColor=color, textAnchor="middle"))

# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 1 — Phases of Metabolic Response (Timeline)
# ══════════════════════════════════════════════════════════════════════════════
class PhasesTimelineDiagram(Flowable):
    def __init__(self, width=PW, height=110):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        d = self
        W, H = self.width, self.height

        # Background
        d.canv.setFillColor(C_GREY_LIGHT)
        d.canv.rect(0, 0, W, H, fill=1, stroke=0)

        # Title
        d.canv.setFillColor(C_BLUE_DARK)
        d.canv.setFont("Helvetica-Bold", 10)
        d.canv.drawCentredString(W/2, H-14, "PHASES OF THE METABOLIC RESPONSE TO INJURY")

        # Timeline arrow
        tl_y = 52
        tl_x0, tl_x1 = 20, W-20
        d.canv.setStrokeColor(C_GREY)
        d.canv.setLineWidth(2)
        d.canv.line(tl_x0, tl_y, tl_x1-10, tl_y)
        d.canv.setFillColor(C_GREY)
        d.canv.polygon([tl_x1-10, tl_y+5, tl_x1, tl_y, tl_x1-10, tl_y-5], fill=1, stroke=0)
        d.canv.setFont("Helvetica-Bold", 8)
        d.canv.drawRightString(W-5, tl_y-3, "TIME")

        # Phase boxes
        phases = [
            (tl_x0, 90, "INJURY",       ["0h"],           C_RED_MID,    C_WHITE),
            (tl_x0+10, 72, "CATABOLIC PHASE", ["0-48 hrs"],  C_ORANGE_MID, C_WHITE),
            (tl_x0+90, 72, "FLOW PHASE / SIRS",["Days–Weeks"], C_PURPLE_MID, C_WHITE),
            (tl_x0+195, 72, "ANABOLIC PHASE", ["Weeks"],    C_GREEN_MID,  C_WHITE),
        ]

        # Draw injury marker
        d.canv.setFillColor(C_RED_MID)
        d.canv.circle(tl_x0, tl_y, 6, fill=1, stroke=0)
        d.canv.setFillColor(C_WHITE)
        d.canv.setFont("Helvetica-Bold", 6)
        d.canv.drawCentredString(tl_x0, tl_y-2, "!")

        # Catabolic box
        bx1 = tl_x0+12; bw1 = 75
        d.canv.setFillColor(C_ORANGE_MID)
        d.canv.roundRect(bx1, tl_y+6, bw1, 26, 4, fill=1, stroke=0)
        d.canv.setFillColor(C_WHITE)
        d.canv.setFont("Helvetica-Bold", 8)
        d.canv.drawCentredString(bx1+bw1/2, tl_y+22, "CATABOLIC")
        d.canv.setFont("Helvetica", 7)
        d.canv.drawCentredString(bx1+bw1/2, tl_y+12, "Phase 1  |  0–48 hours")

        # Below catabolic
        d.canv.setFillColor(C_ORANGE_DARK)
        d.canv.setFont("Helvetica", 7)
        features1 = ["Low BP • Low temp • Lactic acidosis", "Hyperglycaemia • Low metabolic rate"]
        for i, f in enumerate(features1):
            d.canv.drawCentredString(bx1+bw1/2, tl_y - 10 - i*9, f)

        # Flow phase box
        bx2 = bx1+bw1+8; bw2 = 105
        d.canv.setFillColor(C_PURPLE_MID)
        d.canv.roundRect(bx2, tl_y+6, bw2, 26, 4, fill=1, stroke=0)
        d.canv.setFillColor(C_WHITE)
        d.canv.setFont("Helvetica-Bold", 8)
        d.canv.drawCentredString(bx2+bw2/2, tl_y+22, "FLOW / SIRS PHASE")
        d.canv.setFont("Helvetica", 7)
        d.canv.drawCentredString(bx2+bw2/2, tl_y+12, "Phase 2  |  Days to Weeks")

        d.canv.setFillColor(C_PURPLE_DARK)
        d.canv.setFont("Helvetica", 7)
        features2 = ["Hypermetabolism • Fever • High cardiac output", "Muscle wasting • Oedema • Leukocytosis"]
        for i, f in enumerate(features2):
            d.canv.drawCentredString(bx2+bw2/2, tl_y - 10 - i*9, f)

        # Anabolic box
        bx3 = bx2+bw2+8; bw3 = W - bx3 - 25
        d.canv.setFillColor(C_GREEN_MID)
        d.canv.roundRect(bx3, tl_y+6, bw3, 26, 4, fill=1, stroke=0)
        d.canv.setFillColor(C_WHITE)
        d.canv.setFont("Helvetica-Bold", 8)
        d.canv.drawCentredString(bx3+bw3/2, tl_y+22, "ANABOLIC")
        d.canv.setFont("Helvetica", 7)
        d.canv.drawCentredString(bx3+bw3/2, tl_y+12, "Phase 3  |  Weeks")

        d.canv.setFillColor(C_GREEN_DARK)
        d.canv.setFont("Helvetica", 7)
        features3 = ["Tissue repair • Weight regain", "Anabolism restored"]
        for i, f in enumerate(features3):
            d.canv.drawCentredString(bx3+bw3/2, tl_y - 10 - i*9, f)

        # Tick marks on timeline
        ticks = [(tl_x0, "0"), (bx1+bw1, "48h"), (bx2+bw2, "Days"), (bx3+bw3, "Wks")]
        for tx, lbl in ticks:
            d.canv.setStrokeColor(C_GREY)
            d.canv.setLineWidth(1)
            d.canv.line(tx, tl_y-3, tx, tl_y+3)
            d.canv.setFillColor(C_GREY)
            d.canv.setFont("Helvetica", 6.5)
            d.canv.drawCentredString(tx, tl_y-11, lbl)


# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 2 — Injury → Response Flowchart (full cascade)
# ══════════════════════════════════════════════════════════════════════════════
class InjuryCascadeFlowchart(Flowable):
    def __init__(self, width=PW, height=340):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def _box(self, x, y, w, h, bg, border, lines, fsize=8, bold=True,
             tcol=C_WHITE, radius=5):
        c = self.canv
        c.setFillColor(bg)
        c.setStrokeColor(border)
        c.setLineWidth(1.3)
        c.roundRect(x, y, w, h, radius, fill=1, stroke=1)
        fn = "Helvetica-Bold" if bold else "Helvetica"
        total = len(lines)*fsize*1.25
        start = y + h/2 + total/2 - fsize*0.9
        c.setFillColor(tcol)
        for i, ln in enumerate(lines):
            c.setFont(fn, fsize)
            c.drawCentredString(x+w/2, start - i*fsize*1.3, ln)

    def _arr_down(self, x, y, length=20, col=C_GREY):
        c = self.canv
        c.setStrokeColor(col); c.setFillColor(col); c.setLineWidth(1.5)
        c.line(x, y, x, y-length+6)
        c.polygon([x-4, y-length+6, x, y-length, x+4, y-length+6], fill=1, stroke=0)

    def _arr_right(self, x, y, length=25, col=C_GREY):
        c = self.canv
        c.setStrokeColor(col); c.setFillColor(col); c.setLineWidth(1.5)
        c.line(x, y, x+length-6, y)
        c.polygon([x+length-6, y+4, x+length, y, x+length-6, y-4], fill=1, stroke=0)

    def _arr_left(self, x, y, length=25, col=C_GREY):
        c = self.canv
        c.setStrokeColor(col); c.setFillColor(col); c.setLineWidth(1.5)
        c.line(x, y, x-length+6, y)
        c.polygon([x-length+6, y+4, x-length, y, x-length+6, y-4], fill=1, stroke=0)

    def draw(self):
        c = self.canv
        W, H = self.width, self.height

        # Background
        c.setFillColor(colors.HexColor("#FAFAFA"))
        c.rect(0, 0, W, H, fill=1, stroke=0)
        c.setStrokeColor(C_BLUE_DARK); c.setLineWidth(1)
        c.rect(0, 0, W, H, fill=0, stroke=1)

        # Title
        c.setFillColor(C_BLUE_DARK); c.setFont("Helvetica-Bold", 10)
        c.drawCentredString(W/2, H-14, "INJURY RESPONSE CASCADE — COMPLETE FLOWCHART")

        # ── Row 1: INJURY (top centre) ────────────────────────────────────────
        r1y = H-38; bw = 90; bh = 22; cx = W/2
        self._box(cx-bw/2, r1y, bw, bh, C_RED_MID, C_RED_DARK,
                  ["INJURY / SURGERY"], fsize=9)

        # ── Row 2: Two parallel pathways ─────────────────────────────────────
        r2y = r1y - 55
        # Nervous system path (left)
        lx = 30; lw = 130; lh = 38
        self._box(lx, r2y, lw, lh, C_BLUE_MID, C_BLUE_DARK,
                  ["NERVOUS SYSTEM", "Pain signals → Spinal cord", "→ Hypothalamus"], fsize=7.5)
        # Immune path (right)
        rx = W-30-130; rw = 130; rh = 38
        self._box(rx, r2y, rw, rh, C_ORANGE_MID, C_ORANGE_DARK,
                  ["IMMUNE SYSTEM", "DAMPs released from", "damaged cells"], fsize=7.5)

        # Arrows from INJURY to both
        # Left arrow (diagonal down-left)
        c.setStrokeColor(C_GREY); c.setLineWidth(1.5)
        c.line(cx, r1y, lx+lw/2, r2y+rh+2)
        c.setFillColor(C_GREY)
        c.polygon([lx+lw/2-4, r2y+rh+2, lx+lw/2, r2y+rh-4, lx+lw/2+4, r2y+rh+2],
                  fill=1, stroke=0)
        # Right arrow
        c.setStrokeColor(C_GREY); c.setLineWidth(1.5)
        c.line(cx, r1y, rx+rw/2, r2y+rh+2)
        c.polygon([rx+rw/2-4, r2y+rh+2, rx+rw/2, r2y+rh-4, rx+rw/2+4, r2y+rh+2],
                  fill=1, stroke=0)

        # ── Row 3: Neuroendocrine (left) and Cytokines (right) ───────────────
        r3y = r2y - 65
        # Neuroendocrine box
        ne_x = 10; ne_w = 160; ne_h = 54
        self._box(ne_x, r3y, ne_w, ne_h, C_BLUE_DARK, C_BLUE_DARK,
                  ["NEUROENDOCRINE RESPONSE",
                   "CRF → ACTH → Cortisol ↑",
                   "Sympathetic → Adrenaline ↑",
                   "Pancreas → Glucagon ↑",
                   "Insulin ↓  IGF-1 ↓  T3 ↓"], fsize=7.5)
        self._arr_down(lx+lw/2, r2y, length=r2y-r3y-ne_h+2, col=C_BLUE_MID)

        # Cytokine box (right)
        cy_x = W-10-160; cy_w = 160; cy_h = 54
        self._box(cy_x, r3y, cy_w, cy_h, C_ORANGE_DARK, C_ORANGE_DARK,
                  ["INFLAMMATORY MEDIATORS",
                   "DAMPs → PRRs → Inflammasome",
                   "→ Caspases activated",
                   "IL-1 ↑  IL-6 ↑  IL-8 ↑",
                   "TNF-α ↑  Nitric Oxide ↑"], fsize=7.5)
        self._arr_down(rx+rw/2, r2y, length=r2y-r3y-cy_h+2, col=C_ORANGE_MID)

        # Bidirectional arrow between them
        mid_y = r3y + ne_h/2
        c.setStrokeColor(C_PURPLE_MID); c.setLineWidth(1.5)
        c.line(ne_x+ne_w+4, mid_y, cy_x-4, mid_y)
        # arrowheads both ways
        c.setFillColor(C_PURPLE_MID)
        c.polygon([ne_x+ne_w+4, mid_y+3, ne_x+ne_w-2, mid_y, ne_x+ne_w+4, mid_y-3], fill=1, stroke=0)
        c.polygon([cy_x-4, mid_y+3, cy_x+2, mid_y, cy_x-4, mid_y-3], fill=1, stroke=0)
        c.setFillColor(C_PURPLE_DARK); c.setFont("Helvetica-Bold", 6.5)
        c.drawCentredString(W/2, mid_y+4, "INTERACT")

        # ── Row 4: Combined effects (centre box) ─────────────────────────────
        r4y = r3y - 55
        ce_w = 280; ce_h = 44; ce_x = W/2 - ce_w/2
        self._box(ce_x, r4y, ce_w, ce_h, C_PURPLE_MID, C_PURPLE_DARK,
                  ["COMBINED METABOLIC EFFECTS",
                   "Hyperglycaemia • Pyrexia • Insulin resistance",
                   "Fat mobilisation • Muscle protein breakdown",
                   "Acute-phase protein synthesis in liver"], fsize=7.5)

        # Arrows from NE and Cytokines down to combined
        c.setStrokeColor(C_GREY); c.setLineWidth(1.5)
        c.line(ne_x+ne_w/2, r3y, ce_x+30, r4y+ce_h)
        c.setFillColor(C_GREY)
        c.polygon([ce_x+26, r4y+ce_h, ce_x+30, r4y+ce_h+5, ce_x+34, r4y+ce_h], fill=1, stroke=0)
        c.setStrokeColor(C_GREY); c.setLineWidth(1.5)
        c.line(cy_x+cy_w/2, r3y, ce_x+ce_w-30, r4y+ce_h)
        c.polygon([ce_x+ce_w-34, r4y+ce_h, ce_x+ce_w-30, r4y+ce_h+5, ce_x+ce_w-26, r4y+ce_h],
                  fill=1, stroke=0)

        # ── Row 5: Four outcome boxes ─────────────────────────────────────────
        r5y = r4y - 62
        out_w = (W-50)/4 - 5; out_h = 52
        outcomes = [
            (C_RED_MID, C_RED_DARK,
             ["CATABOLISM", "• Muscle wasting", "• Fat breakdown", "• Weight loss", "• Nitrogen loss"]),
            (C_ORANGE_MID, C_ORANGE_DARK,
             ["HYPERMETABOLISM", "• ↑ O₂ consumption", "• ↑ CO₂ production", "• ↑ Heart rate", "• Fever"]),
            (C_TEAL_MID, C_TEAL_DARK,
             ["IMMUNOSUPPRESSION", "• ↓ T-cell function", "• Risk of sepsis", "• MODS risk", "• Opportunistic infxn"]),
            (C_YELLOW_MID, C_YELLOW_DARK,
             ["FLUID SHIFTS", "• Capillary leakage", "• Tissue oedema", "• ↓ Albumin", "• Weight gain (fluid)"]),
        ]
        for i, (bg, bd, lines) in enumerate(outcomes):
            ox = 15 + i*(out_w+8)
            self._box(ox, r5y, out_w, out_h, bg, bd, lines, fsize=7, bold=False)
            # Arrow from combined box down
            arr_x = ox + out_w/2
            c.setStrokeColor(C_GREY); c.setLineWidth(1.2)
            c.line(max(ce_x+15, min(arr_x, ce_x+ce_w-15)), r4y,
                   arr_x, r5y+out_h+2)
            c.setFillColor(C_GREY)
            c.polygon([arr_x-3, r5y+out_h+2, arr_x, r5y+out_h-3, arr_x+3, r5y+out_h+2],
                      fill=1, stroke=0)

        # ── Row 6: Worst case ─────────────────────────────────────────────────
        r6y = r5y - 38
        wc_w = 200; wc_h = 28; wc_x = W/2-wc_w/2
        self._box(wc_x, r6y, wc_w, wc_h, C_RED_DARK, C_RED_DARK,
                  ["IF UNCONTROLLED → SIRS → MODS → DEATH",
                   "Mortality ~25% with established MODS"], fsize=7.5)
        # Arrow down
        self._arr_down(W/2, r5y, length=r5y-r6y-wc_h+2, col=C_RED_MID)

        # ── Row 7: Treatment / ERAS ───────────────────────────────────────────
        r7y = r6y - 38
        tx_w = 250; tx_h = 28; tx_x = W/2-tx_w/2
        self._box(tx_x, r7y, tx_w, tx_h, C_GREEN_MID, C_GREEN_DARK,
                  ["TREATMENT GOAL: Restore Homeostasis",
                   "ERAS • Minimal surgery • Pain control • Early feeding • Mobilisation"], fsize=7.5)
        # Counter arrow (upward, represents treatment fighting the cascade)
        c.setStrokeColor(C_GREEN_MID); c.setLineWidth(2)
        c.line(W-18, r7y+tx_h/2, W-18, r5y+out_h/2)
        c.setFillColor(C_GREEN_MID)
        c.polygon([W-22, r5y+out_h/2, W-18, r5y+out_h/2+6, W-14, r5y+out_h/2], fill=1, stroke=0)
        c.setFont("Helvetica-Bold", 6.5); c.setFillColor(C_GREEN_DARK)
        c.saveState()
        c.translate(W-10, (r7y+tx_h/2+r5y+out_h/2)/2)
        c.rotate(90)
        c.drawCentredString(0, 0, "TREATMENT")
        c.restoreState()


# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 3 — Neuroendocrine Pathway (simplified)
# ══════════════════════════════════════════════════════════════════════════════
class NeuroendocrineDiagram(Flowable):
    def __init__(self, width=PW, height=200):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        c = self.canv
        W, H = self.width, self.height

        c.setFillColor(C_BLUE_LIGHT)
        c.rect(0, 0, W, H, fill=1, stroke=0)
        c.setStrokeColor(C_BLUE_DARK); c.setLineWidth(0.8)
        c.rect(0, 0, W, H, fill=0, stroke=1)

        c.setFillColor(C_BLUE_DARK); c.setFont("Helvetica-Bold", 9.5)
        c.drawCentredString(W/2, H-13, "NEUROENDOCRINE RESPONSE — STEP BY STEP")

        # Draw brain (simple oval)
        bx, by, bw, bh = W/2-35, H-85, 70, 45
        c.setFillColor(colors.HexColor("#FFD8B1"))
        c.setStrokeColor(C_ORANGE_DARK); c.setLineWidth(1.5)
        c.ellipse(bx, by, bx+bw, by+bh, fill=1, stroke=1)
        c.setFillColor(C_BLUE_DARK); c.setFont("Helvetica-Bold", 7)
        c.drawCentredString(bx+bw/2, by+bh/2+5, "HYPOTHALAMUS")
        c.setFont("Helvetica", 6.5)
        c.drawCentredString(bx+bw/2, by+bh/2-5, "releases CRF ↓")

        # Pituitary (small circle below brain)
        px, py = W/2, H-105
        c.setFillColor(colors.HexColor("#B8E4FF"))
        c.setStrokeColor(C_BLUE_MID); c.setLineWidth(1.2)
        c.circle(px, py, 14, fill=1, stroke=1)
        c.setFillColor(C_BLUE_DARK); c.setFont("Helvetica-Bold", 6)
        c.drawCentredString(px, py+3, "PITUITARY")
        c.setFont("Helvetica", 5.5)
        c.drawCentredString(px, py-5, "ACTH + GH ↑")

        # Arrow brain → pituitary
        c.setStrokeColor(C_BLUE_MID); c.setFillColor(C_BLUE_MID); c.setLineWidth(1.5)
        c.line(px, by-2, px, py+16)
        c.polygon([px-3, py+16, px, py+10, px+3, py+16], fill=1, stroke=0)

        # Left branch: Adrenal gland
        ax, ay = 60, H-148
        c.setFillColor(colors.HexColor("#FFE0CC"))
        c.setStrokeColor(C_ORANGE_DARK); c.setLineWidth(1.2)
        c.roundRect(ax, ay, 75, 32, 4, fill=1, stroke=1)
        c.setFillColor(C_ORANGE_DARK); c.setFont("Helvetica-Bold", 7)
        c.drawCentredString(ax+37, ay+22, "ADRENAL GLAND")
        c.setFont("Helvetica", 6.5)
        c.drawCentredString(ax+37, ay+12, "Cortisol ↑  Adrenaline ↑")

        # Arrow pituitary → adrenal
        c.setStrokeColor(C_ORANGE_MID); c.setFillColor(C_ORANGE_MID); c.setLineWidth(1.3)
        c.line(px-14, py-10, ax+75, ay+16)
        c.polygon([ax+71, ay+12, ax+75, ay+18, ax+79, ay+12], fill=1, stroke=0)

        # Right branch: Pancreas
        panx, pany = W-140, H-148
        c.setFillColor(colors.HexColor("#E0FFE8"))
        c.setStrokeColor(C_GREEN_DARK); c.setLineWidth(1.2)
        c.roundRect(panx, pany, 80, 32, 4, fill=1, stroke=1)
        c.setFillColor(C_GREEN_DARK); c.setFont("Helvetica-Bold", 7)
        c.drawCentredString(panx+40, pany+22, "PANCREAS")
        c.setFont("Helvetica", 6.5)
        c.drawCentredString(panx+40, pany+12, "Glucagon ↑  Insulin ↓")

        # Arrow pituitary → pancreas (via sympathetic)
        c.setStrokeColor(C_GREEN_MID); c.setFillColor(C_GREEN_MID); c.setLineWidth(1.3)
        c.line(px+14, py-10, panx, pany+16)
        c.polygon([panx-4, pany+12, panx, pany+18, panx+4, pany+12], fill=1, stroke=0)

        # Injury signal (bottom left)
        inj_x, inj_y = 30, 45
        # Draw starburst
        c.setFillColor(C_RED_MID); c.setFont("Helvetica-Bold", 9)
        c.drawCentredString(inj_x+15, inj_y, "INJURY")
        c.setFillColor(C_RED_DARK); c.setFont("Helvetica", 7)
        c.drawCentredString(inj_x+15, inj_y-10, "Pain signals")

        # Arrow injury → hypothalamus (upward left)
        c.setStrokeColor(C_RED_MID); c.setFillColor(C_RED_MID); c.setLineWidth(1.5)
        c.line(inj_x+15, inj_y+10, bx+10, by+2)
        c.polygon([bx+6, by+6, bx+10, by-2, bx+14, by+6], fill=1, stroke=0)
        # Label
        c.setFont("Helvetica-Oblique", 6); c.setFillColor(C_RED_DARK)
        c.drawString(35, 80, "Nerve signals")
        c.drawString(35, 71, "(spinal cord)")

        # Effects boxes at bottom
        eff_y = 8
        effects = [
            (15,   90, C_ORANGE_LIGHT, C_ORANGE_DARK, ["Cortisol", "Glucose ↑", "Fat breakdown"]),
            (115,  90, C_RED_LIGHT,    C_RED_DARK,     ["Adrenaline", "Heart rate ↑", "BP ↑"]),
            (215,  90, C_GREEN_LIGHT,  C_GREEN_DARK,   ["Glucagon", "Liver glucose", "output ↑"]),
            (315,  90, C_BLUE_LIGHT,   C_BLUE_DARK,    ["GH + ACTH", "Lipolysis", "Protein breakdown"]),
        ]
        for ex, ew, bg, bd, lns in effects:
            c.setFillColor(bg); c.setStrokeColor(bd); c.setLineWidth(1)
            c.roundRect(ex, eff_y, ew, 30, 3, fill=1, stroke=1)
            c.setFillColor(bd); c.setFont("Helvetica-Bold", 6.5)
            c.drawCentredString(ex+ew/2, eff_y+22, lns[0])
            c.setFont("Helvetica", 6)
            c.drawCentredString(ex+ew/2, eff_y+14, lns[1])
            c.drawCentredString(ex+ew/2, eff_y+6, lns[2])

        # Arrows from adrenal/pancreas down to effects
        for sx, sy, ex2, ey2 in [
            (ax+20, ay, 15+45, eff_y+30),
            (ax+55, ay, 115+45, eff_y+30),
            (panx+20, pany, 215+45, eff_y+30),
            (panx+60, pany, 315+45, eff_y+30),
        ]:
            c.setStrokeColor(C_GREY); c.setFillColor(C_GREY); c.setLineWidth(1)
            c.line(sx, sy, ex2, ey2+2)
            c.polygon([ex2-3, ey2+2, ex2, ey2-4, ex2+3, ey2+2], fill=1, stroke=0)


# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 4 — Ubiquitin-Proteasome Pathway
# ══════════════════════════════════════════════════════════════════════════════
class UbiquitinDiagram(Flowable):
    def __init__(self, width=PW, height=160):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        c = self.canv
        W, H = self.width, self.height

        c.setFillColor(C_PURPLE_LIGHT)
        c.rect(0, 0, W, H, fill=1, stroke=0)
        c.setStrokeColor(C_PURPLE_DARK); c.setLineWidth(0.8)
        c.rect(0, 0, W, H, fill=0, stroke=1)

        c.setFillColor(C_PURPLE_DARK); c.setFont("Helvetica-Bold", 9.5)
        c.drawCentredString(W/2, H-13, "MUSCLE PROTEIN BREAKDOWN: UBIQUITIN-PROTEASOME PATHWAY")

        # Step boxes (horizontal flow)
        steps = [
            (12,  45, 90, 55, C_RED_LIGHT,    C_RED_MID,
             ["STEP 1", "MUSCLE PROTEIN", "Caspases / Calpains", "cut protein into", "fragments"]),
            (118, 45, 90, 55, C_ORANGE_LIGHT,  C_ORANGE_MID,
             ["STEP 2", "TAGGING", "Ubiquitin attached", "(E1 + E2 + E3", "enzymes + ATP)"]),
            (224, 45, 90, 55, C_YELLOW_LIGHT,  C_YELLOW_MID,
             ["STEP 3", "26S PROTEASOME", "Barrel-shaped machine", "grinds protein", "using ATP"]),
            (330, 45, 90, 55, C_GREEN_LIGHT,   C_GREEN_MID,
             ["STEP 4", "AMINO ACIDS", "Released into blood", "→ Used by liver,", "immune cells, wound"]),
        ]
        for sx, sy, sw, sh, bg, bd, lns in steps:
            c.setFillColor(bg); c.setStrokeColor(bd); c.setLineWidth(1.5)
            c.roundRect(sx, sy, sw, sh, 5, fill=1, stroke=1)
            c.setFillColor(bd); c.setFont("Helvetica-Bold", 7.5)
            c.drawCentredString(sx+sw/2, sy+sh-10, lns[0])
            c.setFillColor(C_BLACK); c.setFont("Helvetica-Bold", 7)
            c.drawCentredString(sx+sw/2, sy+sh-20, lns[1])
            c.setFont("Helvetica", 6.5)
            for i, ln in enumerate(lns[2:]):
                c.drawCentredString(sx+sw/2, sy+sh-31-i*9, ln)

        # Arrows between steps
        for ax2 in [108, 214, 320]:
            c.setStrokeColor(C_GREY); c.setFillColor(C_GREY); c.setLineWidth(2)
            c.line(ax2, 72, ax2+4, 72)
            c.polygon([ax2+4, 76, ax2+10, 72, ax2+4, 68], fill=1, stroke=0)

        # Bottom note
        c.setFillColor(C_RED_DARK); c.setFont("Helvetica-Bold", 7.5)
        c.drawCentredString(W/2, 30,
            "In severe sepsis: up to 500 g of skeletal muscle destroyed per day!")
        c.setFillColor(C_BLACK); c.setFont("Helvetica", 7)
        c.drawCentredString(W/2, 19,
            "Cannot be stopped by nutrition alone — treating infection is essential.")
        c.setFillColor(C_ORANGE_DARK); c.setFont("Helvetica-Bold", 7)
        c.drawCentredString(W/2, 8,
            "ATP = energy fuel  •  E1/E2/E3 = tagging enzymes  •  Ubiquitin = 'delete me' tag")


# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 5 — Resource Reprioritisation
# ══════════════════════════════════════════════════════════════════════════════
class ResourceFlowDiagram(Flowable):
    def __init__(self, width=PW, height=140):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        c = self.canv
        W, H = self.width, self.height

        c.setFillColor(C_TEAL_LIGHT)
        c.rect(0, 0, W, H, fill=1, stroke=0)
        c.setStrokeColor(C_TEAL_DARK); c.setLineWidth(0.8)
        c.rect(0, 0, W, H, fill=0, stroke=1)

        c.setFillColor(C_TEAL_DARK); c.setFont("Helvetica-Bold", 9.5)
        c.drawCentredString(W/2, H-13, "RESOURCE REPRIORITISATION DURING INJURY")

        # Left column: Peripheral (donor) tissues
        donor_x = 10; donor_w = 115
        c.setFillColor(C_RED_LIGHT); c.setStrokeColor(C_RED_MID); c.setLineWidth(1.2)
        c.roundRect(donor_x, 20, donor_w, 95, 5, fill=1, stroke=1)
        c.setFillColor(C_RED_DARK); c.setFont("Helvetica-Bold", 8)
        c.drawCentredString(donor_x+donor_w/2, 105, "PERIPHERAL TISSUES")
        c.setFont("Helvetica-Bold", 7); c.setFillColor(C_RED_DARK)
        c.drawCentredString(donor_x+donor_w/2, 93, "(DONORS)")

        donors = [("SKELETAL MUSCLE", "→ Gives amino acids (Gln, Ala)"),
                  ("ADIPOSE TISSUE",  "→ Gives fatty acids"),
                  ("SKIN",            "→ Gives structural proteins")]
        for i, (title, sub) in enumerate(donors):
            ty = 78 - i*22
            c.setFillColor(C_RED_MID); c.roundRect(donor_x+6, ty, donor_w-12, 18, 3, fill=1, stroke=0)
            c.setFillColor(C_WHITE); c.setFont("Helvetica-Bold", 6.5)
            c.drawCentredString(donor_x+donor_w/2, ty+11, title)
            c.setFont("Helvetica", 6)
            c.drawCentredString(donor_x+donor_w/2, ty+3, sub)

        # Centre: Arrow + label
        mid_x = donor_x + donor_w + 8
        mid_w = 100
        c.setFillColor(C_YELLOW_LIGHT); c.setStrokeColor(C_YELLOW_MID); c.setLineWidth(1.2)
        c.roundRect(mid_x, 40, mid_w, 55, 5, fill=1, stroke=1)
        c.setFillColor(C_YELLOW_DARK); c.setFont("Helvetica-Bold", 8)
        c.drawCentredString(mid_x+mid_w/2, 84, "FUEL RELEASED")
        c.setFont("Helvetica", 7)
        c.drawCentredString(mid_x+mid_w/2, 73, "Amino acids")
        c.drawCentredString(mid_x+mid_w/2, 63, "(esp. Glutamine,")
        c.drawCentredString(mid_x+mid_w/2, 54, "Alanine, BCAAs)")
        c.drawCentredString(mid_x+mid_w/2, 44, "+ Fatty acids")
        # Big arrow right
        arr_y = 67
        c.setStrokeColor(C_YELLOW_MID); c.setFillColor(C_YELLOW_MID); c.setLineWidth(3)
        c.line(donor_x+donor_w+2, arr_y, mid_x-2, arr_y)
        c.polygon([mid_x-4, arr_y+5, mid_x+2, arr_y, mid_x-4, arr_y-5], fill=1, stroke=0)
        c.setStrokeColor(C_TEAL_MID); c.setFillColor(C_TEAL_MID); c.setLineWidth(3)
        arr_x2 = mid_x+mid_w
        c.line(arr_x2, arr_y, arr_x2+8, arr_y)
        c.polygon([arr_x2+6, arr_y+5, arr_x2+12, arr_y, arr_x2+6, arr_y-5], fill=1, stroke=0)

        # Right column: Central (recipient) tissues
        rec_x = mid_x + mid_w + 14; rec_w = W - rec_x - 10
        c.setFillColor(C_GREEN_LIGHT); c.setStrokeColor(C_GREEN_MID); c.setLineWidth(1.2)
        c.roundRect(rec_x, 20, rec_w, 95, 5, fill=1, stroke=1)
        c.setFillColor(C_GREEN_DARK); c.setFont("Helvetica-Bold", 8)
        c.drawCentredString(rec_x+rec_w/2, 105, "CENTRAL TISSUES")
        c.setFont("Helvetica-Bold", 7)
        c.drawCentredString(rec_x+rec_w/2, 93, "(RECIPIENTS)")

        recipients = [("LIVER",          "Makes glucose + acute-phase proteins"),
                      ("IMMUNE SYSTEM",   "Fuels immune cell activity"),
                      ("WOUND / REPAIR",  "Builds new tissue")]
        for i, (title, sub) in enumerate(recipients):
            ty = 78 - i*22
            c.setFillColor(C_GREEN_MID); c.roundRect(rec_x+6, ty, rec_w-12, 18, 3, fill=1, stroke=0)
            c.setFillColor(C_WHITE); c.setFont("Helvetica-Bold", 6.5)
            c.drawCentredString(rec_x+rec_w/2, ty+11, title)
            c.setFont("Helvetica", 6)
            c.drawCentredString(rec_x+rec_w/2, ty+3, sub)

        # Bottom note
        c.setFillColor(C_TEAL_DARK); c.setFont("Helvetica-Oblique", 7)
        c.drawCentredString(W/2, 10, "The body sacrifices muscle and fat to keep the liver, immune system, and wound supplied.")


# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 6 — ERAS vs Traditional Care
# ══════════════════════════════════════════════════════════════════════════════
class ERASGraph(Flowable):
    def __init__(self, width=PW, height=160):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        c = self.canv
        W, H = self.width, self.height

        c.setFillColor(C_GREEN_LIGHT)
        c.rect(0, 0, W, H, fill=1, stroke=0)
        c.setStrokeColor(C_GREEN_DARK); c.setLineWidth(0.8)
        c.rect(0, 0, W, H, fill=0, stroke=1)

        c.setFillColor(C_GREEN_DARK); c.setFont("Helvetica-Bold", 9.5)
        c.drawCentredString(W/2, H-13, "ERAS vs TRADITIONAL CARE — FUNCTIONAL RECOVERY")

        # Axes
        ox, oy = 55, 25; aw, ah = W-80, 100
        c.setStrokeColor(C_BLACK); c.setLineWidth(1.5)
        c.line(ox, oy, ox, oy+ah)       # y-axis
        c.line(ox, oy+ah*0.75, ox+aw, oy+ah*0.75)  # baseline (normal function level)

        # Axis labels
        c.setFillColor(C_BLACK); c.setFont("Helvetica-Bold", 7.5)
        c.saveState()
        c.translate(15, oy+ah/2)
        c.rotate(90)
        c.drawCentredString(0, 0, "Functional Capacity")
        c.restoreState()

        c.setFont("Helvetica-Bold", 7.5)
        c.drawCentredString(ox+aw/2, oy-8, "Time after Surgery")

        # Time markers
        normal_y = oy + ah*0.75
        sx = ox + 60  # surgery point x
        c.setStrokeColor(C_GREY); c.setLineWidth(0.8)
        c.line(sx, oy, sx, oy+ah+5)
        c.setFillColor(C_GREY); c.setFont("Helvetica", 6.5)
        c.drawCentredString(sx, oy+ah+8, "Surgery")

        # Traditional curve (deep trough)
        import math
        trad_pts = []
        for i in range(100):
            t = i / 99.0
            px2 = ox + 60 + t*(aw - 65)
            # Drops to 40% then slowly recovers
            if t < 0.15:
                factor = 1 - t/0.15 * 0.55
            elif t < 0.55:
                factor = 0.45 + (t-0.15)/0.4 * 0.15
            else:
                factor = 0.60 + (t-0.55)/0.45 * 0.40
            py2 = oy + ah*0.75 * factor
            trad_pts.append((px2, py2))

        c.setStrokeColor(C_RED_MID); c.setLineWidth(2.5)
        p = c.beginPath()
        p.moveTo(trad_pts[0][0], trad_pts[0][1])
        for px2, py2 in trad_pts[1:]:
            p.lineTo(px2, py2)
        c.drawPath(p, stroke=1, fill=0)

        # ERAS curve (shallow dip, fast recovery)
        eras_pts = []
        for i in range(100):
            t = i / 99.0
            px2 = ox + 60 + t*(aw - 65)
            if t < 0.08:
                factor = 1 - t/0.08 * 0.22
            elif t < 0.25:
                factor = 0.78 + (t-0.08)/0.17 * 0.22
            else:
                factor = 1.0
            py2 = oy + ah*0.75 * factor
            eras_pts.append((px2, py2))

        c.setStrokeColor(C_GREEN_MID); c.setLineWidth(2.5)
        p2 = c.beginPath()
        p2.moveTo(eras_pts[0][0], eras_pts[0][1])
        for px2, py2 in eras_pts[1:]:
            p2.lineTo(px2, py2)
        c.drawPath(p2, stroke=1, fill=0)

        # Normal baseline label
        c.setFillColor(C_GREY); c.setFont("Helvetica-Oblique", 6.5)
        c.drawString(ox+2, normal_y+2, "Normal")

        # Pre-surgery flat lines
        c.setStrokeColor(C_RED_MID); c.setLineWidth(2.5)
        c.line(ox, normal_y, sx, normal_y)
        c.setStrokeColor(C_GREEN_MID); c.setLineWidth(2.5)
        c.line(ox, normal_y, sx, normal_y)

        # Legend
        leg_x = ox + aw - 170; leg_y = oy + 5
        c.setFillColor(C_WHITE); c.setStrokeColor(C_GREY); c.setLineWidth(0.8)
        c.roundRect(leg_x, leg_y, 165, 38, 3, fill=1, stroke=1)
        # ERAS line
        c.setStrokeColor(C_GREEN_MID); c.setLineWidth(2.5)
        c.line(leg_x+8, leg_y+28, leg_x+30, leg_y+28)
        c.setFillColor(C_GREEN_DARK); c.setFont("Helvetica-Bold", 7)
        c.drawString(leg_x+34, leg_y+25, "ERAS (Enhanced Recovery)")
        # Trad line
        c.setStrokeColor(C_RED_MID); c.setLineWidth(2.5)
        c.line(leg_x+8, leg_y+14, leg_x+30, leg_y+14)
        c.setFillColor(C_RED_DARK); c.setFont("Helvetica-Bold", 7)
        c.drawString(leg_x+34, leg_y+11, "Traditional Care")

        # Callout: 30-50% shorter stay
        c.setFillColor(C_GREEN_MID)
        c.roundRect(ox+80, oy+5, 130, 22, 4, fill=1, stroke=0)
        c.setFillColor(C_WHITE); c.setFont("Helvetica-Bold", 7.5)
        c.drawCentredString(ox+145, oy+16, "Hospital stay reduced 30–50%!")


# ══════════════════════════════════════════════════════════════════════════════
# DIAGRAM 7 — Body Composition Bar
# ══════════════════════════════════════════════════════════════════════════════
class BodyCompositionDiagram(Flowable):
    def __init__(self, width=PW, height=150):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        c = self.canv
        W, H = self.width, self.height

        c.setFillColor(C_YELLOW_LIGHT)
        c.rect(0, 0, W, H, fill=1, stroke=0)
        c.setStrokeColor(C_YELLOW_DARK); c.setLineWidth(0.8)
        c.rect(0, 0, W, H, fill=0, stroke=1)

        c.setFillColor(C_YELLOW_DARK); c.setFont("Helvetica-Bold", 9.5)
        c.drawCentredString(W/2, H-13, "BODY COMPOSITION OF A 70 kg ADULT (NORMAL)")

        # Bar dimensions
        bx, by, bw = 50, 18, 55
        total_h = H - 35

        segments = [
            (3,  "MINERALS\n3 kg",         C_GREEN_MID,   C_WHITE),
            (14, "EXTRACELLULAR\nWATER 14L", C_PURPLE_MID, C_WHITE),
            (28, "INTRACELLULAR\nWATER 28L", C_BLUE_MID,   C_WHITE),
            (12, "PROTEIN 12 kg\n(Muscle + Visceral)", C_ORANGE_MID, C_WHITE),
            (13, "FAT 13 kg",               C_YELLOW_MID,  C_BLACK),
        ]
        total = sum(s[0] for s in segments)
        cur_y = by
        bar_segs = []
        for kg, label, col, tcol in segments:
            seg_h = (kg / total) * total_h
            bar_segs.append((bx, cur_y, bw, seg_h, col, tcol, label, kg))
            cur_y += seg_h

        for (sx2, sy2, sw2, sh2, col, tcol, label, kg) in bar_segs:
            c.setFillColor(col); c.setStrokeColor(C_WHITE); c.setLineWidth(0.8)
            c.rect(sx2, sy2, sw2, sh2, fill=1, stroke=1)
            if sh2 > 12:
                lines2 = label.split("\n")
                ly = sy2 + sh2/2 + len(lines2)*4 - 4
                for ln in lines2:
                    c.setFillColor(tcol); c.setFont("Helvetica-Bold", 6)
                    c.drawCentredString(sx2+sw2/2, ly, ln)
                    ly -= 8

        # Y axis labels
        c.setStrokeColor(C_GREY); c.setLineWidth(0.8)
        c.line(bx-2, by, bx-2, by+total_h)
        for y_val in [0, 10, 20, 30, 40, 50, 60, 70]:
            yl = by + (y_val/total)*total_h
            c.setStrokeColor(C_GREY); c.setLineWidth(0.5)
            c.line(bx-6, yl, bx-2, yl)
            c.setFillColor(C_BLACK); c.setFont("Helvetica", 5.5)
            c.drawRightString(bx-8, yl-2, f"{y_val}")
        c.setFillColor(C_BLACK); c.setFont("Helvetica-Bold", 6.5)
        c.saveState()
        c.translate(15, by+total_h/2)
        c.rotate(90)
        c.drawCentredString(0, 0, "Mass (kg)")
        c.restoreState()

        # Right side: annotation table
        tx = bx + bw + 20
        c.setFillColor(C_BLACK); c.setFont("Helvetica-Bold", 8)
        c.drawString(tx, by+total_h+3, "What gets lost in injury:")
        notes = [
            (C_ORANGE_MID, "PROTEIN (-12 kg risk):"),
            (None,         "  • Muscle wasting (ubiquitin pathway)"),
            (None,         "  • Immune proteins decrease"),
            (None,         "  • 500g/day in severe sepsis"),
            (C_YELLOW_MID, "FAT mobilised for energy:"),
            (None,         "  • Lipolysis by cortisol + adrenaline"),
            (None,         "  • Ketone bodies used by brain"),
            (C_PURPLE_MID, "FLUID shifts:"),
            (None,         "  • ECF expands (capillary leak)"),
            (None,         "  • Apparent weight GAIN early"),
        ]
        ny = by + total_h - 5
        for col2, note in notes:
            if col2:
                c.setFillColor(col2); c.roundRect(tx-2, ny-2, 8, 8, 2, fill=1, stroke=0)
                c.setFillColor(C_BLACK); c.setFont("Helvetica-Bold", 7)
                c.drawString(tx+10, ny, note)
            else:
                c.setFont("Helvetica", 6.5); c.setFillColor(C_BLACK)
                c.drawString(tx, ny, note)
            ny -= 11

        # LBM bracket
        lbm_y_bot = by
        lbm_y_top = by + (57/total)*total_h
        c.setStrokeColor(C_GREY); c.setLineWidth(1.2)
        c.line(bx+bw+2, lbm_y_bot, bx+bw+8, lbm_y_bot)
        c.line(bx+bw+8, lbm_y_bot, bx+bw+8, lbm_y_top)
        c.line(bx+bw+2, lbm_y_top, bx+bw+8, lbm_y_top)
        c.setFillColor(C_GREY); c.setFont("Helvetica-Bold", 6)
        c.saveState()
        c.translate(bx+bw+14, (lbm_y_bot+lbm_y_top)/2)
        c.rotate(90)
        c.drawCentredString(0, 0, "LBM/FFM (~57 kg)")
        c.restoreState()


# ══════════════════════════════════════════════════════════════════════════════
# BUILD STORY
# ══════════════════════════════════════════════════════════════════════════════
story = []

# ── Cover Banner ──────────────────────────────────────────────────────────────
cover_data = [
    [Paragraph("METABOLIC RESPONSE TO INJURY", ST_MAIN_TITLE)],
    [Paragraph("Complete Quick-Reference Guide with Flowcharts &amp; Diagrams", ST_MAIN_SUB)],
    [Paragraph("Bailey &amp; Love's Surgery | Chapter 1 — Simplified for Easy Understanding", ST_MAIN_SUB)],
]
cover = Table(cover_data, colWidths=[PW])
cover.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,-1), C_DARK_BG),
    ("TOPPADDING",    (0,0),(-1,-1), 16),
    ("BOTTOMPADDING", (0,0),(-1,-1), 16),
    ("LEFTPADDING",   (0,0),(-1,-1), 12),
    ("RIGHTPADDING",  (0,0),(-1,-1), 12),
]))
story.append(cover)
story.append(sp(8))

# ── What is the Metabolic Response? ──────────────────────────────────────────
story.append(Paragraph("What is the Metabolic Response to Injury?", ST_H1))
story.append(hr())
story.append(Paragraph(
    "When your body is <b>injured</b> (surgery, trauma, burns, sepsis), it launches an <b>emergency survival programme</b>. "
    "Every organ, hormone, and immune cell shifts from routine work to <b>crisis management</b>. "
    "The body breaks down its own tissues to generate fuel and building blocks — then, once the danger passes, rebuilds.",
    ST_BODY))
story.append(Paragraph(
    "<b>Homeostasis</b> = the body's normal stable balance. Injury disrupts this. The entire metabolic response "
    "is the body's attempt to <b>restore homeostasis</b>. The two-word summary: <b>Break down → Rebuild.</b>",
    ST_BODY))
story.append(sp(6))

# ── Phases Timeline ───────────────────────────────────────────────────────────
story.append(Paragraph("The Three Phases at a Glance", ST_H2))
story.append(PhasesTimelineDiagram(width=PW, height=110))
story.append(Paragraph(
    "Figure 1 — Timeline of the metabolic response phases. Phase 1 is catabolic (breakdown), Phase 2 is the "
    "hypermetabolic flow/SIRS phase, and Phase 3 is anabolic (repair and recovery).",
    ST_CAP))
story.append(sp(8))

# ── Full Cascade Flowchart ────────────────────────────────────────────────────
story.append(Paragraph("Complete Injury Response Cascade — How It All Connects", ST_H1))
story.append(hr())
story.append(InjuryCascadeFlowchart(width=PW, height=340))
story.append(Paragraph(
    "Figure 2 — Master flowchart of the metabolic response. Injury triggers two simultaneous pathways: "
    "the nervous system (neuroendocrine) and the immune system (inflammatory). These interact to produce "
    "catabolism, hypermetabolism, immunosuppression, and fluid shifts. Uncontrolled, this leads to SIRS → MODS.",
    ST_CAP))
story.append(sp(8))

# ── Neuroendocrine ────────────────────────────────────────────────────────────
story.append(Paragraph("The Neuroendocrine Response — Step by Step", ST_H1))
story.append(hr())
story.append(Paragraph(
    "Injury pain signals travel from the wound → spinal cord → hypothalamus. The hypothalamus then "
    "coordinates a hormonal cascade designed to mobilise emergency fuel within minutes to hours.",
    ST_BODY))
story.append(NeuroendocrineDiagram(width=PW, height=200))
story.append(Paragraph(
    "Figure 3 — Neuroendocrine pathway. The hypothalamus releases CRF → Pituitary releases ACTH and GH "
    "→ Adrenal glands release cortisol and adrenaline → Pancreas releases glucagon. Net effect: "
    "blood glucose rises, fat is mobilised, protein is broken down. Insulin, IGF-1, testosterone, and T3 all fall.",
    ST_CAP))
story.append(sp(6))

# Two-column: what goes up / what goes down
col1_items = [
    [Paragraph("HORMONES THAT RISE ↑", PS("UH", parent="Normal", fontSize=9,
        fontName="Helvetica-Bold", textColor=C_WHITE, alignment=TA_CENTER))],
    [b("Cortisol — raises glucose, breaks down fat and muscle", ST_BULLET)],
    [b("Adrenaline — raises heart rate, blood pressure, glucose", ST_BULLET)],
    [b("Glucagon — stimulates liver to release glucose", ST_BULLET)],
    [b("ACTH — drives cortisol release", ST_BULLET)],
    [b("Growth Hormone — lipolysis and protein effects", ST_BULLET)],
    [b("IL-1, IL-6, TNF-α — drive fever + acute-phase response", ST_BULLET)],
]
col2_items = [
    [Paragraph("HORMONES THAT FALL ↓", PS("DH", parent="Normal", fontSize=9,
        fontName="Helvetica-Bold", textColor=C_WHITE, alignment=TA_CENTER))],
    [b("Insulin — cells become resistant; blood sugar rises", ST_BULLET)],
    [b("IGF-1 — reduced anabolic stimulus", ST_BULLET)],
    [b("Testosterone — less muscle building signal", ST_BULLET)],
    [b("T3 (Thyroid hormone) — reduced metabolic drive", ST_BULLET)],
    [b("Albumin — drops due to capillary leakage + redistribution", ST_BULLET)],
    [b("IGF-1 — growth and repair signals suppressed", ST_BULLET)],
]
def build_col(rows, bg, border, header_bg):
    data = []
    for i, row in enumerate(rows):
        data.append(row)
    t = Table(data, colWidths=[(PW/2)-6])
    ts = [
        ("BACKGROUND", (0,0),(0,0), header_bg),
        ("BACKGROUND", (0,1),(-1,-1), bg),
        ("BOX",        (0,0),(-1,-1), 1.2, border),
        ("INNERGRID",  (0,0),(-1,-1), 0.3, border),
        ("TOPPADDING", (0,0),(-1,-1), 4),
        ("BOTTOMPADDING",(0,0),(-1,-1), 4),
        ("LEFTPADDING",(0,0),(-1,-1), 6),
    ]
    t.setStyle(TableStyle(ts))
    return t

up_table = build_col(col1_items, C_ORANGE_LIGHT, C_ORANGE_MID, C_ORANGE_DARK)
down_table = build_col(col2_items, C_BLUE_LIGHT, C_BLUE_MID, C_BLUE_DARK)

two_col = Table([[up_table, Spacer(12,1), down_table]], colWidths=[(PW/2)-3, 12, (PW/2)-3])
two_col.setStyle(TableStyle([("VALIGN",(0,0),(-1,-1),"TOP")]))
story.append(two_col)
story.append(sp(8))

# ── Inflammatory Cascade ──────────────────────────────────────────────────────
story.append(Paragraph("The Inflammatory Cascade — DAMPs, PRRs, Cytokines", ST_H1))
story.append(hr())

inf_steps = [
    ("1", "INJURY",          "Cells are damaged",
     C_RED_MID,    C_WHITE),
    ("2", "DAMPs RELEASED",  "Danger fragments spill out\n(HMGB1, heat-shock proteins,\nS100 proteins)",
     C_ORANGE_MID, C_WHITE),
    ("3", "PRRs DETECT",     "Toll-like / NOD-like receptors\non macrophages, neutrophils\ndetect DAMPs",
     C_PURPLE_MID, C_WHITE),
    ("4", "INFLAMMASOME",    "Intracellular complex forms\n→ Caspases activated",
     C_PURPLE_DARK,C_WHITE),
    ("5", "CYTOKINES",       "IL-1, IL-6, IL-8, TNF-α\nreleased → Fever, SIRS",
     C_BLUE_MID,   C_WHITE),
    ("6", "RESOLUTION or\nSIRS/MODS", "If controlled: repair\nIf uncontrolled: SIRS\n→ MODS (25% mortality)",
     C_RED_DARK,   C_WHITE),
]

step_w = (PW - 5*(8)) / 6
step_rows = []
num_row = []; box_row = []; lbl_row = []
for num, title, desc, bg, tc in inf_steps:
    num_row.append(Paragraph(num, PS("NN", parent="Normal", fontSize=14,
        fontName="Helvetica-Bold", textColor=bg, alignment=TA_CENTER)))
    inner = [Paragraph(title, PS("ST", parent="Normal", fontSize=8,
        fontName="Helvetica-Bold", textColor=C_WHITE, alignment=TA_CENTER, spaceAfter=2))]
    for ln in desc.split("\n"):
        inner.append(Paragraph(ln, PS("SD", parent="Normal", fontSize=6.5,
            fontName="Helvetica", textColor=C_WHITE, alignment=TA_CENTER, spaceAfter=0)))
    t = Table([[inner]], colWidths=[step_w])
    t.setStyle(TableStyle([
        ("BACKGROUND",(0,0),(-1,-1), bg),
        ("TOPPADDING",(0,0),(-1,-1), 5),
        ("BOTTOMPADDING",(0,0),(-1,-1), 5),
        ("LEFTPADDING",(0,0),(-1,-1), 3),
        ("RIGHTPADDING",(0,0),(-1,-1), 3),
        ("ROUNDEDCORNERS",(0,0),(-1,-1), 4),
    ]))
    box_row.append(t)

# Assemble with arrows between
all_cells = []
col_widths = []
for i, cell in enumerate(box_row):
    all_cells.append(cell)
    col_widths.append(step_w)
    if i < len(box_row)-1:
        all_cells.append(Paragraph("▶", PS("AR", parent="Normal", fontSize=10,
            textColor=C_GREY, alignment=TA_CENTER)))
        col_widths.append(8)

flow_table = Table([all_cells], colWidths=col_widths)
flow_table.setStyle(TableStyle([
    ("VALIGN",(0,0),(-1,-1),"MIDDLE"),
    ("TOPPADDING",(0,0),(-1,-1),0),
    ("BOTTOMPADDING",(0,0),(-1,-1),0),
]))
story.append(flow_table)
story.append(Paragraph(
    "Figure 4 — The inflammatory cascade from injury to SIRS/MODS. Each step amplifies the next.",
    ST_CAP))
story.append(sp(6))

# SIRS vs CARS note
sirs_cars = Table([[
    cbox([
        Paragraph("<b>SIRS</b> — Systemic Inflammatory Response Syndrome", PS("SH", parent="Normal",
            fontSize=9, fontName="Helvetica-Bold", textColor=C_RED_DARK, spaceAfter=3)),
        "The body's inflammation goes system-wide. Signs: Temp >38°C or <36°C, HR >90, "
        "RR >20, WBC >12,000. If severe → organ damage.",
    ], bg=C_RED_LIGHT, border=C_RED_MID, width=(PW/2)-4),
    Spacer(8, 1),
    cbox([
        Paragraph("<b>CARS</b> — Compensatory Anti-inflammatory Response Syndrome", PS("CH", parent="Normal",
            fontSize=9, fontName="Helvetica-Bold", textColor=C_BLUE_DARK, spaceAfter=3)),
        "The body's counter-response to SIRS — damps inflammation down. If CARS dominates "
        "→ immunosuppression → opportunistic infections → worse outcomes.",
    ], bg=C_BLUE_LIGHT, border=C_BLUE_MID, width=(PW/2)-4),
]], colWidths=[(PW/2)-4, 8, (PW/2)-4])
sirs_cars.setStyle(TableStyle([("VALIGN",(0,0),(-1,-1),"TOP")]))
story.append(sirs_cars)
story.append(sp(8))

# ── Resource Reprioritisation ─────────────────────────────────────────────────
story.append(Paragraph("Resource Reprioritisation — Why You Lose Muscle", ST_H1))
story.append(hr())
story.append(Paragraph(
    "During injury, the body is like a city in emergency mode: <b>non-essential buildings are stripped "
    "for materials to build the hospital, police station, and repair crews</b>. Muscle, fat, and skin "
    "are the 'non-essential buildings'. The liver, immune system, and wound are the essential services.",
    ST_BODY))
story.append(ResourceFlowDiagram(width=PW, height=140))
story.append(Paragraph(
    "Figure 5 — Resource flow during injury. Peripheral tissues (muscle, fat, skin) donate amino acids "
    "and fatty acids. Central tissues (liver, immune system, wound) receive and use them.",
    ST_CAP))
story.append(sp(8))

# ── Muscle Wasting ────────────────────────────────────────────────────────────
story.append(Paragraph("How Muscle is Broken Down — The Ubiquitin-Proteasome System", ST_H1))
story.append(hr())
story.append(UbiquitinDiagram(width=PW, height=160))
story.append(Paragraph(
    "Figure 6 — The ubiquitin-proteasome pathway. This is the main molecular mechanism of muscle "
    "wasting in injury. Steps: Cut → Tag (ubiquitin) → Shred (proteasome) → Release amino acids.",
    ST_CAP))
story.append(sp(8))

# ── Body Composition ──────────────────────────────────────────────────────────
story.append(Paragraph("Body Composition — What Gets Lost and Why It Matters", ST_H1))
story.append(hr())
story.append(BodyCompositionDiagram(width=PW, height=150))
story.append(Paragraph(
    "Figure 7 — Body composition of a 70 kg adult. Fat and protein are the reserves mobilised during "
    "injury. Protein loss impairs function (weakness, poor wound healing, infections). Fluid shifts "
    "can cause paradoxical weight gain (oedema) even while lean mass is being lost.",
    ST_CAP))
story.append(sp(8))

# ── Avoidable Factors ─────────────────────────────────────────────────────────
story.append(Paragraph("Avoidable Factors That Make Things Worse", ST_H1))
story.append(hr())

avoid_data = [
    [Paragraph("Factor", ST_TH), Paragraph("Why It's Bad", ST_TH), Paragraph("Fix It With", ST_TH)],
    [Paragraph("Pain (uncontrolled)", ST_TD), 
     Paragraph("Activates sympathetic + neuroendocrine cascade continuously", ST_TD),
     Paragraph("Epidural, spinal, wound catheters, IV analgesia", ST_TD)],
    [Paragraph("Hypothermia", ST_TD),
     Paragraph("Increases catabolism 2-3x; cardiac arrhythmias", ST_TD),
     Paragraph("Forced-air warming blankets; maintain theatre temperature", ST_TD)],
    [Paragraph("Starvation / Fasting", ST_TD),
     Paragraph("Forces gluconeogenesis from muscle; worsens catabolism", ST_TD),
     Paragraph("Carbohydrate drink 2h pre-op; early enteral feeding post-op", ST_TD)],
    [Paragraph("Immobility / Bed rest", ST_TD),
     Paragraph("Removes fed-state amino acid stimulus; wasting accelerates", ST_TD),
     Paragraph("Early mobilisation — day 0 or 1 post-operatively", ST_TD)],
    [Paragraph("Tissue Oedema (excess IV saline)", ST_TD),
     Paragraph("Impairs gut, lungs, wound healing; prolongs hospital stay", ST_TD),
     Paragraph("Goal-directed fluid therapy; avoid excess saline", ST_TD)],
    [Paragraph("Haemorrhage / Low BP", ST_TD),
     Paragraph("Triggers RAAS + ADH; prolongs catabolic phase", ST_TD),
     Paragraph("Stop bleeding; adequate resuscitation", ST_TD)],
    [Paragraph("Sepsis / Infection", ST_TD),
     Paragraph("Perpetuates DAMPs loop; extends catabolism indefinitely", ST_TD),
     Paragraph("Early diagnosis, source control, appropriate antibiotics", ST_TD)],
]

avoid_table = Table(avoid_data, colWidths=[4.5*cm, 7.0*cm, 6.2*cm], repeatRows=1)
avoid_table.setStyle(TableStyle([
    ("BACKGROUND",    (0,0),(-1,0), C_BLUE_DARK),
    ("BACKGROUND",    (0,1),(-1,1), C_ORANGE_LIGHT),
    ("BACKGROUND",    (0,2),(-1,2), C_BLUE_LIGHT),
    ("BACKGROUND",    (0,3),(-1,3), C_ORANGE_LIGHT),
    ("BACKGROUND",    (0,4),(-1,4), C_BLUE_LIGHT),
    ("BACKGROUND",    (0,5),(-1,5), C_ORANGE_LIGHT),
    ("BACKGROUND",    (0,6),(-1,6), C_BLUE_LIGHT),
    ("BACKGROUND",    (0,7),(-1,7), C_ORANGE_LIGHT),
    ("BOX",           (0,0),(-1,-1), 1, C_GREY),
    ("INNERGRID",     (0,0),(-1,-1), 0.4, C_GREY),
    ("TOPPADDING",    (0,0),(-1,-1), 5),
    ("BOTTOMPADDING", (0,0),(-1,-1), 5),
    ("LEFTPADDING",   (0,0),(-1,-1), 6),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]))
story.append(avoid_table)
story.append(sp(8))

# ── ERAS ──────────────────────────────────────────────────────────────────────
story.append(Paragraph("ERAS — Enhanced Recovery After Surgery", ST_H1))
story.append(hr())
story.append(Paragraph(
    "<b>ERAS</b> packages all the fixes for avoidable factors into a single multimodal protocol. "
    "The goal: <b>attack every stressor simultaneously</b> to keep the metabolic response as small as possible "
    "and get the patient back to normal function within days, not weeks.",
    ST_BODY))

story.append(ERASGraph(width=PW, height=160))
story.append(Paragraph(
    "Figure 8 — ERAS vs Traditional care. The ERAS curve shows a much shallower dip in functional "
    "capacity and far faster recovery. Hospital stays reduced by 30–50%.",
    ST_CAP))
story.append(sp(6))

eras_boxes = [
    (C_GREEN_LIGHT,  C_GREEN_MID,  "Minimal Access Surgery",
     "Laparoscopy/robotic instead of open surgery. Smaller wound = smaller inflammatory trigger = smaller metabolic response."),
    (C_BLUE_LIGHT,   C_BLUE_MID,   "Pain Control",
     "Epidural, spinal blocks, wound catheters. Less pain → less neuroendocrine activation → less cortisol/adrenaline surge."),
    (C_ORANGE_LIGHT, C_ORANGE_MID, "Minimal Starvation",
     "Carbohydrate drink 2h before surgery. Start eating same day or next day after surgery. This alone reduces insulin resistance significantly."),
    (C_PURPLE_LIGHT, C_PURPLE_MID, "Early Mobilisation",
     "Get the patient out of bed on day 0 or 1. Physical activity is the most powerful stimulus to reverse muscle wasting."),
    (C_TEAL_LIGHT,   C_TEAL_MID,   "Smart Fluid Management",
     "Give exactly what's needed — not more, not less. Avoid excess saline (causes oedema). Use goal-directed therapy."),
    (C_YELLOW_LIGHT, C_YELLOW_MID, "Temperature Control",
     "Maintain normothermia throughout surgery and recovery. Warming blankets, warm fluids, warm theatre environment."),
]

eras_rows = []
for i in range(0, len(eras_boxes), 2):
    row = []
    for j in range(2):
        if i+j < len(eras_boxes):
            bg, bd, title, text = eras_boxes[i+j]
            inner = [
                Paragraph(title, PS("ET", parent="Normal", fontSize=9.5, fontName="Helvetica-Bold",
                    textColor=bd, spaceAfter=3)),
                Paragraph(text, ST_SMALL),
            ]
            t = Table([[inner]], colWidths=[(PW/2)-4])
            t.setStyle(TableStyle([
                ("BACKGROUND",(0,0),(-1,-1), bg),
                ("BOX",(0,0),(-1,-1), 1.2, bd),
                ("TOPPADDING",(0,0),(-1,-1), 7),
                ("BOTTOMPADDING",(0,0),(-1,-1), 7),
                ("LEFTPADDING",(0,0),(-1,-1), 8),
                ("RIGHTPADDING",(0,0),(-1,-1), 8),
            ]))
            row.append(t)
        else:
            row.append(Spacer(1,1))
        if j == 0:
            row.append(Spacer(8,1))
    eras_rows.append(row)

eras_grid = Table(eras_rows, colWidths=[(PW/2)-4, 8, (PW/2)-4])
eras_grid.setStyle(TableStyle([
    ("VALIGN",(0,0),(-1,-1),"TOP"),
    ("BOTTOMPADDING",(0,0),(-1,-1), 5),
]))
story.append(eras_grid)
story.append(sp(8))

# ── Quick Reference Summary Table ─────────────────────────────────────────────
story.append(PageBreak())
story.append(Paragraph("Quick Reference Summary — Everything at a Glance", ST_H1))
story.append(hr())

# Master summary table
qr_data = [
    [Paragraph("TOPIC", ST_TH), Paragraph("SIMPLE EXPLANATION", ST_TH),
     Paragraph("KEY NUMBERS / FACTS", ST_TH)],
    [Paragraph("Metabolic Response", ST_TD),
     Paragraph("Emergency programme the body activates after any significant injury", ST_TD),
     Paragraph("Driven by hormones + cytokines within minutes", ST_TD)],
    [Paragraph("Catabolic Phase", ST_TD),
     Paragraph("Body breaks itself down to release energy and building blocks", ST_TD),
     Paragraph("Lasts 24–48 hours after injury", ST_TD)],
    [Paragraph("Flow / SIRS Phase", ST_TD),
     Paragraph("Hypermetabolic state — high energy burn, fever, muscle loss", ST_TD),
     Paragraph("Metabolic rate 15–25% above normal (burns: higher)", ST_TD)],
    [Paragraph("Anabolic Phase", ST_TD),
     Paragraph("Repair and rebuild — tissue healed, muscle regained", ST_TD),
     Paragraph("Can take weeks after major injury", ST_TD)],
    [Paragraph("DAMPs", ST_TD),
     Paragraph("'Danger signals' released from damaged cells — trigger the immune alarm", ST_TD),
     Paragraph("Detected by Toll-like and NOD-like receptors", ST_TD)],
    [Paragraph("Cytokines", ST_TD),
     Paragraph("Chemical messengers that spread the inflammatory signal", ST_TD),
     Paragraph("IL-1, IL-6, IL-8, TNF-α all rise within 24h", ST_TD)],
    [Paragraph("Cortisol ↑", ST_TD),
     Paragraph("Raises glucose, breaks fat and muscle down for fuel", ST_TD),
     Paragraph("Rises within hours of injury", ST_TD)],
    [Paragraph("Insulin ↓", ST_TD),
     Paragraph("Cells stop responding — insulin resistance develops (like Type 2 DM)", ST_TD),
     Paragraph("Persists ~2 weeks after major surgery", ST_TD)],
    [Paragraph("Muscle Wasting", ST_TD),
     Paragraph("Ubiquitin-proteasome pathway shreds muscle protein for amino acids", ST_TD),
     Paragraph("Up to 500 g/day in severe sepsis", ST_TD)],
    [Paragraph("Resource Shift", ST_TD),
     Paragraph("Amino acids from muscle → liver, immune system, wound", ST_TD),
     Paragraph("Glutamine and Alanine are the main carriers", ST_TD)],
    [Paragraph("Acute-Phase Response", ST_TD),
     Paragraph("Liver switches from albumin to CRP and fibrinogen production", ST_TD),
     Paragraph("CRP ↑ = positive reactant; Albumin ↓ = negative reactant", ST_TD)],
    [Paragraph("SIRS", ST_TD),
     Paragraph("Systemic Inflammatory Response Syndrome — inflammation goes body-wide", ST_TD),
     Paragraph("MODS mortality ~25%", ST_TD)],
    [Paragraph("ERAS", ST_TD),
     Paragraph("Multimodal protocol: minimal surgery + pain control + early feeding + mobilisation", ST_TD),
     Paragraph("Hospital stay reduced 30–50%", ST_TD)],
]

qr_table = Table(qr_data, colWidths=[3.8*cm, 8.8*cm, 5.1*cm], repeatRows=1)
row_colors = [C_BLUE_DARK] + [
    (C_ORANGE_LIGHT if i%2==1 else C_BLUE_LIGHT) for i in range(1, len(qr_data))
]
ts = [
    ("BACKGROUND",    (0,0),(-1,0), C_BLUE_DARK),
    ("BOX",           (0,0),(-1,-1), 1, C_GREY),
    ("INNERGRID",     (0,0),(-1,-1), 0.4, C_GREY),
    ("TOPPADDING",    (0,0),(-1,-1), 5),
    ("BOTTOMPADDING", (0,0),(-1,-1), 5),
    ("LEFTPADDING",   (0,0),(-1,-1), 6),
    ("VALIGN",        (0,0),(-1,-1), "TOP"),
]
for i in range(1, len(qr_data)):
    bg = C_ORANGE_LIGHT if i%2==1 else C_BLUE_LIGHT
    ts.append(("BACKGROUND", (0,i),(-1,i), bg))
qr_table.setStyle(TableStyle(ts))
story.append(qr_table)
story.append(sp(8))

# ── Footer ────────────────────────────────────────────────────────────────────
story.append(hr(color=C_GREY, t=0.8))
story.append(Paragraph(
    "<i>Source: Bailey &amp; Love's Short Practice of Surgery — Chapter 1: Metabolic Response to Injury. "
    "Simplified study guide for educational purposes. All figures are original diagrams created for this guide.</i>",
    PS("FT", parent="Normal", fontSize=7.5, leading=11,
       textColor=C_GREY, fontName="Helvetica-Oblique", alignment=TA_CENTER)))

# ── Build ──────────────────────────────────────────────────────────────────────
doc.build(story)
print(f"PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/metabolic-injury && python quick_ref_pdf.py 2>&1

Editing File

~/metabolic-injury/quick_ref_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/metabolic-injury/quick_ref_pdf.py'
Running Command

cd /home/daytona/workspace/metabolic-injury && python quick_ref_pdf.py 2>&1

Running Command

grep -n 'parent="Normal"' /home/daytona/workspace/metabolic-injury/quick_ref_pdf.py | head -20

The PS() function already has parent=base['Normal'] hardcoded, so passing parent="Normal" again causes a conflict. I need to fix the PS function to handle this, and also fix all inline calls that pass parent=:
Editing File

~/metabolic-injury/quick_ref_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/metabolic-injury/quick_ref_pdf.py'
Running Command

cd /home/daytona/workspace/metabolic-injury && python quick_ref_pdf.py 2>&1

ReportLab Canvas uses beginPath() + lineTo for polygons. Let me fix all c.polygon(...) calls to use the proper canvas path API:
Running Command

grep -n "\.polygon(" /home/daytona/workspace/metabolic-injury/quick_ref_pdf.py | head -30

I need to add a helper function to replace c.polygon() and fix all occurrences. The cleanest fix is to add a draw_polygon helper using canvas path API and replace all .polygon( calls:
Running Command

cd /home/daytona/workspace/metabolic-injury && python3 -c " import re with open('quick_ref_pdf.py', 'r') as f: src = f.read() # Add helper function after the imports helper = ''' def draw_poly(c, pts, fill=1, stroke=0): \"\"\"Draw a filled polygon on a reportlab canvas. pts = flat list [x0,y0,x1,y1,...]\"\"\" p = c.beginPath() p.moveTo(pts[0], pts[1]) for i in range(2, len(pts), 2): p.lineTo(pts[i], pts[i+1]) p.close() c.drawPath(p, fill=fill, stroke=stroke) ''' # Insert after import math line src = src.replace('import math\n', 'import math\n' + helper) # Replace all .polygon( with draw_poly( # Pattern: c.polygon([...], fill=1, stroke=0) or d.canv.polygon([...], fill=1, stroke=0) src = re.sub(r'([a-z_]+)\.polygon\(', lambda m: 'draw_poly(' + m.group(1) + ', ', src) src = re.sub(r'd\.canv\.polygon\(', 'draw_poly(d.canv, ', src) with open('quick_ref_pdf.py', 'w') as f: f.write(src) print('Done') "

Running Command

cd /home/daytona/workspace/metabolic-injury && python quick_ref_pdf.py 2>&1

Reading File
The regex replacement accidentally inserted the helper function inside the draw() method. I need to remove the spurious draw_poly insertion inside the class and properly place it at module level:
Reading File
The import math inside the class triggered the insertion. Let me fix this cleanly with a Python script:
Running Command

cd /home/daytona/workspace/metabolic-injury && python3 -c " with open('quick_ref_pdf.py', 'r') as f: src = f.read() # Remove the badly placed draw_poly + fix the surrounding code bad = ''' # Traditional curve (deep trough) import math def draw_poly(c, pts, fill=1, stroke=0): \"\"\"Draw a filled polygon on a reportlab canvas. pts = flat list [x0,y0,x1,y1,...]\"\"\" p = c.beginPath() p.moveTo(pts[0], pts[1]) for i in range(2, len(pts), 2): p.lineTo(pts[i], pts[i+1]) p.close() c.drawPath(p, fill=fill, stroke=stroke) trad_pts = []''' good = ''' # Traditional curve (deep trough) trad_pts = []''' src = src.replace(bad, good) with open('quick_ref_pdf.py', 'w') as f: f.write(src) print('Fixed. Lines around 774:') lines = src.split('\n') for i, l in enumerate(lines[770:790], 771): print(f'{i}: {l}') "

Running Command

cd /home/daytona/workspace/metabolic-injury && python quick_ref_pdf.py 2>&1

The regex turned d.canv.polygon( into draw_poly(d.canv, but also turned some d.polygon( patterns into draw_poly(d, . Let me just use a simple sed-based global fix:
Running Command

cd /home/daytona/workspace/metabolic-injury && python3 -c " with open('quick_ref_pdf.py', 'r') as f: src = f.read() # Fix all mangled polygon calls back to draw_poly(c, [...]) # Pattern 1: draw_poly(d.canv, [... -> draw_poly(d.canv, [ # Pattern 2: draw_poly(c, [ -> already correct # Pattern 3: draw_poly(d, [... -> should be draw_poly(d.canv, [ import re src = re.sub(r'draw_poly\(d, \[', 'draw_poly(d.canv, [', src) # Also fix d.draw_poly(canv, -> draw_poly(d.canv, src = re.sub(r'd\.draw_poly\(canv,', 'draw_poly(d.canv,', src) with open('quick_ref_pdf.py', 'w') as f: f.write(src) # Verify - find all draw_poly calls matches = re.findall(r'draw_poly\([^)]+\)', src) for m in matches[:10]: print(m[:80]) print(f'Total: {len(matches)} draw_poly calls') "

Running Command

cd /home/daytona/workspace/metabolic-injury && python quick_ref_pdf.py 2>&1

This is a shared conversation. Sign in to Orris to start your own chat.