How to ensure adequacy and high quality hemodialysis?

Reading File
Finding Sources
Finding Sources
Searching PubMed

"hemodialysis adequacy" AND "Kt/V"

Reading File
Finding Sources
Finding Sources
Searching PubMed

"hemodialysis" AND "dialysis adequacy"

Reading File
Reading File
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Finding Sources
I now have comprehensive, multi-source content to write a detailed answer. Let me compile the full response.

Ensuring Adequacy and High-Quality Hemodialysis

Hemodialysis (HD) adequacy is not a single measurement but a multidimensional standard encompassing solute clearance, fluid removal, membrane quality, access function, session parameters, and clinical outcomes. Here is a complete breakdown based on nephrology textbooks.

1. Why Adequacy Matters: Historical Context

The National Cooperative Dialysis Study (NCDS), launched in 1974, was the first clinical trial to systematically evaluate HD adequacy. It aimed to control average BUN at 50 vs. 100 mg/dL, but ultimately demonstrated a strong association between Kt/V(urea) and patient outcomes. Subsequent observational studies repeatedly confirmed higher mortality risk when Kt/V falls below 1.2. The NIH-sponsored HEMO Study (late 1990s) further showed no additional survival benefit from increasing single-pool Kt/V above 1.3 per treatment three times weekly.
  • Brenner and Rector's The Kidney, p. 2734

2. Measuring Hemodialysis Adequacy

A. Kt/V (Urea Kinetic Modeling)

The primary metric. K = urea clearance, t = treatment time, V = urea volume of distribution (total body water).
  • Single-pool Kt/V (spKt/V): Target ≥ 1.4 per session (prescription target), delivered minimum ≥ 1.2
  • Equilibrated Kt/V (eKt/V): More accurate; target ≥ 1.05 - accounts for urea rebound from peripheral compartments after dialysis
  • Formula: derived from the elimination constant (K/V) using the slope of log-linear decline in urea concentration during dialysis
Kt/V properly accounts for ultrafiltration-associated clearance, which URR underestimates.
  • Brenner and Rector's The Kidney, p. 2781; Harrison's, p. 588; Comprehensive Clinical Nephrology 7th Ed.

B. Urea Reduction Ratio (URR)

A simpler, widely used measure:
URR = [(Pre-dialysis BUN − Post-dialysis BUN) / Pre-dialysis BUN] × 100
  • Target: ≥ 65% (chronic setting)
  • Limitations: does not account for ultrafiltration volume, urea generation during dialysis, or residual renal function
  • Has a curvilinear relationship with Kt/V: if Kt/V doubles from 1.5 to 3.0, URR only increases from 0.75 to 0.85
  • Harrison's, p. 588; Washington Manual, p. 4415; Goldman-Cecil Medicine

C. Conductivity Clearance

An alternative, blood-sample-free method measuring sodium clearance via the dialysate conductivity monitor. Since sodium clearance closely approximates urea clearance, this provides real-time instantaneous clearance data. Must be adjusted for cardiopulmonary recirculation and body surface area.
  • Brenner and Rector's The Kidney, p. 2902

3. Components of the Dialysis Prescription

These are the adjustable parameters that determine delivered dose (Box 63.1, Brenner & Rector):
ParameterTarget/Recommendation
Session durationMinimum 4 h per session; ≥12 h/week total
Frequency3x/week standard; 6x/week for enhanced outcomes
Blood flow rate (Qb)≥250 mL/min (typically 300-450 mL/min)
Dialysate flow rate (Qd)500-800 mL/min, countercurrent to blood
DialyzerHigh-flux; large KoA (mass transfer coefficient)
Ultrafiltration rateIndividualized; avoid >13 mL/kg/h (hypotension risk)
Dialysate compositionK 2 mEq/L, HCO3 35 mEq/L (individualized)
AnticoagulationHeparin (standard); alternatives for bleeding risk
Dialysate temperatureSlightly cool (35-36.5°C) to reduce hypotension
Vascular accessAV fistula preferred > AV graft > catheter

4. Dialyzer Selection

The dialyzer is the core determinant of solute and fluid removal quality.

Key selection criteria:

  1. Solute clearance capacity - urea (small solutes, <300 Da) via diffusion; middle molecules (300-12,000 Da, e.g., beta-2 microglobulin) via convection
  2. Ultrafiltration coefficient (Kuf) - capacity to remove fluid (mL/min/mmHg); in vitro values may be 10-20% higher than in vivo
  3. Biocompatibility - synthetic membranes (polysulfone, polyamide, polyethersulfone) are more inert than older cellulose-based membranes; reduced cytokine activation and complement activation

High-flux vs. low-flux membranes:

  • High-flux membranes: Higher hydraulic permeability, better removal of middle molecules, especially beta-2 microglobulin; required for hemodiafiltration (HDF)
  • Standard: Kuf >20 mL/h/mmHg/m², sieving coefficient for β2-microglobulin ≥0.6 for online HDF
  • Brenner and Rector's The Kidney, p. 3057; Comprehensive Clinical Nephrology, p. 2302

5. Blood and Dialysate Flow Optimization

  • Countercurrent flow (dialysate opposite to blood) maximizes the concentration gradient throughout the dialyzer length - concurrent flow reduces small solute clearance by ~10%
  • Increasing dialysate flow (Qd) reduces solute accumulation in dialysate compartment; at Qd of 500 mL/min, doubling Qd to 1000 mL/min increases urea clearance by only ~10% (diminishing returns)
  • Increasing blood flow rate (Qb) has a more direct effect on clearance; limited by access function and patient tolerance
  • After optimizing Qb and Qd, session length can be extended to further augment total solute removal
  • Brenner and Rector's The Kidney, p. 3068; Comprehensive Clinical Nephrology

6. Session Duration and Frequency

Standard regimen issues:

  • Sessions shorter than 3 hours worsen solute disequilibrium, reduce middle-molecule clearance, increase ultrafiltration rate, and increase hypotension/myocardial stunning risk
  • Sessions of 4-5 hours are optimal for most patients; beyond 5 hours, diminishing returns on urea clearance due to declining blood-side concentrations
  • The long interdialytic "weekend" interval (Saturday-to-Monday) is associated with significantly increased mortality and heart failure hospitalization

More frequent HD:

The Frequent Hemodialysis Network (FHN) Daily Trial (6x/week in-center HD vs. 3x/week) demonstrated:
  • Improved blood pressure and phosphate control
  • Reduced left ventricular mass and end-diastolic volume
  • Improved self-reported physical health and shorter post-dialysis recovery time
  • No significant effect on cognitive function or serum albumin
Nocturnal HD (6x/week at home): improved blood pressure and phosphate control; left ventricular mass benefit was modest.
  • Brenner and Rector's The Kidney, p. 3047; Harrison's, p. 589; Comprehensive Clinical Nephrology, p. 2311

7. Hemodiafiltration (HDF) - Enhanced Quality Dialysis

Online HDF combines diffusion (HD) and convection (hemofiltration) to achieve superior middle-molecule clearance:
  • Requires high-flux membrane with Kuf >20 mL/h/mmHg/m²
  • Target convection volume (CV): high-volume HDF (>20 L/session)
  • Filtration fraction (FF) must be kept ≤25% (UFR/Qb) to prevent hemoconcentration and membrane clogging; modern machines can safely allow up to 30% with dynamic transmembrane pressure optimization
  • Particularly beneficial for beta-2 microglobulin, advanced glycation end products, and other middle uremic toxins

8. Water Treatment and Dialysate Quality

Water quality is critical to dialysis safety and adequacy. Contaminated dialysate exposes the patient to ~120 L of water per session:
  • AAMI standards for bacterial contamination and endotoxin levels must be monitored monthly
  • Culture source water, treatment system checkpoints, product water, dialysate, and bicarbonate solution
  • LAL (Limulus Amebocyte Lysate) assay for endotoxin; may miss small endotoxin fragments - cytokine induction assay may provide better detection
  • Ultrapure dialysate (bacterial count <0.1 CFU/mL; endotoxin <0.03 EU/mL) reduces micro-inflammation and is required for online HDF
  • Brenner and Rector's The Kidney, p. 2726

9. Vascular Access Quality

Vascular access is the HD patient's "lifeline" and directly determines delivered dose:
Access TypeNotes
AV fistula (AVF)Gold standard; lowest infection and thrombosis rates
AV graft (AVG)Used when AVF not feasible; higher complication rate
Tunneled catheterLast resort; high infection risk, lower flow rates limit Kt/V
Access recirculation (blood returning to the arterial needle before completing systemic circulation) falsely lowers delivered Kt/V - should be investigated if URR/Kt/V is unexpectedly low.

10. Troubleshooting Inadequate Dialysis

When URR <65% or Kt/V <1.2, a systematic approach is needed:
  1. Verify the session was representative - check for shortened time, access problems, early termination
  2. Check for vascular access recirculation - most common cause of low delivered dose
  3. Review blood sampling errors - delayed post-dialysis sampling falsely lowers Kt/V
  4. Increase treatment time - most effective single intervention
  5. Use a higher-efficiency dialyzer - larger KoA
  6. Increase blood and dialysate flow rates
  7. Consider switching from catheter to AV access
  • Comprehensive Clinical Nephrology 7th Ed., p. 2301

11. Beyond Urea: Broader Adequacy Targets

Urea clearance is a surrogate. True dialysis quality also requires:
  • Volume/fluid control: Dry weight assessment; avoid excessive interdialytic weight gain; UF rate individualization
  • Electrolyte correction: Potassium, phosphorus, bicarbonate normalization
  • Phosphate removal: Better achieved with longer sessions (phosphate is predominantly intracellular, equilibrates slowly); serum phosphate <5.5 mg/dL
  • Anemia management: EPO/ESA use, iron supplementation, target Hgb 10-11.5 g/dL
  • Blood pressure control: Target predialysis <140/90 mmHg; more frequent/longer dialysis improves BP
  • Nutritional status: Monitor serum albumin, normalized protein catabolic rate (nPCR); avoid reducing dose when lean body mass decreases - maintain dose based on ideal V
  • Residual kidney function (RKF): Even small amounts of RKF contribute meaningfully to total solute clearance and should be preserved (avoid nephrotoxins, maintain hydration)

Summary: Key Adequacy Targets

MetricMinimum Target
spKt/V≥1.2 delivered; ≥1.4 prescribed
eKt/V≥1.05
URR≥65%
Session duration≥4 h; ≥12 h/week total
Frequency≥3x/week
Blood flow rate≥250 mL/min
Dialysate flow rate500-800 mL/min
DialyzerHigh-flux synthetic preferred
Serum phosphate<5.5 mg/dL

Sources:
  • [Brenner and Rector's The Kidney, 2-Volume Set](Brenner & Rector) - chapters on hemodialysis adequacy, dialyzer choice, prescription (pp. 2729-3075)
  • Harrison's Principles of Internal Medicine 22E (2025) - Goals of Dialysis section, p. 587-589
  • Comprehensive Clinical Nephrology, 7th Edition - Treatment Time, Frequency, and HDF Dose sections, p. 2296-2311
  • Goldman-Cecil Medicine International Edition - Dialysis chapter, p. 3143-3170
  • Washington Manual of Medical Therapeutics - Prescription and Adequacy, p. 4412-4421

What causes muscle cramping during or post HD?

Finding Sources
Finding Sources
Searching PubMed

"muscle cramps" AND "hemodialysis"

Finding Sources
Finding Sources
Reading Article

PMID: 36691882

Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Finding Sources
Reading Article

PMID: 40725745

Finding Sources
Reading File
I now have comprehensive, authoritative content from both Brenner & Rector and Comprehensive Clinical Nephrology. I have everything needed for a thorough answer.

Muscle Cramping During or After Hemodialysis

Muscle cramps are among the most common and distressing intradialytic complications. They occur during or after approximately 60% of HD treatments (Brenner & Rector), are quite painful, reduce quality of life, and are a leading cause of early session termination - accounting for 15% of premature dialysis discontinuations (Comprehensive Clinical Nephrology 7th Ed.).

Epidemiology and Presentation

  • Occur in 5-20% of HD patients, predominantly affecting the legs
  • Onset typically late in the dialysis session
  • Electromyography shows increased tonic muscle electrical activity throughout dialysis
  • Serum creatine kinase may be elevated
  • More common in patients with large interdialytic weight gains, aggressive ultrafiltration, and low dry weight targets

Pathogenesis and Causes

The exact pathogenesis is not fully understood, but several overlapping mechanisms are implicated:

1. Volume Contraction and Hypotension (Primary Mechanism)

Excessive or rapid ultrafiltration causes intravascular volume depletion, which triggers vasoconstriction and impaired oxygen delivery to muscle. When cramping accompanies hypotensive episodes, this hemodynamic mechanism is strongly implicated.
  • High UF rates (>10-13 mL/kg/h) are independently associated with cardiovascular morbidity and muscle cramps
  • Brenner and Rector's The Kidney, p. 2749

2. Hypoosmolality / Osmolar Shifts

Solute diffusion during HD reduces plasma osmolality. The resulting plasma hypoosmolality and cell osmotic fluid shifts cause water to move into muscle cells, altering intracellular ion concentrations and triggering spontaneous muscle contractions.
  • This is why cramps often signal that the patient has reached or exceeded their target (dry) weight
  • Comprehensive Clinical Nephrology 7th Ed., p. 1304

3. Hypomagnesemia

Magnesium plays a critical role in neuromuscular excitability and muscle relaxation. Dialysis can lower serum magnesium (low dialysate Mg, poor intake), promoting abnormal muscle firing. Standard dialysate magnesium concentrations are typically 0.5-1 mEq/L to prevent intradialytic hypomagnesemia.
  • Brenner and Rector's The Kidney, p. 428; Comprehensive Clinical Nephrology

4. L-Carnitine Deficiency

Carnitine is freely dialyzable and lost with each session. Carnitine deficiency impairs fatty acid metabolism in muscle, predisposing to fatigue and cramping. However, the evidence for L-carnitine supplementation specifically for cramps remains inconsistent across studies.
  • Comprehensive Clinical Nephrology, p. 1304; Kljajić et al., J Clin Med 2025 [PMID: 40725745]

5. Accumulation of Uremic Solutes

Accumulation of unidentified uremic toxins between sessions may predispose muscle tissue to cramping, independent of the acute hemodynamic events of dialysis.
  • Brenner and Rector's The Kidney, p. 2749

6. Nutritional Deficiencies

Various nutritional deficiencies (vitamin E, electrolytes) may lower the threshold for muscle cramping in dialysis patients.

Summary of Causative Factors

MechanismKey Driver
Excessive/rapid UFVolume contraction, tissue hypoperfusion
Plasma hypoosmolalityOsmolar shift into muscle cells
HypomagnesemiaNeuromuscular hyperexcitability
L-Carnitine deficiencyImpaired muscle fatty acid metabolism
Uremic toxin accumulationIncreased muscle irritability
Nutritional deficiencies (Vit E, electrolytes)Lowered cramp threshold

Acute Management

Directed at raising plasma osmolality or correcting hypovolemia:
InterventionDoseNotes
50% Dextrose in water (D50W)25-50 mL IVPreferred in non-diabetics; no thirst/fluid gain
23-23.5% Hypertonic saline15-20 mL IVEffective; causes thirst, post-dialytic weight gain
25% Mannitol50-100 mL IVEffective; repeated use causes thirst and fluid overload
Normal saline bolus + cease UF100-200 mLWhen cramps accompany hypotension
Note: Hypertonic saline and D50W are equally effective acutely. D50W is generally preferred. All three osmotic agents are less desirable if used repeatedly due to volume consequences.

Prevention

Prescription adjustments:

  • Reassess and potentially increase dry weight by 0.5 kg if no signs of fluid overload
  • Reduce the UF rate by extending session duration or increasing frequency
  • Reduce dietary sodium intake to limit interdialytic weight gain
  • Use sodium modeling (starting dialysate Na 145-155 mEq/L, tapering linearly to 135-140 mEq/L by end of session) - may reduce osmolar drop
  • Individualize dialysate sodium to approximate the patient's serum sodium

Pharmacologic prevention:

  • Vitamin E (taken before bedtime) - small studies suggest benefit; considered safe
  • Quinine sulfate (250-300 mg, 2 h before dialysis) - historically used; effective in some patients, but the FDA has issued a black box warning due to drug-induced thrombotic microangiopathy, QT prolongation, and hypersensitivity reactions - largely abandoned in the US
  • Oxazepam (5-10 mg, 2 h before dialysis) - some evidence of benefit
  • L-Carnitine (20 mg/kg/session IV post-dialysis) - theoretical rationale; meta-analysis inconclusive
  • Magnesium supplementation - if hypomagnesemia documented
  • Enalapril 5 mg twice weekly - anecdotal reports; proposed mechanism is angiotensin II-mediated thirst inhibition

Non-pharmacologic:

  • Stretching exercises before/during dialysis
  • Creatine monohydrate (12 mg before dialysis)
  • Intradialytic blood volume biofeedback systems to guide UF and reduce cramp incidence
  • Massage, aromatherapy, reflexology, acupressure - a 2023 meta-analysis (14 RCTs) found non-pharmacological interventions (exercise, aromatherapy, reflexology, massage, acupressure) effective for reducing muscle cramp severity in HD patients [PMID: 36691882]

Sources:

Create a quick reference PDF on hemodialysis complications and management strategies

Reading File
Running Command

mkdir -p /home/daytona/workspace/hd-complications-pdf && ls /home/daytona/worksp…

Writing File

~/hd-complications-pdf/generate_pdf.py

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

OUTPUT = "/home/daytona/workspace/hd-complications-pdf/HD_Complications_Quick_Reference.pdf"

# ── Colour palette ──────────────────────────────────────────────────────────
NAVY      = HexColor("#1A3557")
TEAL      = HexColor("#1E7F8E")
LIGHT_BLU = HexColor("#D6EAF8")
LIGHT_GRN = HexColor("#D5F5E3")
LIGHT_YEL = HexColor("#FEF9E7")
LIGHT_RED = HexColor("#FDEDEC")
LIGHT_PUR = HexColor("#F4ECF7")
LIGHT_ORG = HexColor("#FDEBD0")
MID_TEAL  = HexColor("#A9CCE3")
ORANGE    = HexColor("#E67E22")
RED       = HexColor("#C0392B")
GREEN     = HexColor("#1E8449")
GREY_BG   = HexColor("#F2F3F4")
DARK_GREY = HexColor("#2C3E50")
MID_GREY  = HexColor("#5D6D7E")

# ── Document setup ───────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=1.8*cm, rightMargin=1.8*cm,
    topMargin=2*cm, bottomMargin=2*cm,
    title="Hemodialysis Complications – Quick Reference",
    author="Orris Medical Reference"
)

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

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

def style(name, parent="Normal", **kw):
    s = ParagraphStyle(name, parent=base[parent])
    for k, v in kw.items():
        setattr(s, k, v)
    return s

S_COVER_TITLE = style("CoverTitle",
    fontSize=26, textColor=white, leading=32,
    alignment=TA_CENTER, fontName="Helvetica-Bold")
S_COVER_SUB = style("CoverSub",
    fontSize=13, textColor=HexColor("#D6EAF8"), leading=18,
    alignment=TA_CENTER, fontName="Helvetica")
S_COVER_DATE = style("CoverDate",
    fontSize=10, textColor=HexColor("#A9CCE3"), leading=14,
    alignment=TA_CENTER, fontName="Helvetica-Oblique")

S_SECTION = style("Section",
    fontSize=13, textColor=white, leading=17,
    fontName="Helvetica-Bold", alignment=TA_LEFT,
    leftIndent=6, spaceAfter=4)
S_SUBHEAD = style("Subhead",
    fontSize=10.5, textColor=NAVY, leading=14,
    fontName="Helvetica-Bold", spaceBefore=6, spaceAfter=2)
S_BODY = style("Body",
    fontSize=9, textColor=DARK_GREY, leading=13,
    fontName="Helvetica", spaceAfter=2)
S_BULLET = style("Bullet",
    fontSize=9, textColor=DARK_GREY, leading=13,
    fontName="Helvetica", leftIndent=14, spaceAfter=1,
    bulletIndent=5, bulletFontSize=9)
S_TABLE_HDR = style("TblHdr",
    fontSize=9, textColor=white, leading=12,
    fontName="Helvetica-Bold", alignment=TA_CENTER)
S_TABLE_CELL = style("TblCell",
    fontSize=8.5, textColor=DARK_GREY, leading=11,
    fontName="Helvetica")
S_TABLE_CELL_C = style("TblCellC",
    fontSize=8.5, textColor=DARK_GREY, leading=11,
    fontName="Helvetica", alignment=TA_CENTER)
S_FOOTER = style("Footer",
    fontSize=7.5, textColor=MID_GREY, alignment=TA_CENTER,
    fontName="Helvetica-Oblique")
S_CAPTION = style("Caption",
    fontSize=8, textColor=MID_GREY, leading=11,
    fontName="Helvetica-Oblique", alignment=TA_CENTER)
S_ALERT = style("Alert",
    fontSize=9, textColor=RED, leading=13,
    fontName="Helvetica-Bold", leftIndent=8)
S_NOTE = style("Note",
    fontSize=8.5, textColor=MID_GREY, leading=12,
    fontName="Helvetica-Oblique", leftIndent=8)

def b(text): return f"<b>{text}</b>"
def i(text): return f"<i>{text}</i>"
def colored(text, col): return f'<font color="{col}">{text}</font>'

# ── Helper builders ───────────────────────────────────────────────────────────
def section_header(title, color=TEAL):
    tbl = Table([[Paragraph(title, S_SECTION)]], colWidths=[W])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), color),
        ("ROUNDEDCORNERS", [4]),
        ("TOPPADDING", (0,0), (-1,-1), 5),
        ("BOTTOMPADDING", (0,0), (-1,-1), 5),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
    ]))
    return tbl

def colored_box(content_rows, bg_color, border_color=None):
    """Wrap rows in a shaded box."""
    bc = border_color or bg_color
    tbl = Table(content_rows, colWidths=[W])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), bg_color),
        ("BOX", (0,0), (-1,-1), 0.5, bc),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 10),
        ("RIGHTPADDING", (0,0), (-1,-1), 10),
    ]))
    return tbl

def two_col_table(headers, rows, col_widths, header_bg=NAVY):
    """Generic table with styled header."""
    data = [[Paragraph(h, S_TABLE_HDR) for h in headers]]
    for row in rows:
        data.append([Paragraph(str(c), S_TABLE_CELL) if i==0 else
                     Paragraph(str(c), S_TABLE_CELL) for i,c in enumerate(row)])
    tbl = Table(data, colWidths=col_widths, repeatRows=1)
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,0), header_bg),
        ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, GREY_BG]),
        ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
        ("TOPPADDING", (0,0), (-1,-1), 4),
        ("BOTTOMPADDING", (0,0), (-1,-1), 4),
        ("LEFTPADDING", (0,0), (-1,-1), 6),
        ("RIGHTPADDING", (0,0), (-1,-1), 6),
        ("VALIGN", (0,0), (-1,-1), "TOP"),
    ]))
    return tbl

def bullet(text): return Paragraph(f"• {text}", S_BULLET)
def body(text):   return Paragraph(text, S_BODY)
def sp(h=4):      return Spacer(1, h)
def hr():         return HRFlowable(width="100%", thickness=0.5, color=HexColor("#BDC3C7"), spaceAfter=4, spaceBefore=4)

# ─────────────────────────────────────────────────────────────────────────────
# PAGE CALLBACKS (header / footer)
# ─────────────────────────────────────────────────────────────────────────────
def on_page(canvas, doc):
    canvas.saveState()
    # Top stripe
    canvas.setFillColor(NAVY)
    canvas.rect(0, A4[1]-1*cm, A4[0], 1*cm, fill=1, stroke=0)
    canvas.setFont("Helvetica-Bold", 8)
    canvas.setFillColor(white)
    canvas.drawString(1.8*cm, A4[1]-0.65*cm, "HD COMPLICATIONS – QUICK REFERENCE")
    canvas.setFont("Helvetica", 8)
    canvas.drawRightString(A4[0]-1.8*cm, A4[1]-0.65*cm, f"Page {doc.page}")
    # Bottom stripe
    canvas.setFillColor(GREY_BG)
    canvas.rect(0, 0, A4[0], 0.9*cm, fill=1, stroke=0)
    canvas.setFont("Helvetica-Oblique", 7)
    canvas.setFillColor(MID_GREY)
    canvas.drawCentredString(A4[0]/2, 0.32*cm,
        "For clinical reference only. Always consult institutional protocols and current guidelines.")
    canvas.restoreState()

def on_first_page(canvas, doc):
    # Full cover background
    canvas.setFillColor(NAVY)
    canvas.rect(0, 0, A4[0], A4[1], fill=1, stroke=0)
    # Decorative teal band
    canvas.setFillColor(TEAL)
    canvas.rect(0, A4[1]*0.38, A4[0], 4, fill=1, stroke=0)
    canvas.rect(0, A4[1]*0.35, A4[0], 4, fill=1, stroke=0)

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

# ══════════════════════════════════════════════════════════
# COVER PAGE
# ══════════════════════════════════════════════════════════
story.append(Spacer(1, 5.5*cm))
story.append(Paragraph("HEMODIALYSIS COMPLICATIONS", S_COVER_TITLE))
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph("Quick Reference Guide for Clinical Practice", S_COVER_SUB))
story.append(Spacer(1, 0.5*cm))
story.append(HRFlowable(width="60%", thickness=1, color=TEAL, spaceAfter=8, spaceBefore=4))
story.append(Spacer(1, 0.4*cm))
story.append(Paragraph(
    "Intradialytic &amp; Post-Dialytic Complications · Causes · Management Strategies",
    S_COVER_SUB))
story.append(Spacer(1, 4*cm))
story.append(Paragraph("Based on Brenner &amp; Rector's The Kidney · Harrison's PoIM 22E · "
                        "Comprehensive Clinical Nephrology 7E · Goldman-Cecil Medicine",
                        S_COVER_DATE))
story.append(Spacer(1, 0.3*cm))
story.append(Paragraph("July 2026", S_COVER_DATE))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 2 – OVERVIEW & QUICK TARGETS
# ══════════════════════════════════════════════════════════
story.append(section_header("OVERVIEW OF HEMODIALYSIS COMPLICATIONS"))
story.append(sp(6))
story.append(body(
    "Hemodialysis (HD) is a life-sustaining but physiologically demanding procedure. "
    "With over 400,000 patients receiving >60 million HD sessions/year in the US alone, "
    "complications—though infrequent per session—are clinically significant in aggregate. "
    "Complications are classified as <b>intradialytic</b> (occurring during the session) "
    "or <b>post-dialytic</b> (occurring after). Recognition and systematic management "
    "are essential to preserve patient safety and treatment adequacy."))
story.append(sp(8))

# Quick targets box
story.append(Paragraph("Key Adequacy Targets", S_SUBHEAD))
targets = [
    ["Parameter", "Target", "Notes"],
    ["spKt/V", "≥ 1.4 prescribed / ≥ 1.2 delivered", "Single-pool Kt/V per session"],
    ["eKt/V", "≥ 1.05", "Equilibrated (accounts for urea rebound)"],
    ["URR", "≥ 65%", "Urea Reduction Ratio per session"],
    ["Session duration", "≥ 4 h per session; ≥ 12 h/week", "Minimum; individualize upward"],
    ["Blood flow rate", "≥ 250 mL/min (250–450)", "Limited by access function"],
    ["Dialysate flow rate", "500–800 mL/min (countercurrent)", "Higher rates have diminishing returns"],
    ["UF rate", "< 10–13 mL/kg/h", "Higher rates ↑ cardiovascular risk"],
    ["Dialyzer", "High-flux synthetic membrane", "Polysulfone preferred"],
    ["Dialysate Na", "Match patient's serum Na (~138–140 mEq/L)", "Avoid fixed high Na"],
    ["Dialysate K", "2 mEq/L (standard)", "Adjust for pre-HD K level"],
    ["Serum phosphate", "< 5.5 mg/dL", "Longer sessions improve removal"],
]
col_w = [W*0.22, W*0.38, W*0.40]
tbl_data = [[Paragraph(h, S_TABLE_HDR) for h in targets[0]]]
for row in targets[1:]:
    tbl_data.append([Paragraph(row[0], S_TABLE_CELL),
                     Paragraph(row[1], S_TABLE_CELL),
                     Paragraph(row[2], S_TABLE_CELL)])
t = Table(tbl_data, colWidths=col_w, repeatRows=1)
t.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), NAVY),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_BLU]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "MIDDLE"),
]))
story.append(t)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 3 – INTRADIALYTIC HYPOTENSION
# ══════════════════════════════════════════════════════════
story.append(section_header("1. INTRADIALYTIC HYPOTENSION (IDH)", NAVY))
story.append(sp(5))

# Definition box
story.append(colored_box([
    [Paragraph("<b>Definition (KDOQI):</b> Decrease in systolic BP ≥ 20 mmHg "
               "<i>or</i> decrease in MAP ≥ 10 mmHg associated with clinical symptoms requiring intervention.", S_BODY)]
], LIGHT_BLU, MID_TEAL))
story.append(sp(6))
story.append(body(f"<b>Frequency:</b> Occurs in 15–30% of all HD sessions; >50% of sessions in susceptible patients. "
                  "Strongly associated with large interdialytic weight gains, female sex, diabetes, older age, longer vintage, and underlying cardiac disease."))
story.append(sp(8))

idh_data = [
    [Paragraph("CAUSES", S_TABLE_HDR), Paragraph("PREVENTION", S_TABLE_HDR), Paragraph("ACUTE MANAGEMENT", S_TABLE_HDR)],
    [
        Paragraph("• Excessive/rapid UF (>10–13 mL/kg/h)\n• Impaired vascular refilling\n• Reduced cardiac reserve\n"
                  "• Heat transfer from dialysate → vasodilation\n• ↓ plasma osmolality (solute removal)\n"
                  "• Antihypertensive medications\n• Food intake during dialysis\n• Low dialysate Ca or Mg\n• Acetate-based dialysate", S_TABLE_CELL),
        Paragraph("• Reassess dry weight\n• ↓ interdialytic sodium/fluid intake\n• Individualize dialysate Na ≈ serum Na\n"
                  "• Cool dialysate (35–36.5°C)\n• Dialysate Ca 2.25–2.5 mEq/L\n• Avoid antihypertensives pre-HD\n"
                  "• No food during HD (esp. diabetics)\n• UF modeling / sequential UF\n• Extend session or ↑ frequency\n"
                  "• Midodrine 2.5–10 mg, 15–30 min pre-HD (refractory cases)\n• Bicarbonate (not acetate) dialysate", S_TABLE_CELL),
        Paragraph("• ↓ UF rate or pause UF\n• Supine / Trendelenburg position\n• Normal saline 100–250 mL bolus\n"
                  "• ↓ blood flow rate\n• O₂ supplementation\n• If no reversal: discontinue HD\n"
                  "• Rule out myocardial ischemia, pericardial effusion", S_TABLE_CELL),
    ]
]
idh_tbl = Table(idh_data, colWidths=[W*0.33, W*0.34, W*0.33], repeatRows=1)
idh_tbl.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [LIGHT_BLU]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 5), ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(idh_tbl)
story.append(sp(8))
story.append(Paragraph(
    "<i>Note: High UF rates (>10–13 mL/kg/h) are independently associated with increased cardiovascular morbidity and mortality. "
    "Midodrine side effects include supine hypertension, urinary retention, and pilomotor reactions.</i>", S_NOTE))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 4 – MUSCLE CRAMPS
# ══════════════════════════════════════════════════════════
story.append(section_header("2. MUSCLE CRAMPS", NAVY))
story.append(sp(5))
story.append(colored_box([
    [Paragraph("<b>Frequency:</b> Occur during/after ~60% of HD sessions (Brenner &amp; Rector). "
               "Account for <b>15% of premature session discontinuations</b>. "
               "Predominantly affect legs; onset typically late in the session.", S_BODY)]
], LIGHT_RED, RED))
story.append(sp(6))

cramp_patho = [
    [Paragraph("PATHOGENESIS", S_TABLE_HDR), Paragraph("MECHANISM", S_TABLE_HDR)],
    [Paragraph("Volume contraction + hypotension", S_TABLE_CELL),
     Paragraph("Vasoconstriction → impaired O₂ delivery to muscle; occurs with excessive UF or over-reaching dry weight", S_TABLE_CELL)],
    [Paragraph("Plasma hypoosmolality", S_TABLE_CELL),
     Paragraph("Solute diffusion ↓ plasma osmolality → osmotic fluid shift into muscle cells → altered intracellular ion concentrations → spontaneous contraction", S_TABLE_CELL)],
    [Paragraph("Hypomagnesemia", S_TABLE_CELL),
     Paragraph("Mg²⁺ is lost during dialysis; critical for neuromuscular stability. Dialysate Mg typically 0.5–1 mEq/L", S_TABLE_CELL)],
    [Paragraph("L-Carnitine deficiency", S_TABLE_CELL),
     Paragraph("Carnitine is freely dialyzable; deficiency impairs muscle fatty acid oxidation → fatigue + cramping", S_TABLE_CELL)],
    [Paragraph("Uremic toxin accumulation", S_TABLE_CELL),
     Paragraph("Unidentified uremic solutes accumulating between sessions may increase muscle irritability", S_TABLE_CELL)],
    [Paragraph("Nutritional deficiencies", S_TABLE_CELL),
     Paragraph("Vitamin E deficiency may lower cramp threshold", S_TABLE_CELL)],
]
cramp_tbl = Table(cramp_patho, colWidths=[W*0.35, W*0.65], repeatRows=1)
cramp_tbl.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), NAVY),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_RED]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(cramp_tbl)
story.append(sp(8))

# Acute management
story.append(Paragraph("Acute Management – Raise Plasma Osmolality", S_SUBHEAD))
acute_cramp = [
    [Paragraph("Agent", S_TABLE_HDR), Paragraph("Dose", S_TABLE_HDR), Paragraph("Notes", S_TABLE_HDR)],
    [Paragraph("50% Dextrose (D50W)", S_TABLE_CELL), Paragraph("25–50 mL IV", S_TABLE_CELL),
     Paragraph("Preferred (non-diabetics); no thirst or significant fluid gain", S_TABLE_CELL)],
    [Paragraph("23–23.5% Hypertonic saline", S_TABLE_CELL), Paragraph("15–20 mL IV", S_TABLE_CELL),
     Paragraph("Effective; causes post-dialytic thirst and ↑ IDWG", S_TABLE_CELL)],
    [Paragraph("25% Mannitol", S_TABLE_CELL), Paragraph("50–100 mL IV", S_TABLE_CELL),
     Paragraph("Effective; repeated use → thirst, fluid overload", S_TABLE_CELL)],
    [Paragraph("Normal saline + pause UF", S_TABLE_CELL), Paragraph("100–200 mL IV", S_TABLE_CELL),
     Paragraph("When cramps accompany hypotension", S_TABLE_CELL)],
]
act = Table(acute_cramp, colWidths=[W*0.28, W*0.20, W*0.52], repeatRows=1)
act.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, GREY_BG]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(act)
story.append(sp(8))

story.append(Paragraph("Prevention Strategies", S_SUBHEAD))
prev_cramp = [
    [Paragraph("Strategy", S_TABLE_HDR), Paragraph("Details", S_TABLE_HDR)],
    [Paragraph("Prescription adjustment", S_TABLE_CELL),
     Paragraph("↑ dry weight by 0.5 kg if no fluid overload; extend session; ↑ frequency; ↓ UF rate", S_TABLE_CELL)],
    [Paragraph("Dietary counselling", S_TABLE_CELL),
     Paragraph("Reduce Na intake → ↓ IDWG → lower required UF rate per session", S_TABLE_CELL)],
    [Paragraph("Sodium modeling", S_TABLE_CELL),
     Paragraph("Start dialysate Na 145–155 mEq/L; linear taper to 135–140 mEq/L by end of session", S_TABLE_CELL)],
    [Paragraph("Vitamin E", S_TABLE_CELL),
     Paragraph("Taken before bedtime; small RCTs suggest benefit; safe and well-tolerated", S_TABLE_CELL)],
    [Paragraph("Quinine sulfate 250–300 mg", S_TABLE_CELL),
     Paragraph("⚠ FDA BLACK BOX WARNING: risk of TMA, QT prolongation, hypersensitivity. Largely abandoned in the US.", S_TABLE_CELL)],
    [Paragraph("Oxazepam 5–10 mg", S_TABLE_CELL),
     Paragraph("Given 2 h pre-dialysis; some evidence of benefit", S_TABLE_CELL)],
    [Paragraph("L-Carnitine 20 mg/kg/session", S_TABLE_CELL),
     Paragraph("IV post-dialysis; meta-analysis results inconsistent for cramps specifically", S_TABLE_CELL)],
    [Paragraph("Magnesium supplementation", S_TABLE_CELL),
     Paragraph("If hypomagnesemia documented; also stretching, creatine monohydrate 12 mg pre-HD", S_TABLE_CELL)],
    [Paragraph("Blood volume biofeedback", S_TABLE_CELL),
     Paragraph("Automated UF adjustment guided by continuous relative blood volume monitoring", S_TABLE_CELL)],
    [Paragraph("Non-pharmacological", S_TABLE_CELL),
     Paragraph("Exercise, aromatherapy, reflexology, massage, acupressure (meta-analysis of 14 RCTs supports efficacy)", S_TABLE_CELL)],
]
prev = Table(prev_cramp, colWidths=[W*0.30, W*0.70], repeatRows=1)
prev.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), NAVY),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_YEL]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    # Highlight quinine row in red
    ("BACKGROUND", (0,5), (-1,5), LIGHT_RED),
    ("TEXTCOLOR", (0,5), (0,5), RED),
]))
story.append(prev)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 5 – CARDIOVASCULAR & ARRHYTHMIAS + DISEQUILIBRIUM
# ══════════════════════════════════════════════════════════
story.append(section_header("3. CARDIOVASCULAR COMPLICATIONS", NAVY))
story.append(sp(5))

cv_data = [
    [Paragraph("COMPLICATION", S_TABLE_HDR), Paragraph("CAUSES / RISK FACTORS", S_TABLE_HDR), Paragraph("MANAGEMENT", S_TABLE_HDR)],
    [Paragraph("Myocardial stunning / LV dysfunction", S_TABLE_CELL),
     Paragraph("• Rapid UF → ↓ preload\n• Sympathetic activation\n• Heat transfer from dialysate\n• Dialysis-induced regional wall motion abnormalities", S_TABLE_CELL),
     Paragraph("• Cool dialysate (35–36.5°C)\n• ↓ UF rate; extend session\n• Avoid food during HD\n• Echocardiography if recurrent IDH", S_TABLE_CELL)],
    [Paragraph("Cardiac arrhythmias", S_TABLE_CELL),
     Paragraph("• Electrolyte shifts (K⁺, Ca²⁺, Mg²⁺)\n• Low dialysate Ca\n• Pre-existing LVH, IHD\n• Autonomic dysregulation", S_TABLE_CELL),
     Paragraph("• Individualize dialysate K (min 2 mEq/L)\n• Dialysate Ca 2.25–2.5 mEq/L\n• Avoid rapid K removal\n• Cardiac monitoring in high-risk patients", S_TABLE_CELL)],
    [Paragraph("Hypertension (post-HD)", S_TABLE_CELL),
     Paragraph("• Fluid overload / inadequate UF\n• RAAS activation\n• Sympathetic overactivity\n• Endothelial dysfunction", S_TABLE_CELL),
     Paragraph("• Achieve dry weight\n• Restrict dietary Na\n• More frequent/longer HD\n• Antihypertensives after HD session", S_TABLE_CELL)],
    [Paragraph("Increased mortality risk\n(long interdialytic interval)", S_TABLE_CELL),
     Paragraph("• Extended Saturday-to-Monday gap\n• Fluid/solute accumulation\n• Cardiovascular stress", S_TABLE_CELL),
     Paragraph("• Minimise long interval\n• Consider 6×/week HD for high-risk patients\n• Monitor for post-weekend presentations", S_TABLE_CELL)],
]
cv = Table(cv_data, colWidths=[W*0.22, W*0.38, W*0.40], repeatRows=1)
cv.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_BLU]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 5), ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(cv)
story.append(sp(10))

# Disequilibrium syndrome
story.append(section_header("4. DIALYSIS DISEQUILIBRIUM SYNDROME (DDS)", NAVY))
story.append(sp(5))
dds_data = [
    [Paragraph("FEATURE", S_TABLE_HDR), Paragraph("DETAILS", S_TABLE_HDR)],
    [Paragraph("Definition", S_TABLE_CELL),
     Paragraph("Neurological syndrome resulting from rapid solute removal in severely uremic patients, especially at dialysis initiation", S_TABLE_CELL)],
    [Paragraph("Mechanism", S_TABLE_CELL),
     Paragraph("Rapid ↓ plasma osmolality → osmotic gradient → cerebral oedema. Brain retains 'idiogenic osmoles' when plasma urea falls faster than CNS equilibration.", S_TABLE_CELL)],
    [Paragraph("Symptoms (mild)", S_TABLE_CELL),
     Paragraph("Nausea, vomiting, headache, restlessness, blurred vision", S_TABLE_CELL)],
    [Paragraph("Symptoms (severe)", S_TABLE_CELL),
     Paragraph("Seizures, obtundation, coma (rare but life-threatening)", S_TABLE_CELL)],
    [Paragraph("Risk factors", S_TABLE_CELL),
     Paragraph("Very high BUN pre-dialysis, first HD session, rapid solute removal, paediatric patients, pre-existing neurological disease", S_TABLE_CELL)],
    [Paragraph("Prevention", S_TABLE_CELL),
     Paragraph("Use low-efficiency dialyzer initially; short first sessions (2 h); slow blood flow rate (150–200 mL/min); target BUN reduction ≤30–40% in first session", S_TABLE_CELL)],
    [Paragraph("Management", S_TABLE_CELL),
     Paragraph("Stop or slow HD; IV mannitol (1 g/kg) or hypertonic saline; seizure management (benzodiazepines); supportive care", S_TABLE_CELL)],
]
dds = Table(dds_data, colWidths=[W*0.25, W*0.75], repeatRows=1)
dds.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), NAVY),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_PUR]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(dds)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 6 – ACCESS & INFECTIOUS COMPLICATIONS
# ══════════════════════════════════════════════════════════
story.append(section_header("5. VASCULAR ACCESS COMPLICATIONS", NAVY))
story.append(sp(5))
access_data = [
    [Paragraph("COMPLICATION", S_TABLE_HDR), Paragraph("CAUSES", S_TABLE_HDR), Paragraph("MANAGEMENT", S_TABLE_HDR)],
    [Paragraph("AV fistula / graft thrombosis", S_TABLE_CELL),
     Paragraph("• Stenosis (intimal hyperplasia)\n• Hypotension\n• External compression\n• Hypercoagulability", S_TABLE_CELL),
     Paragraph("• Fistulogram\n• Thrombolysis or thrombectomy\n• Angioplasty / stent for stenosis\n• Anticoagulation if indicated", S_TABLE_CELL)],
    [Paragraph("Stenosis", S_TABLE_CELL),
     Paragraph("• Venous outflow stenosis\n• Subclavian stenosis (tunneled catheter history)\n• Neointimal hyperplasia", S_TABLE_CELL),
     Paragraph("• Surveillance with access flow measurement\n• Angioplasty (PTA) ± stenting\n• Surgical revision if refractory", S_TABLE_CELL)],
    [Paragraph("Access recirculation", S_TABLE_CELL),
     Paragraph("• Stenosis reducing forward flow\n• Reversed needle placement\n• Low blood flow", S_TABLE_CELL),
     Paragraph("• Measure recirculation (urea method or ultrasound dilution)\n• Treat underlying stenosis\n• Reduces delivered Kt/V", S_TABLE_CELL)],
    [Paragraph("Catheter infection / bacteraemia", S_TABLE_CELL),
     Paragraph("• Biofilm formation\n• Hub contamination\n• Femoral > IJ > subclavian (infection risk)", S_TABLE_CELL),
     Paragraph("• Blood cultures × 2\n• Empiric broad-spectrum antibiotics (Staph + GNR coverage)\n• Catheter removal after 48 h of negative cultures\n• Antibiotics ≥ 2–3 weeks for bacteraemia", S_TABLE_CELL)],
    [Paragraph("Steal syndrome", S_TABLE_CELL),
     Paragraph("• High-flow AV access diverts blood from distal limb\n• Large calibre graft / fistula", S_TABLE_CELL),
     Paragraph("• Banding\n• DRIL procedure (Distal Revascularisation Interval Ligation)\n• Access revision or ligation if severe", S_TABLE_CELL)],
]
acc = Table(access_data, colWidths=[W*0.22, W*0.37, W*0.41], repeatRows=1)
acc.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_GRN]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 5), ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(acc)
story.append(sp(8))

story.append(colored_box([
    [Paragraph("<b>Access Hierarchy:</b> AV Fistula (gold standard) > AV Graft > Tunneled Catheter (last resort). "
               "Catheters carry the highest infection risk and lowest flow rates, limiting delivered Kt/V.", S_BODY)]
], LIGHT_GRN, GREEN))
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 7 – METABOLIC & OTHER COMPLICATIONS
# ══════════════════════════════════════════════════════════
story.append(section_header("6. METABOLIC & ELECTROLYTE COMPLICATIONS", NAVY))
story.append(sp(5))

meta_data = [
    [Paragraph("COMPLICATION", S_TABLE_HDR), Paragraph("CAUSE", S_TABLE_HDR), Paragraph("MANAGEMENT", S_TABLE_HDR)],
    [Paragraph("Hyperkalemia (pre-HD)", S_TABLE_CELL),
     Paragraph("Dietary excess, metabolic acidosis, tissue catabolism, missed sessions", S_TABLE_CELL),
     Paragraph("Dietary K restriction; standard dialysate K 2 mEq/L; correct acidosis; avoid rapid K removal (arrhythmia risk)", S_TABLE_CELL)],
    [Paragraph("Hyperphosphatemia", S_TABLE_CELL),
     Paragraph("Poor dietary control; predominantly intracellular → slow equilibration; inadequate dialysis time", S_TABLE_CELL),
     Paragraph("Phosphate binders (Ca-based, non-Ca-based, sevelamer); longer HD sessions; dietary counselling; target PO₄ <5.5 mg/dL", S_TABLE_CELL)],
    [Paragraph("Metabolic acidosis", S_TABLE_CELL),
     Paragraph("Loss of buffering capacity; urea generation; inadequate dialysate bicarbonate", S_TABLE_CELL),
     Paragraph("Dialysate HCO₃ 35 mEq/L (standard); target pre-HD HCO₃ 22–26 mEq/L; adequate Kt/V", S_TABLE_CELL)],
    [Paragraph("Hyponatremia (post-HD)", S_TABLE_CELL),
     Paragraph("Low dialysate Na relative to plasma; excessive water gain", S_TABLE_CELL),
     Paragraph("Individualise dialysate Na; restrict free water intake; avoid fixed low dialysate Na", S_TABLE_CELL)],
    [Paragraph("Hypocalcemia / Hypercalcemia", S_TABLE_CELL),
     Paragraph("Low dialysate Ca; over-correction with Ca supplements; hyperparathyroidism", S_TABLE_CELL),
     Paragraph("Dialysate Ca 2.25–2.5 mEq/L; cinacalcet; vitamin D analogues; parathyroidectomy for severe HPT", S_TABLE_CELL)],
    [Paragraph("Hypomagnesemia", S_TABLE_CELL),
     Paragraph("Inadequate dialysate Mg; poor dietary intake; diuretic use", S_TABLE_CELL),
     Paragraph("Dialysate Mg 0.5–1 mEq/L; oral Mg supplementation if symptomatic", S_TABLE_CELL)],
]
meta = Table(meta_data, colWidths=[W*0.22, W*0.38, W*0.40], repeatRows=1)
meta.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_ORG]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 5), ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(meta)
story.append(sp(10))

story.append(section_header("7. DIALYSATE & WATER-RELATED COMPLICATIONS", NAVY))
story.append(sp(5))
water_data = [
    [Paragraph("PROBLEM", S_TABLE_HDR), Paragraph("CAUSE / MECHANISM", S_TABLE_HDR), Paragraph("PREVENTION / MANAGEMENT", S_TABLE_HDR)],
    [Paragraph("Bacterial contamination / pyrogenic reactions", S_TABLE_CELL),
     Paragraph("Gram-negative bacteria in water system; biofilm formation; endotoxin passage across membranes", S_TABLE_CELL),
     Paragraph("Monthly cultures of source water, product water, dialysate; LAL assay for endotoxin; ultrapure dialysate for HDF; prompt culture & antibiotics", S_TABLE_CELL)],
    [Paragraph("Chloramine toxicity", S_TABLE_CELL),
     Paragraph("Inadequate dechlorination; causes haemolytic anaemia and methaemoglobinaemia", S_TABLE_CELL),
     Paragraph("Activated carbon filtration; regular monitoring of water treatment system", S_TABLE_CELL)],
    [Paragraph("Aluminium toxicity", S_TABLE_CELL),
     Paragraph("Aluminium-contaminated water or phosphate binders; causes dialysis encephalopathy, adynamic bone disease, anaemia", S_TABLE_CELL),
     Paragraph("Reverse osmosis + deionisation; monitor water Al levels; avoid Al-based binders; deferoxamine chelation for toxicity", S_TABLE_CELL)],
    [Paragraph("Fluoride toxicity", S_TABLE_CELL),
     Paragraph("High fluoride in source water; inadequate removal", S_TABLE_CELL),
     Paragraph("Reverse osmosis; periodic water analysis; AAMI standards compliance", S_TABLE_CELL)],
]
water = Table(water_data, colWidths=[W*0.22, W*0.38, W*0.40], repeatRows=1)
water.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), NAVY),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_BLU]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 5), ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(water)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 8 – ANTICOAGULATION & BLEEDING + ANEMIA
# ══════════════════════════════════════════════════════════
story.append(section_header("8. ANTICOAGULATION, BLEEDING & CLOTTING", NAVY))
story.append(sp(5))
anticoag_data = [
    [Paragraph("SCENARIO", S_TABLE_HDR), Paragraph("APPROACH", S_TABLE_HDR)],
    [Paragraph("Standard anticoagulation", S_TABLE_CELL),
     Paragraph("Unfractionated heparin (UFH): bolus 1,000–5,000 U pre-HD + infusion 500–1,500 U/h. Target aPTT 1.5–2× baseline. Stop 30–60 min before session ends.", S_TABLE_CELL)],
    [Paragraph("HIT (Heparin-Induced Thrombocytopenia)", S_TABLE_CELL),
     Paragraph("Substitute argatroban or bivalirudin; avoid all heparin products including heparin flushes", S_TABLE_CELL)],
    [Paragraph("Active bleeding / high risk", S_TABLE_CELL),
     Paragraph("Heparin-free HD: frequent saline flushes (100 mL q15–30 min); citrate anticoagulation; or regional heparin with protamine reversal", S_TABLE_CELL)],
    [Paragraph("Dialyzer clotting", S_TABLE_CELL),
     Paragraph("Fibrin deposition in hollow fibres → ↓ effective membrane area → ↓ Kt/V. Risk with low blood flow, high haematocrit, inadequate heparin.", S_TABLE_CELL)],
    [Paragraph("Uremic bleeding", S_TABLE_CELL),
     Paragraph("Platelet dysfunction (↓ GP Ib, ↓ ADP/TXA₂). Treat with: dialysis (reversal), dDAVP 0.3 mcg/kg IV, conjugated oestrogens, cryoprecipitate. Correct anaemia (target Hgb ≥10 g/dL).", S_TABLE_CELL)],
]
ac = Table(anticoag_data, colWidths=[W*0.30, W*0.70], repeatRows=1)
ac.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_YEL]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 5), ("BOTTOMPADDING", (0,0), (-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(ac)
story.append(sp(10))

story.append(section_header("9. ANAEMIA MANAGEMENT IN HD", NAVY))
story.append(sp(5))
anaemia_data = [
    [Paragraph("PARAMETER", S_TABLE_HDR), Paragraph("TARGET / APPROACH", S_TABLE_HDR)],
    [Paragraph("Target Haemoglobin", S_TABLE_CELL), Paragraph("10–11.5 g/dL (KDIGO); avoid >13 g/dL (↑ thrombosis risk)", S_TABLE_CELL)],
    [Paragraph("ESA therapy", S_TABLE_CELL), Paragraph("Erythropoietin alfa, darbepoetin alfa; IV preferred in HD patients; dose adjust for Hgb response", S_TABLE_CELL)],
    [Paragraph("Iron targets", S_TABLE_CELL), Paragraph("Serum ferritin >200 µg/L; TSAT >20%; IV iron preferred (ferric carboxymaltose, ferric gluconate, iron sucrose)", S_TABLE_CELL)],
    [Paragraph("ESA hypo-response", S_TABLE_CELL), Paragraph("Evaluate: iron deficiency, infection/inflammation (↑CRP), hyperparathyroidism, haemolysis, malnutrition, inadequate dialysis", S_TABLE_CELL)],
    [Paragraph("L-Carnitine", S_TABLE_CELL), Paragraph("May reduce ESA requirements in carnitine-deficient patients; evidence inconsistent (2025 review)", S_TABLE_CELL)],
]
an = Table(anaemia_data, colWidths=[W*0.30, W*0.70], repeatRows=1)
an.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), NAVY),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_PUR]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(an)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════
# PAGE 9 – TROUBLESHOOTING INADEQUATE DIALYSIS + SUMMARY
# ══════════════════════════════════════════════════════════
story.append(section_header("10. TROUBLESHOOTING INADEQUATE DIALYSIS DOSE", NAVY))
story.append(sp(5))
story.append(body("When URR <65% or delivered Kt/V <1.2, investigate systematically:"))
story.append(sp(4))

trouble_data = [
    [Paragraph("STEP", S_TABLE_HDR), Paragraph("CHECK", S_TABLE_HDR), Paragraph("ACTION", S_TABLE_HDR)],
    [Paragraph("1", S_TABLE_CELL), Paragraph("Session representativeness", S_TABLE_CELL),
     Paragraph("Was the session shortened, interrupted, or otherwise unusual? Repeat measurement before changing prescription.", S_TABLE_CELL)],
    [Paragraph("2", S_TABLE_CELL), Paragraph("Vascular access recirculation", S_TABLE_CELL),
     Paragraph("Most common cause. Measure recirculation by urea or ultrasound dilution method. Treat underlying stenosis.", S_TABLE_CELL)],
    [Paragraph("3", S_TABLE_CELL), Paragraph("Blood sampling errors", S_TABLE_CELL),
     Paragraph("Post-HD blood drawn too late → falsely low Kt/V. Pre-HD sample from access line → falsely low pre-HD BUN. Follow sampling protocol strictly.", S_TABLE_CELL)],
    [Paragraph("4", S_TABLE_CELL), Paragraph("Treatment time", S_TABLE_CELL),
     Paragraph("Increase session duration – most effective single intervention. Document actual 'time on dialysis' vs. prescribed time.", S_TABLE_CELL)],
    [Paragraph("5", S_TABLE_CELL), Paragraph("Dialyzer efficiency", S_TABLE_CELL),
     Paragraph("Switch to higher KoA dialyzer. Check for membrane clotting (reduced effective surface area).", S_TABLE_CELL)],
    [Paragraph("6", S_TABLE_CELL), Paragraph("Blood / dialysate flow rates", S_TABLE_CELL),
     Paragraph("Increase Qb (if access allows) and/or Qd. Verify countercurrent flow configuration.", S_TABLE_CELL)],
    [Paragraph("7", S_TABLE_CELL), Paragraph("Vascular access type", S_TABLE_CELL),
     Paragraph("Transition from catheter to permanent AV access if feasible – higher flows, lower recirculation.", S_TABLE_CELL)],
    [Paragraph("8", S_TABLE_CELL), Paragraph("Body size / V estimation", S_TABLE_CELL),
     Paragraph("If lean body mass has increased, V is larger → same Kt gives lower Kt/V. Adjust prescription to ideal V, not current V.", S_TABLE_CELL)],
]
tr = Table(trouble_data, colWidths=[W*0.07, W*0.27, W*0.66], repeatRows=1)
tr.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), TEAL),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, GREY_BG]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
    ("ALIGN", (0,0), (0,-1), "CENTER"),
]))
story.append(tr)
story.append(sp(10))

# Summary
story.append(section_header("QUICK REFERENCE SUMMARY", ORANGE))
story.append(sp(5))

summary_data = [
    [Paragraph("COMPLICATION", S_TABLE_HDR), Paragraph("KEY CAUSE", S_TABLE_HDR), Paragraph("FIRST-LINE RESPONSE", S_TABLE_HDR)],
    [Paragraph("Intradialytic Hypotension", S_TABLE_CELL), Paragraph("Excessive UF rate", S_TABLE_CELL), Paragraph("↓ UF + supine + 100–250 mL saline", S_TABLE_CELL)],
    [Paragraph("Muscle Cramps", S_TABLE_CELL), Paragraph("Hypovolaemia + hypoosmolality", S_TABLE_CELL), Paragraph("D50W 25–50 mL IV; reassess dry weight", S_TABLE_CELL)],
    [Paragraph("Disequilibrium Syndrome", S_TABLE_CELL), Paragraph("Rapid urea removal → cerebral oedema", S_TABLE_CELL), Paragraph("Slow/stop HD; mannitol 1 g/kg IV", S_TABLE_CELL)],
    [Paragraph("Access Thrombosis", S_TABLE_CELL), Paragraph("Stenosis / hypotension", S_TABLE_CELL), Paragraph("Thrombolysis / thrombectomy + fistulogram", S_TABLE_CELL)],
    [Paragraph("Catheter Bacteraemia", S_TABLE_CELL), Paragraph("Biofilm / hub contamination", S_TABLE_CELL), Paragraph("Blood cultures + empiric antibiotics + catheter removal", S_TABLE_CELL)],
    [Paragraph("Inadequate Kt/V", S_TABLE_CELL), Paragraph("Access recirculation / short time", S_TABLE_CELL), Paragraph("Check recirculation; ↑ session time; ↑ flows", S_TABLE_CELL)],
    [Paragraph("Hyperphosphataemia", S_TABLE_CELL), Paragraph("Diet + intracellular shift", S_TABLE_CELL), Paragraph("Binders + longer sessions", S_TABLE_CELL)],
    [Paragraph("Arrhythmia", S_TABLE_CELL), Paragraph("Rapid K/Ca shifts", S_TABLE_CELL), Paragraph("Individualise dialysate K/Ca; cardiac monitoring", S_TABLE_CELL)],
    [Paragraph("Uremic Bleeding", S_TABLE_CELL), Paragraph("Platelet dysfunction", S_TABLE_CELL), Paragraph("Adequate dialysis + dDAVP + correct anaemia", S_TABLE_CELL)],
]
sm = Table(summary_data, colWidths=[W*0.27, W*0.33, W*0.40], repeatRows=1)
sm.setStyle(TableStyle([
    ("BACKGROUND", (0,0), (-1,0), ORANGE),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [white, LIGHT_YEL]),
    ("GRID", (0,0), (-1,-1), 0.3, HexColor("#BDC3C7")),
    ("TOPPADDING", (0,0), (-1,-1), 4), ("BOTTOMPADDING", (0,0), (-1,-1), 4),
    ("LEFTPADDING", (0,0), (-1,-1), 6), ("RIGHTPADDING", (0,0), (-1,-1), 6),
    ("VALIGN", (0,0), (-1,-1), "TOP"),
]))
story.append(sm)
story.append(sp(8))

story.append(colored_box([
    [Paragraph(
        "<b>Sources:</b> Brenner &amp; Rector's The Kidney (10th Ed.) · Harrison's Principles of Internal Medicine 22E (2025) · "
        "Comprehensive Clinical Nephrology 7th Ed. · Goldman-Cecil Medicine · Washington Manual of Medical Therapeutics · "
        "Kesik G &amp; Altinok Ersoy N, Ther Apher Dial 2023 (PMID 36691882) · Kljajić M et al., J Clin Med 2025 (PMID 40725745)",
        S_NOTE)]
], GREY_BG, HexColor("#BDC3C7")))

# ─────────────────────────────────────────────────────────────────────────────
# BUILD
# ─────────────────────────────────────────────────────────────────────────────
doc.build(story,
          onFirstPage=on_first_page,
          onLaterPages=on_page)
print("PDF generated:", OUTPUT)
Running Command

cd /home/daytona/workspace/hd-complications-pdf && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/hd-complications-pdf/HD_Complications_Quick_Refer…

Your PDF is ready for download:

HD Complications Quick Reference

PDF Document · PDF


What's inside (9 pages, A4, colour-coded):
SectionContent
CoverTitle page with source attribution
Overview + Key TargetsAdequacy parameters table (Kt/V, URR, flow rates, UF limits)
1. Intradialytic HypotensionCauses / Prevention / Acute management (3-column)
2. Muscle CrampsPathogenesis table + acute osmolality management + prevention strategies (with quinine FDA warning highlighted in red)
3. Cardiovascular ComplicationsMyocardial stunning, arrhythmias, hypertension, long interdialytic interval mortality
4. Dialysis Disequilibrium SyndromeMechanism, symptoms (mild/severe), prevention, management
5. Vascular Access ComplicationsThrombosis, stenosis, recirculation, catheter bacteraemia, steal syndrome
6. Metabolic & Electrolyte ComplicationsK⁺, PO₄, HCO₃, Na, Ca, Mg
7. Water/Dialysate ComplicationsBacterial contamination, chloramine, aluminium, fluoride toxicity
8. Anticoagulation & AnaemiaHeparin protocols, HIT, uremic bleeding, ESA/iron targets
9. Troubleshooting + SummaryStep-by-step inadequate dose approach + one-page quick-reference summary table
This is a shared conversation. Sign in to Orris to start your own chat.