Please teach me this topic based on this pdf. Focus on pathophysiological reasoning behind every concept so that I apply it in real life ward

Reading File
Running Command

cd /tmp/workspace/attachments/60d78e58-f784-44f0-9a8d-53957b4f842d && python3 -c " import pdfplumber with pdfplumber.open('RhD alloimmunization in pregnancy- Management.pdf') as pdf: print(f'Total pages: {len(pdf.pages)}') for i, page in enumerate(pdf.pages): text = page.extract_text() print(f'--- PAGE {i+1} ---') print(text) print() "

Searching Images

Rh alloimmunization hemolytic disease fetus newborn pathophysiology

Summary : This flowchart outlines the diagnostic and management pathway for pregnancies affected by maternal alloimmunization to Anti-K, Anti-D, or Anti-c antibodies, focusing on the risk assessment and monitoring for hemolytic disease of the fetus and newborn (HDFN).

flowchart:
# Nodes :
  • Anti-K detected (rectangle)
  • Titrate antibody (rectangle)
  • Non-invasive pre-natal diagnosis (rectangle)
  • Test father (rectangle)
  • K Positive Heterozygous expression (rectangle)
  • K Positive Homozygous expression (rectangle)
  • K Negative (rectangle)
  • cffDNA (rectangle)
  • K Positive (rectangle)
  • K Negative (rectangle)
  • Anti-D detected (rectangle)
  • Quantify Antibody level 4–15 IU/mL mod risk HDFN >15 IU/mL severe risk HDFN (rectangle)
  • Non-invasive pre-natal diagnosis (rectangle)
  • Test father (rectangle)
  • D Positive Heterozygous expression (rectangle)
  • D Positive Homozygous expression (rectangle)
  • D Negative (rectangle)
  • cffDNA (rectangle)
  • D Positive (rectangle)
  • D Negative (rectangle)
  • Fetus at risk of HDFN (rectangle)
  • Referral to local Fetal Medicine Specialist for MCA – PSV Doppler (rectangle)
  • MCA-PSV > 1.5 MoM (rectangle)
  • Refer to tertiary fetal medicine service with expertise in invasive fetal therapy (IFT) for IUT(s) (rectangle)
  • MCA-PSV < 1.5 MoM (rectangle)
  • Serial MCA-PSV studies (rectangle)
  • Deliver at not later than 37–38 weeks’ gestation, unless other clinical concerns indicate earlier delivery (rectangle)
  • Cord blood, Hb, Bili, DAT (rectangle)
  • Anti-c detected (rectangle)
  • Quantify Antibody level 7.5–20 IU/mL mod risk HDFN >20 IU/mL severe risk HDFN (rectangle)
  • Non-invasive pre-natal diagnosis (rectangle)
  • Test father (rectangle)
  • c Positive Heterozygous expression (rectangle)
  • c Positive Homozygous expression (rectangle)
  • c-Negative (rectangle)
  • cffDNA (rectangle)
  • c Positive (rectangle)
  • c Negative (rectangle)
  • Legend (rectangle) – defines abbreviations used in the chart

# Connectors :
  • Arrows indicate the flow from antibody detection to titration, then to non-invasive diagnosis or paternal testing.
  • Branches split based on paternal genotype (heterozygous, homozygous, negative).
  • If the father is negative, the pathway ends (no risk).
  • If the father is positive (heterozygous or homozygous), cffDNA is used to determine fetal antigen status.
  • If the fetus is antigen negative, the pathway ends (no risk).
  • If the fetus is antigen positive, the fetus is at risk of HDFN and referred for further monitoring.
  • For at-risk fetuses, referral to fetal medicine for MCA-PSV Doppler is indicated.
  • If MCA-PSV > 1.5 MoM, refer for invasive fetal therapy (IUT).
  • If MCA-PSV < 1.5 MoM, continue serial monitoring.
  • Delivery is recommended at 37–38 weeks unless earlier delivery is clinically indicated.

# Layout :
  • The chart is organized into three parallel vertical pathways for Anti-K, Anti-D, and Anti-c, each with similar diagnostic and management steps.
  • Each pathway splits into non-invasive diagnosis and paternal testing, then converges on fetal risk assessment and management.
  • The bottom section merges all pathways for final fetal monitoring and delivery planning.
  • A legend box is present at the bottom left, defining abbreviations.

# Analysis :
  • The flowchart provides a clear, stepwise approach for managing pregnancies at risk of HDFN due to Anti-K, Anti-D, or Anti-c alloimmunization.
  • The process emphasizes non-invasive testing first, with paternal testing to stratify risk.
  • Only fetuses at risk (antigen positive) are referred for intensive monitoring and possible intervention.
  • The use of MCA-PSV Doppler is central for ongoing fetal surveillance, with invasive therapy reserved for those with evidence of fetal anemia.
  • The chart standardizes care and minimizes unnecessary interventions for low-risk pregnancies.

Summary : This flowchart outlines the diagnostic and management pathway for pregnancies affected by maternal alloimmunization to Anti-K, Anti-D, or Anti-c antibodies, focusing on the risk assessment and monitoring for hemolytic disease of the fetus and newborn (HDFN). flowchart: # Nodes : • Anti-K detected (rectangle) • Titrate antibody (rectangle) • Non-invasive pre-natal diagnosis (rectangle) • Test father (rectangle) • K Positive Heterozygous expression (rectangle) • K Positive Homozygous expression (rectangle) • K Negative (rectangle) • cffDNA (rectangle) • K Positive (rectangle) • K Negative (rectangle) • Anti-D detected (rectangle) • Quantify Antibody level 4–15 IU/mL mod risk HDFN >15 IU/mL severe risk HDFN (rectangle) • Non-invasive pre-natal diagnosis (rectangle) • Test father (rectangle) • D Positive Heterozygous expression (rectangle) • D Positive Homozygous expression (rectangle) • D Negative (rectangle) • cffDNA (rectangle) • D Positive (rectangle) • D Negative (rectangle) • Fetus at risk of HDFN (rectangle) • Referral to local Fetal Medicine Specialist for MCA – PSV Doppler (rectangle) • MCA-PSV > 1.5 MoM (rectangle) • Refer to tertiary fetal medicine service with expertise in invasive fetal therapy (IFT) for IUT(s) (rectangle) • MCA-PSV < 1.5 MoM (rectangle) • Serial MCA-PSV studies (rectangle) • Deliver at not later than 37–38 weeks’ gestation, unless other clinical concerns indicate earlier delivery (rectangle) • Cord blood, Hb, Bili, DAT (rectangle) • Anti-c detected (rectangle) • Quantify Antibody level 7.5–20 IU/mL mod risk HDFN >20 IU/mL severe risk HDFN (rectangle) • Non-invasive pre-natal diagnosis (rectangle) • Test father (rectangle) • c Positive Heterozygous expression (rectangle) • c Positive Homozygous expression (rectangle) • c-Negative (rectangle) • cffDNA (rectangle) • c Positive (rectangle) • c Negative (rectangle) • Legend (rectangle) – defines abbreviations used in the chart # Connectors : • Arrows indicate the flow from antibody detection to titration, then to non-invasive diagnosis or paternal testing. • Branches split based on paternal genotype (heterozygous, homozygous, negative). • If the father is negative, the pathway ends (no risk). • If the father is positive (heterozygous or homozygous), cffDNA is used to determine fetal antigen status. • If the fetus is antigen negative, the pathway ends (no risk). • If the fetus is antigen positive, the fetus is at risk of HDFN and referred for further monitoring. • For at-risk fetuses, referral to fetal medicine for MCA-PSV Doppler is indicated. • If MCA-PSV > 1.5 MoM, refer for invasive fetal therapy (IUT). • If MCA-PSV < 1.5 MoM, continue serial monitoring. • Delivery is recommended at 37–38 weeks unless earlier delivery is clinically indicated. # Layout : • The chart is organized into three parallel vertical pathways for Anti-K, Anti-D, and Anti-c, each with similar diagnostic and management steps. • Each pathway splits into non-invasive diagnosis and paternal testing, then converges on fetal risk assessment and management. • The bottom section merges all pathways for final fetal monitoring and delivery planning. • A legend box is present at the bottom left, defining abbreviations. # Analysis : • The flowchart provides a clear, stepwise approach for managing pregnancies at risk of HDFN due to Anti-K, Anti-D, or Anti-c alloimmunization. • The process emphasizes non-invasive testing first, with paternal testing to stratify risk. • Only fetuses at risk (antigen positive) are referred for intensive monitoring and possible intervention. • The use of MCA-PSV Doppler is central for ongoing fetal surveillance, with invasive therapy reserved for those with evidence of fetal anemia. • The chart standardizes care and minimizes unnecessary interventions for low-risk pregnancies.

Summary : This flowchart outlines the diagnostic and management pathway for pregnancies affected by maternal alloimmunization to K, D, or c antigens, focusing on the risk assessment and monitoring for hemolytic disease of the fetus and newborn (HDFN). It details the steps for antibody titration, non-invasive prenatal diagnosis, paternal testing, and subsequent fetal monitoring and intervention.

flowchart:
# Main Pathways :
• Three parallel pathways for Anti-K, Anti-D, and Anti-c detected in maternal blood.
• Each pathway begins with antibody detection and titration/quantification.
• Decision points for non-invasive prenatal diagnosis and paternal antigen testing.
• Use of cell-free fetal DNA (cffDNA) for fetal antigen status determination.
• Referral to fetal medicine specialist if fetus is at risk of HDFN.

# Nodes :
• Anti-K detected (rectangle)
• Titrate antibody (rectangle)
• Non-invasive pre-natal diagnosis (rectangle)
• Test father (rectangle)
• K Positive Heterozygous expression (rectangle)
• K Positive Homozygous expression (rectangle)
• K Negative (rectangle)
• cffDNA (rectangle)
• K Positive (rectangle)
• K Negative (rectangle)
• Anti-D detected (rectangle)
• Quantify Antibody level 4–15 IU/mL mod risk HDFN, >15 IU/mL severe risk HDFN (rectangle)
• D Positive Heterozygous expression (rectangle)
• D Positive Homozygous expression (rectangle)
• D Negative (rectangle)
• D Positive (rectangle)
• D Negative (rectangle)
• Fetus at risk of HDFN (rectangle)
• Referral to local Fetal Medicine Specialist for MCA – PSV Doppler (rectangle)
• Anti-c detected (rectangle)
• Quantify Antibody level 7.5–20 IU/mL mod risk HDFN, >20 IU/mL severe risk HDFN (rectangle)
• c Positive Heterozygous expression (rectangle)
• c Positive Homozygous expression (rectangle)
• c-Negative (rectangle)
• c Positive (rectangle)
• c Negative (rectangle)

# Connectors :
• Arrows indicate progression from antibody detection to diagnosis, paternal testing, and fetal risk assessment.
• Branching based on test results (e.g., positive/negative, heterozygous/homozygous).
• Merging of pathways at "Fetus at risk of HDFN" leading to specialist referral.

# Management Pathway (Bottom Section) :
• MCA-PSV > 1.5 MoM: Refer to tertiary fetal medicine service for intrauterine transfusion (IUT) if indicated.
• IUT generally performed up to 34 weeks’ gestation, with timing and delivery advice from the specialist service.
• MCA-PSV < 1.5 MoM: Serial MCA-PSV studies.
• Delivery recommended at 37–38 weeks’ gestation unless earlier delivery is clinically indicated.
• At delivery: Cord blood, hemoglobin, bilirubin, direct antiglobulin test (DAT).

# Legend :
• Ab – Antibody
• Bili – bilirubin
• DAT – direct antiglobulin test
• CffDNA – cell free fetal DNA
• Hb – hemoglobin
• HDFN – hemolytic disease of the fetus and newborn
• IUT – intrauterine transfusion
• MCS Doppler – middle cerebral artery Doppler
• Pos/Neg – positive/negative
• US – ultrasound

# Layout :
• Three main vertical columns for Anti-K, Anti-D, and Anti-c.
• Each column splits into non-invasive prenatal diagnosis and paternal testing.
• All columns converge at fetal risk assessment and management.
• Bottom section provides management steps based on Doppler results.

Analysis :
• The flowchart provides a clear, stepwise approach for managing pregnancies at risk of HDFN due to maternal alloimmunization.
• It emphasizes early risk stratification using both non-invasive and paternal testing, with escalation to specialist care if the fetus is at risk.
• The use of MCA-PSV Doppler as a key decision point for intervention is highlighted.
• The chart ensures that all possible antigen combinations and test results are accounted for, minimizing missed diagnoses and optimizing fetal outcomes.

Summary : This flowchart outlines the diagnostic and management pathway for pregnancies affected by maternal alloimmunization to K, D, or c antigens, focusing on the risk assessment and monitoring for hemolytic disease of the fetus and newborn (HDFN). It details the steps for antibody titration, non-invasive prenatal diagnosis, paternal testing, and subsequent fetal monitoring and intervention. flowchart: # Main Pathways : • Three parallel pathways for Anti-K, Anti-D, and Anti-c detected in maternal blood. • Each pathway begins with antibody detection and titration/quantification. • Decision points for non-invasive prenatal diagnosis and paternal antigen testing. • Use of cell-free fetal DNA (cffDNA) for fetal antigen status determination. • Referral to fetal medicine specialist if fetus is at risk of HDFN. # Nodes : • Anti-K detected (rectangle) • Titrate antibody (rectangle) • Non-invasive pre-natal diagnosis (rectangle) • Test father (rectangle) • K Positive Heterozygous expression (rectangle) • K Positive Homozygous expression (rectangle) • K Negative (rectangle) • cffDNA (rectangle) • K Positive (rectangle) • K Negative (rectangle) • Anti-D detected (rectangle) • Quantify Antibody level 4–15 IU/mL mod risk HDFN, >15 IU/mL severe risk HDFN (rectangle) • D Positive Heterozygous expression (rectangle) • D Positive Homozygous expression (rectangle) • D Negative (rectangle) • D Positive (rectangle) • D Negative (rectangle) • Fetus at risk of HDFN (rectangle) • Referral to local Fetal Medicine Specialist for MCA – PSV Doppler (rectangle) • Anti-c detected (rectangle) • Quantify Antibody level 7.5–20 IU/mL mod risk HDFN, >20 IU/mL severe risk HDFN (rectangle) • c Positive Heterozygous expression (rectangle) • c Positive Homozygous expression (rectangle) • c-Negative (rectangle) • c Positive (rectangle) • c Negative (rectangle) # Connectors : • Arrows indicate progression from antibody detection to diagnosis, paternal testing, and fetal risk assessment. • Branching based on test results (e.g., positive/negative, heterozygous/homozygous). • Merging of pathways at "Fetus at risk of HDFN" leading to specialist referral. # Management Pathway (Bottom Section) : • MCA-PSV > 1.5 MoM: Refer to tertiary fetal medicine service for intrauterine transfusion (IUT) if indicated. • IUT generally performed up to 34 weeks’ gestation, with timing and delivery advice from the specialist service. • MCA-PSV < 1.5 MoM: Serial MCA-PSV studies. • Delivery recommended at 37–38 weeks’ gestation unless earlier delivery is clinically indicated. • At delivery: Cord blood, hemoglobin, bilirubin, direct antiglobulin test (DAT). # Legend : • Ab – Antibody • Bili – bilirubin • DAT – direct antiglobulin test • CffDNA – cell free fetal DNA • Hb – hemoglobin • HDFN – hemolytic disease of the fetus and newborn • IUT – intrauterine transfusion • MCS Doppler – middle cerebral artery Doppler • Pos/Neg – positive/negative • US – ultrasound # Layout : • Three main vertical columns for Anti-K, Anti-D, and Anti-c. • Each column splits into non-invasive prenatal diagnosis and paternal testing. • All columns converge at fetal risk assessment and management. • Bottom section provides management steps based on Doppler results. Analysis : • The flowchart provides a clear, stepwise approach for managing pregnancies at risk of HDFN due to maternal alloimmunization. • It emphasizes early risk stratification using both non-invasive and paternal testing, with escalation to specialist care if the fetus is at risk. • The use of MCA-PSV Doppler as a key decision point for intervention is highlighted. • The chart ensures that all possible antigen combinations and test results are accounted for, minimizing missed diagnoses and optimizing fetal outcomes.

A pathophysiology diagram illustrating the complex cytokine signaling network in pregnant women (PW) with chronic venous disease (CVD) and its impact on the newborn (NB). The diagram features a central map of cytokines (e.g., IL-6, TNF-̑, IL-10, IL-17A, IFN-̳) and immune cells (Th1, Th2, Th17, Treg, Eosinophils) interconnected by stimulatory and inhibitory pathways. Color-coded arrows indicate dysregulation: yellow arrows signify increased levels in CVD (this study), red arrows represent previous CVD findings (HIF-1̑, MMPs), and green arrows denote decreased levels (IL-4, IL-10, IL-13, IFN-̳). Key educational highlights include the Th1/Th2 imbalance, impaired Th17/Treg ratio, and the TNF-̑/IL-10 imbalance leading to a hyperinflammatory state. Clinical annotations link these changes to preeclampsia, maternal-fetal microbial invasivity, and fetal eosinophilia. A silhouette of a pregnant woman with visible venous disease in the legs and a fetus in utero provides anatomical context, emphasizing the maternal-fetal interface's role in future health outcomes.

A pathophysiology diagram illustrating the complex cytokine signaling network in pregnant women (PW) with chronic venous disease (CVD) and its impact on the newborn (NB). The diagram features a central map of cytokines (e.g., IL-6, TNF-̑, IL-10, IL-17A, IFN-̳) and immune cells (Th1, Th2, Th17, Treg, Eosinophils) interconnected by stimulatory and inhibitory pathways. Color-coded arrows indicate dysregulation: yellow arrows signify increased levels in CVD (this study), red arrows represent previous CVD findings (HIF-1̑, MMPs), and green arrows denote decreased levels (IL-4, IL-10, IL-13, IFN-̳). Key educational highlights include the Th1/Th2 imbalance, impaired Th17/Treg ratio, and the TNF-̑/IL-10 imbalance leading to a hyperinflammatory state. Clinical annotations link these changes to preeclampsia, maternal-fetal microbial invasivity, and fetal eosinophilia. A silhouette of a pregnant woman with visible venous disease in the legs and a fetus in utero provides anatomical context, emphasizing the maternal-fetal interface's role in future health outcomes.

Searching Images

middle cerebral artery peak systolic velocity Doppler fetal anemia

This composite diagnostic image demonstrates key ultrasonographic procedures used in the management of fetal anemia, frequently associated with intrauterine parvovirus B19 infection. Panel A illustrates the measurement of the Middle Cerebral Artery (MCA) Peak Systolic Velocity (PSV) using color and spectral Doppler. The top portion shows a transverse view of the fetal head with color flow mapping identifying the Circle of Willis, while the bottom portion displays a high-resistance pulsatile spectral waveform. Quantitative data indicates a peak systolic velocity (PSV) of 55.84 cm/s and a heart rate of 140 bpm, metrics critical for non-invasive screening of fetal anemia. Panel B presents a grayscale B-mode ultrasound image of an intrauterine transfusion (IUT). A hyperechoic needle is visualized being guided into the umbilical vein at the placental insertion site. The image shows the relationship between the placental mass, the anechoic amniotic fluid, and the needle trajectory. These panels represent standard maternal-fetal medicine protocols for diagnosing and treating severe fetal alloimmunization or viral-induced hematopoietic suppression.

This composite diagnostic image demonstrates key ultrasonographic procedures used in the management of fetal anemia, frequently associated with intrauterine parvovirus B19 infection. Panel A illustrates the measurement of the Middle Cerebral Artery (MCA) Peak Systolic Velocity (PSV) using color and spectral Doppler. The top portion shows a transverse view of the fetal head with color flow mapping identifying the Circle of Willis, while the bottom portion displays a high-resistance pulsatile spectral waveform. Quantitative data indicates a peak systolic velocity (PSV) of 55.84 cm/s and a heart rate of 140 bpm, metrics critical for non-invasive screening of fetal anemia. Panel B presents a grayscale B-mode ultrasound image of an intrauterine transfusion (IUT). A hyperechoic needle is visualized being guided into the umbilical vein at the placental insertion site. The image shows the relationship between the placental mass, the anechoic amniotic fluid, and the needle trajectory. These panels represent standard maternal-fetal medicine protocols for diagnosing and treating severe fetal alloimmunization or viral-induced hematopoietic suppression.

This diagnostic image is a Doppler ultrasound of the fetal middle cerebral artery (MCA), commonly used in maternal-fetal medicine to assess for fetal anemia or hypoxia. The display is divided into a B-mode ultrasound view showing the fetal head and circle of Willis in the upper portion, and a spectral Doppler waveform in the lower portion. The spectral waveform exhibits high-resistance flow characterized by sharp systolic peaks and absent-to-reversed end-diastolic flow (AREDF), where the signal descends to or below the zero-velocity baseline. Numerical measurements on the right indicate a peak systolic velocity (PSV) of 92.34 cm/s and an end-diastolic velocity (ED) of -7.56 cm/s, resulting in a high pulsatility index (PI) of 2.71 and a resistance index (RI) of 1.08. These findings are clinically significant as an elevated MCA-PSV is a primary screening marker for severe fetal anemia, while the reversal of diastolic flow indicates significant hemodynamic compromise or high downstream resistance.

This diagnostic image is a Doppler ultrasound of the fetal middle cerebral artery (MCA), commonly used in maternal-fetal medicine to assess for fetal anemia or hypoxia. The display is divided into a B-mode ultrasound view showing the fetal head and circle of Willis in the upper portion, and a spectral Doppler waveform in the lower portion. The spectral waveform exhibits high-resistance flow characterized by sharp systolic peaks and absent-to-reversed end-diastolic flow (AREDF), where the signal descends to or below the zero-velocity baseline. Numerical measurements on the right indicate a peak systolic velocity (PSV) of 92.34 cm/s and an end-diastolic velocity (ED) of -7.56 cm/s, resulting in a high pulsatility index (PI) of 2.71 and a resistance index (RI) of 1.08. These findings are clinically significant as an elevated MCA-PSV is a primary screening marker for severe fetal anemia, while the reversal of diastolic flow indicates significant hemodynamic compromise or high downstream resistance.

This diagnostic image displays a fetal Doppler ultrasound assessment of the middle cerebral artery (MCA), featuring color flow mapping and a spectral Doppler waveform. The upper panel shows an axial view of the fetal head at the level of the Circle of Willis, with color Doppler highlighting arterial flow in red and venous or divergent flow in blue. The lower panel displays a pulsed-wave (PW) spectral waveform demonstrating high-velocity, pulsatile arterial flow. Quantitative measurements indicate a Peak Systolic Velocity (PSV) of 42.8 cm/s, which corresponds to 1.6 multiples of the median (MoM), a clinical indicator of potential fetal anemia. Additional hemodynamic parameters include an End Diastolic Velocity (EDV) of 0.000 cm/s, resulting in a Resistivity Index (RI) of 1.00 and a Pulsatility Index (PI) of 2.67. Technical parameters listed include a 2.3MHz probe frequency (M3), 2.0mm sample volume (SV), and a scan depth of 3.4cm. This visual is critical for monitoring high-risk pregnancies, specifically for diagnosing and managing fetal alloimmune or hemorrhagic anemia.

This diagnostic image displays a fetal Doppler ultrasound assessment of the middle cerebral artery (MCA), featuring color flow mapping and a spectral Doppler waveform. The upper panel shows an axial view of the fetal head at the level of the Circle of Willis, with color Doppler highlighting arterial flow in red and venous or divergent flow in blue. The lower panel displays a pulsed-wave (PW) spectral waveform demonstrating high-velocity, pulsatile arterial flow. Quantitative measurements indicate a Peak Systolic Velocity (PSV) of 42.8 cm/s, which corresponds to 1.6 multiples of the median (MoM), a clinical indicator of potential fetal anemia. Additional hemodynamic parameters include an End Diastolic Velocity (EDV) of 0.000 cm/s, resulting in a Resistivity Index (RI) of 1.00 and a Pulsatility Index (PI) of 2.67. Technical parameters listed include a 2.3MHz probe frequency (M3), 2.0mm sample volume (SV), and a scan depth of 3.4cm. This visual is critical for monitoring high-risk pregnancies, specifically for diagnosing and managing fetal alloimmune or hemorrhagic anemia.

Reading File
I have all the content I need. Let me now deliver a comprehensive, pathophysiology-grounded teaching session.

RhD Alloimmunization in Pregnancy: Management

A Pathophysiology-First Teaching Session


The Core Concept: Why This Happens (The "Why" Behind Everything)

Before touching management, you must deeply understand what is happening at a cellular level - otherwise all the cutoffs and algorithms are just memorization.
The Central Problem:
An RhD-negative mother was previously exposed to RhD-positive red blood cells (from a prior pregnancy, miscarriage, or transfusion). Her immune system mounted an IgG antibody response against the RhD antigen. IgG - and critically, NOT IgM - can cross the placenta via the neonatal Fc receptor (FcRn). Once maternal anti-D IgG crosses into fetal circulation, it coats any RhD-positive fetal RBCs. The fetal reticuloendothelial system (spleen, liver) recognizes these antibody-coated cells and destroys them extravascularly. The result is fetal hemolytic anemia.
Why does it get WORSE with each pregnancy?
This is pure immunology. The first exposure (sensitizing event) generates a primary immune response - slow, predominantly IgM, low titer. At delivery, more fetal RBCs enter maternal circulation (fetomaternal hemorrhage), triggering a secondary (anamnestic) immune response - faster, IgG-dominant, higher titer, longer-lasting memory. In the next RhD-positive pregnancy:
  • The anamnestic response fires earlier and harder
  • IgG levels are higher from the start
  • Fetal anemia develops earlier in gestation and is more severe
This is why the document states: "A patient whose prior pregnancy was complicated by need for fetal transfusion can expect severe fetal anemia to develop in subsequent pregnancies, typically at an earlier gestational age - in one series, a median of 3 weeks earlier."

PART 1: FIRST ALLOIMMUNIZED PREGNANCY

Step 1 - Does the Fetus Actually Carry the Target Antigen?

Pathophysiological reasoning: If the fetus is RhD-negative, its RBCs simply have no RhD antigen on their surface. Maternal anti-D antibodies have nothing to bind to - they cross the placenta harmlessly and the fetus is completely safe. Monitoring for HDFN is therefore utterly pointless and harmful (unnecessary anxiety, interventions, costs).
How we determine fetal RhD status:
(a) Paternal genotyping first - because the father contributes one of the two alleles:
  • If the father is RhD-negative (genotype: RHD deletion / RHD deletion): 100% of his sperm carry no RHD - therefore fetus is RhD-negative. No further fetal testing needed.
  • If the father is homozygous RhD-positive (RHD/RHD): 100% of his sperm carry RHD - fetus must be RhD-positive. Skip to monitoring.
  • If the father is heterozygous (RHD/rh): 50% chance the fetus inherited RHD - need fetal testing.
Ward pearl: Always document the paternity discussion! Non-paternity is more common than clinicians assume (studies suggest 2-10% of cases). If you fail to test because "father is RhD-negative," but he isn't the biological father, you've missed a fetus at risk.
(b) Cell-free fetal DNA (cfDNA) from maternal plasma - after 10 weeks
Here's the beautiful biology: during pregnancy, fetal trophoblastic cells shed fragments of fetal DNA into maternal circulation. We can extract this cfDNA from a maternal blood sample and PCR-amplify RHD exons (4, 5, 7, 10). Detection of these exons = fetus carries RHD = fetus is RhD-positive.
  • Sensitivity: 99.3%, Specificity: 98.4% (first and second trimester)
  • One US assay using next-generation sequencing reports 100% sensitivity and 99.3% specificity
Why test MULTIPLE exons? D variants (partial D, weak D) exist where some exons may be present but others absent. Testing single exons would give false negatives (call the fetus RhD-negative when it actually has a partial D antigen that can still be attacked). Testing exons 4, 5, 7, and 10 together avoids this trap.
Why not amniocentesis? Amniocentesis can also determine fetal RHD by PCR on amniocytes, but there's a critical problem: penetrating the placenta (transplacental amniocentesis) or injuring chorionic villi causes fetomaternal hemorrhage - more fetal RBCs enter maternal circulation, which worsens alloimmunization (boosts maternal anti-D titer). CVS is strongly discouraged for the same reason.

Step 2 - Monitoring Maternal Anti-D Titer

In a first alloimmunized pregnancy with an RhD-positive fetus:
  • Monitor indirect Coombs (indirect antiglobulin test, IAT) monthly until 24 weeks, then every 2 weeks
  • If titer is rising: weekly until critical titer is reached
  • Once critical titer is reached: STOP measuring titers - switch to Doppler
Why the indirect Coombs test?
The indirect Coombs test detects free antibodies in maternal serum. Reagent RhD-positive RBCs are added to maternal serum; anti-D antibodies (if present) coat these cells. Then anti-human globulin (Coombs reagent) is added - it cross-links the antibody-coated cells causing agglutination. The titer is the last dilution at which agglutination still occurs.
The Critical Titer:
Most laboratories use a critical titer of 1:16 (in Europe: 15 IU/mL).
  • Below 1:16: Fetus may develop mild-moderate anemia, but NOT severe anemia. Monitor titers only.
  • At or above 1:16: Fetus is at risk for severe anemia. Titers are no longer sufficient - you need Doppler.
Why does the titer predict severity?
Higher antibody titer = more anti-D IgG crossing the placenta = more fetal RBC destruction = more severe anemia. But titer is a crude tool (sensitivity 100%, specificity only 50-60%). This is why:
  • Titers can rise even when the fetus is RhD-negative (unclear mechanism)
  • Two mothers with the same titer can have very different fetal outcomes based on antibody avidity, FcRn receptor efficiency, and fetal bone marrow compensation
Ward insight: Never use the titer to reassure yourself once it's critical. The titer tells you when to switch to Doppler - not how severe the anemia actually is. Doppler does that job.
The Gel Microcolumn Assay (GMA) - important test awareness: GMA is replacing tube tests in many blood banks because it's more reproducible and automatable. However, GMA often reads 1-2 dilutions HIGHER than tube tests. Since the critical titer of 1:16 was validated using tube tests, you cannot directly apply that threshold to GMA results. Continue using tube titers for clinical management until GMA thresholds are validated.

Step 3 - MCA-PSV Doppler: The Physiological Masterpiece

This is the most important non-invasive tool in HDFN management, and its logic is pure pathophysiology.
The mechanism of MCA-PSV elevation in fetal anemia:
When fetal hemoglobin falls:
  1. Oxygen-carrying capacity drops → tissues become hypoxic
  2. The fetus responds by increasing cardiac output (tachycardia + increased stroke volume)
  3. Simultaneously, anemia reduces blood viscosity (fewer RBCs = thinner blood = less resistance to flow)
  4. Both mechanisms drive blood to flow FASTER through the cerebral arteries
The Middle Cerebral Artery is specifically chosen because:
  • It is easily insonated at the Circle of Willis
  • The fetal brain is a flow-priority organ (cerebral autoregulation preserves flow even in anemia)
  • The PSV (peak velocity at systole) accurately reflects the hemodynamic state
The threshold: MCA-PSV > 1.5 MoM (multiples of the median)
Why use MoM instead of absolute cm/s? Because MCA-PSV physiologically increases across gestation (bigger heart, bigger vessels). 1.5 MoM corrects for gestational age - it represents 1.5 times the expected velocity for that specific gestational age.
Performance (meta-analysis of 9 studies, 675 fetuses):
  • Sensitivity for severe anemia (Hb < 0.55 MoM): 75-100%
  • Specificity: ~87-91%
  • Negative predictive value: 98% (MCA-PSV ≤1.5 MoM is very reassuring)
Critical ward trap: MCA-PSV accuracy falls progressively after multiple transfusions. After intrauterine transfusions (IUT), fetal blood contains mostly adult donor Hb with higher oxygen affinity - the physiological compensation changes. Always be more cautious interpreting MCA-PSV in previously transfused fetuses; the 1.5 MoM threshold becomes less reliable.
Doppler Technique matters clinically:
  • Always measure when fetus is in a quiet behavioral state - active fetal movement or breathing movements cause falsely elevated readings
  • Use the conversion calculator (perinatology.com or fetalmedicinebarcelona.org) to convert cm/s to MoM - you MUST correct for gestational age or the number is meaningless
Historical alternative - Delta OD₄₅₀ (Liley chart): Bilirubin in amniotic fluid (from fetal hemolysis) was spectrophotometrically measured and plotted on the Liley chart to estimate anemia severity. This required amniocentesis (invasive, risk of worsening sensitization) and is now largely obsolete. Doppler is superior and non-invasive.
Here are real-world Doppler images illustrating elevated MCA-PSV:
MCA-PSV Doppler showing PSV 1.6 MoM - fetal anemia screening
MCA-PSV of 42.8 cm/s = 1.6 MoM - this fetus should undergo fetal blood sampling
MCA Doppler showing elevated PSV with absent diastolic flow - severe anemia/compromise
Spectral Doppler with PSV 92.34 cm/s and reversed end-diastolic flow - severe hemodynamic compromise

Step 4 - What Happens After MCA-PSV?

If MCA-PSV ≤ 1.5 MoM:
  • No moderate/severe anemia - continue Doppler every 1-2 weeks
  • At 32 weeks: add weekly antenatal testing (NST/BPP)
  • Deliver at 37+0 to 38+6 weeks. Why not at 39-40 weeks? Because MCA-PSV sensitivity for detecting severe anemia decreases after 35 weeks. Beyond 35 weeks, the risks of missed anemia exceed the small risks of early-term delivery.
If MCA-PSV > 1.5 MoM:
You have compelling physiological evidence of fetal anemia - but you must CONFIRM with fetal blood sampling (cordocentesis) before transfusing. Why? Because MCA-PSV has a false-positive rate of ~12%. Intrauterine transfusion (IUT) carries 1-2% risk of fetal loss - do not expose a non-anemic fetus to that risk.
Fetal blood sampling (cordocentesis):
  • Sample from umbilical vein at cord insertion or from fetal hepatic vein
  • Check fetal hemoglobin
  • Threshold for transfusion: Hb < 2 SD below mean for gestational age, OR hematocrit < 30%
Why transfuse at moderate anemia, not wait for severe? Because by the time fetal Hb is severely depressed (deficit >7 g/dL below mean), the fetus is approaching hydrops. The cascade is:
  • Severe anemia → severe hypoxia → heart failure → increased capillary hydrostatic pressure → edema
  • Hydrops fetalis = ascites + pleural effusion + skin edema + pericardial effusion
  • Mortality in hydrops is very high even with IUT
Transfusing early (at moderate anemia, before hydrops) is mechanistically superior because:
  1. The fetal myocardium is not yet failing
  2. Transfusion is technically safer in a non-hydropic fetus
  3. The fetus can compensate better
Intrauterine Transfusion (IUT) - gestational age limits:
  • Before 18 weeks: Technically very challenging (umbilical vein is tiny - less than 2 mm diameter). Access is nearly impossible without high fetal loss risk.
  • 18-35 weeks: This is the therapeutic window for IUT.
  • ≥35 weeks: IUT risk exceeds risk of preterm delivery. If MCA-PSV >1.5 MoM at ≥35 weeks, DELIVER and transfuse the neonate ex utero.
Intrapartum note: A severely anemic fetus on CTG may show a sinusoidal pattern - a smooth, undulating waveform without beat-to-beat variability. The mechanism is CNS compromise from severe anemia/hypoxia affecting the cardiac autonomic centers. This is a Category III tracing demanding urgent delivery.

PART 2: SUBSEQUENT PREGNANCIES

Why subsequent pregnancies are managed differently

Three key differences drive the escalated approach:
  1. Anamnestic immune response - maternal antibody levels are already high at the start of the pregnancy, not climbing slowly
  2. Earlier onset - fetal anemia develops weeks earlier than in the prior pregnancy
  3. Greater severity - each subsequent IUT provides additional fetal RBC antigen exposure at delivery, further boosting maternal antibody memory
Baseline titer of ≥1:1028 = extremely high titer = fetal anemia before 18 weeks is likely. Before 18 weeks, IUT is technically not feasible. This is the scenario where you need a bridge strategy.

Management Stratified by Prior Pregnancy Severity

Prior pregnancy outcomeStart MCA-PSV monitoring
Severe HDFN <24 weeks OR titer ≥1:102815 weeks gestation
Severe HDFN ≥24 weeks, preterm birth from anemia, neonatal exchange transfusion16 weeks gestation
Prior neonatal phototherapy only (mild HDFN)18 weeks gestation
Why start at 15 weeks for the most severe cases? Because prior severe HDFN <24 weeks means the next fetus could develop life-threatening anemia before 18 weeks - you need to detect it as early as technically feasible so you can use the strategies below.

Bridge Therapies for Very Severe Alloimmunization (Titer ≥1:1028 + Prior Loss Before 24 Weeks)

Why is this group unique? They face a window of vulnerability: fetal anemia can develop as early as 15 weeks, but safe IUT is only possible from 18 weeks. You need to DELAY the onset and REDUCE the severity of fetal anemia until 18+ weeks becomes accessible.
1. IVIG (Intravenous Immunoglobulin G)
Mechanism: IVIG (pooled normal human IgG) saturates the neonatal Fc receptor (FcRn) on the placental syncytiotrophoblast. FcRn normally transports maternal IgG across the placenta. When you flood the system with large doses of normal IgG, the FcRn becomes saturated and cannot transport as much of the pathological anti-D IgG → less anti-D reaches the fetus → less hemolysis.
A secondary mechanism: High-dose IVIG may trigger accelerated catabolism of IgG (including anti-D) by overwhelming reticuloendothelial recycling pathways, lowering maternal anti-D titer.
Evidence: An individual patient data meta-analysis of 97 pregnancies showed IVIG started at 10-12 weeks delayed the first fetal transfusion by a mean of 3.19 weeks vs. prior pregnancy, and reduced fetal demise (incidence ratio 0.23 vs. untreated controls).
Started at: 10-12 weeks gestation
2. Therapeutic Plasma Exchange (TPE)
Mechanism: Directly removes circulating maternal anti-D IgG by replacing maternal plasma with albumin or donor plasma. Reduces the pool of antibodies available for placental transport.
Limitation: The maternal immune system rapidly regenerates IgG between sessions (rebound effect). Therefore, TPE is most effective when combined with IVIG (IVIG blunts the rebound by saturating FcRn and promoting catabolism).
3. Nipocalimab (Investigational - Phase 2 data)
Mechanism: A monoclonal antibody that specifically blocks FcRn - the ONLY known receptor for transplacental IgG transport. By occupying FcRn, nipocalimab:
  1. Prevents placental transport of ALL maternal IgG (including anti-D) to the fetus
  2. Accelerates maternal IgG catabolism (FcRn normally recycles IgG, preventing its degradation)
This is highly targeted - it addresses the actual transport mechanism rather than just diluting antibodies.
Phase 2 results: In 13 high-risk patients (11 anti-D, 2 anti-K), 54% achieved a live birth ≥32 weeks without IUT. Maternal and cord blood showed treatment-related decreases in anti-D titer and total IgG. This remains investigational but represents a potentially paradigm-shifting targeted approach.

PART 3: THE CLINICAL ALGORITHM AT A GLANCE

Here is a flowchart showing the full management pathway across all three alloimmunizing antibodies:
Management flowchart for RhD, anti-K, anti-c alloimmunization in pregnancy

PART 4: SPECIAL WARD PEARLS - "WHY DOES THE BOOK SAY THAT?"

Why NOT give anti-D immunoglobulin to an already-sensitized patient?

Anti-D Ig (Rh immune globulin) works ONLY as primary prophylaxis - it prevents the initial sensitization by coating fetal RhD-positive cells in maternal circulation and clearing them before the immune system mounts a primary response. Once the primary immune response has occurred (patient is already making anti-D), administering more anti-D Ig does nothing. The memory B cells are already primed. The titer will not drop. Do not give it.

Why the same laboratory for serial titers?

Antibody titers are notoriously variable between labs (different techniques, cell preparations, reagents). A rise from 1:8 to 1:16 could be a real doubling OR it could be assay variation. By keeping all samples in the same lab and running the previous sample alongside each new sample (internal control), you ensure a 4-fold rise is genuinely significant. A 1-dilution change (e.g., 2 → 4) may be noise; 2+ dilutions are likely real.

Why delayed cord clamping is NOT contraindicated in HDFN?

The instinct is: "don't let more maternal antibody-laden blood back into the baby." But cord blood flows from placenta TO baby (umbilical vein carries oxygenated blood to fetus), and delayed clamping actually adds volume. In a randomized trial of 70 D-positive fetuses of RhD-alloimmunized mothers, delayed clamping improved neonatal RBC volume at 2 hours without significantly increasing exchange transfusion needs or duration of phototherapy. The net RBC benefit outweighs concerns.

Why avoid cross-matching difficulties in labor?

When a mother carries MULTIPLE alloantibodies (e.g., anti-D plus anti-C - which occur together because they're on the same chromosome - Rh haplotypes like DCe are inherited together), finding compatible blood becomes harder. Multiple antibodies are associated with a more aggressive immune response and higher risk of severe fetal anemia. Pre-order cross-matched RBCs in labor so they're immediately available if:
  • The mother hemorrhages (maternal crossmatch)
  • The neonate needs emergent neonatal transfusion (blood can be rapidly processed for neonatal use)

Why is anti-C particularly dangerous alongside anti-D?

The C antigen is on the RhC/c protein, encoded by RHCE gene - co-inherited with RHCE. Mothers with anti-D who also develop anti-C (from exposure on fetal RBCs that carried both D and C antigens) have experienced TWO sensitizing episodes. The combined antibody response is synergistically more aggressive. The document notes anti-C presence is associated with a higher risk for fetal transfusion requirement.

SUMMARY TABLE: Decision Points and Their Pathophysiological Basis

Clinical DecisionPhysiological Reason
Determine fetal RHD type firstNo target antigen = no attack. Spares unnecessary monitoring
Critical titer = 1:16At this level, sufficient IgG crosses placenta to cause severe RBC destruction
Switch to Doppler at critical titerTiter no longer adds info; MCA-PSV is more sensitive and specific for severity
MCA-PSV 1.5 MoM = thresholdAt this velocity, fetal Hb is predicted to be dangerously low based on physiological compensation
Confirm anemia by cordocentesis before IUT12% false positive MCA-PSV rate - don't transfuse without proof
Transfuse at moderate, not severe anemiaPrevents hydrops cascade; better fetal tolerance of procedure
IUT only 18-35 weeks<18 wks: technical impossibility; >35 wks: delivery is safer
Deliver at 37-38 weeksMCA-PSV less reliable after 35 weeks; early-term delivery safer than missed severe anemia
IVIG/TPE for titer ≥1:1028Bridge to feasible IUT by reducing placental IgG transport via FcRn saturation
Earlier and more frequent Doppler in subsequent pregnanciesAnamnestic response causes earlier onset of fetal anemia

Quick Ward Summary: The Three Questions

Whenever you see an alloimmunized patient on the ward, ask three questions:
  1. Is the fetus at risk? (Is fetus RhD-positive? Check father, then cfDNA)
  2. How much antibody is there? (Maternal titer - is it below or above critical?)
  3. Is the fetus actually anemic? (MCA-PSV → if >1.5 MoM → cordocentesis → IUT if confirmed)
Everything in this topic flows from those three pathophysiological questions.

Create a summary PDF with decision flowcharts and hemoglobin reference tables

Reading File
Running Command

mkdir -p /tmp/workspace/rh-alloimmunization && ls /tmp/workspace/rh-alloimmunization

Writing File

~/rh-alloimmunization/build_pdf.py

"""
RhD Alloimmunization in Pregnancy - Management Summary PDF
Using reportlab with custom flowcharts drawn via canvas
"""

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

# ── Colour Palette ──────────────────────────────────────────────────────────
DARK_BLUE   = HexColor("#1a3a5c")
MID_BLUE    = HexColor("#2e6da4")
LIGHT_BLUE  = HexColor("#dce8f5")
TEAL        = HexColor("#1a7a7a")
LIGHT_TEAL  = HexColor("#d4f0f0")
RED         = HexColor("#c0392b")
LIGHT_RED   = HexColor("#fde8e6")
ORANGE      = HexColor("#e67e22")
LIGHT_ORANGE= HexColor("#fef0e0")
GREEN       = HexColor("#1e7a4a")
LIGHT_GREEN = HexColor("#d5f0e0")
PURPLE      = HexColor("#6c3483")
LIGHT_PURPLE= HexColor("#f0e8f8")
GREY        = HexColor("#5d6d7e")
LIGHT_GREY  = HexColor("#f2f3f4")
YELLOW      = HexColor("#f4c430")
LIGHT_YELLOW= HexColor("#fffde7")
DARK_GREY   = HexColor("#2c3e50")

W, H = A4  # 595 x 842 pts


# ── Styles ───────────────────────────────────────────────────────────────────
def make_styles():
    base = getSampleStyleSheet()
    styles = {}

    styles["cover_title"] = ParagraphStyle(
        "cover_title", fontSize=26, leading=32,
        textColor=white, fontName="Helvetica-Bold",
        alignment=TA_CENTER, spaceAfter=6
    )
    styles["cover_sub"] = ParagraphStyle(
        "cover_sub", fontSize=13, leading=17,
        textColor=HexColor("#cfe2f3"), fontName="Helvetica",
        alignment=TA_CENTER, spaceAfter=4
    )
    styles["cover_note"] = ParagraphStyle(
        "cover_note", fontSize=9, leading=12,
        textColor=HexColor("#a0bcd4"), fontName="Helvetica-Oblique",
        alignment=TA_CENTER
    )
    styles["h1"] = ParagraphStyle(
        "h1", fontSize=16, leading=20,
        textColor=DARK_BLUE, fontName="Helvetica-Bold",
        spaceBefore=10, spaceAfter=6,
        borderPad=4, borderColor=DARK_BLUE,
        underlineWidth=1
    )
    styles["h2"] = ParagraphStyle(
        "h2", fontSize=12, leading=15,
        textColor=MID_BLUE, fontName="Helvetica-Bold",
        spaceBefore=8, spaceAfter=4
    )
    styles["h3"] = ParagraphStyle(
        "h3", fontSize=10, leading=13,
        textColor=DARK_GREY, fontName="Helvetica-Bold",
        spaceBefore=5, spaceAfter=3
    )
    styles["body"] = ParagraphStyle(
        "body", fontSize=9, leading=13,
        textColor=DARK_GREY, fontName="Helvetica",
        spaceAfter=4, alignment=TA_JUSTIFY
    )
    styles["body_bold"] = ParagraphStyle(
        "body_bold", fontSize=9, leading=13,
        textColor=DARK_GREY, fontName="Helvetica-Bold",
        spaceAfter=4
    )
    styles["bullet"] = ParagraphStyle(
        "bullet", fontSize=9, leading=13,
        textColor=DARK_GREY, fontName="Helvetica",
        spaceAfter=2, leftIndent=12,
        bulletIndent=0
    )
    styles["table_header"] = ParagraphStyle(
        "table_header", fontSize=9, leading=11,
        textColor=white, fontName="Helvetica-Bold",
        alignment=TA_CENTER
    )
    styles["table_cell"] = ParagraphStyle(
        "table_cell", fontSize=8.5, leading=11,
        textColor=DARK_GREY, fontName="Helvetica",
        alignment=TA_CENTER
    )
    styles["table_cell_l"] = ParagraphStyle(
        "table_cell_l", fontSize=8.5, leading=11,
        textColor=DARK_GREY, fontName="Helvetica",
        alignment=TA_LEFT
    )
    styles["warning"] = ParagraphStyle(
        "warning", fontSize=8.5, leading=12,
        textColor=RED, fontName="Helvetica-Bold",
        spaceAfter=3
    )
    styles["caption"] = ParagraphStyle(
        "caption", fontSize=7.5, leading=10,
        textColor=GREY, fontName="Helvetica-Oblique",
        alignment=TA_CENTER, spaceAfter=6
    )
    styles["pathophys"] = ParagraphStyle(
        "pathophys", fontSize=8.5, leading=12,
        textColor=HexColor("#2c4f7c"), fontName="Helvetica",
        spaceAfter=3, leftIndent=8, borderPad=4,
        backColor=LIGHT_BLUE, alignment=TA_LEFT
    )
    return styles


# ── Custom Flowables ─────────────────────────────────────────────────────────

class CoverPage(Flowable):
    def __init__(self, width, height):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def draw(self):
        c = self.canv
        # Background gradient effect (solid dark blue)
        c.setFillColor(DARK_BLUE)
        c.rect(0, 0, self.width, self.height, fill=1, stroke=0)

        # Decorative top arc
        c.setFillColor(MID_BLUE)
        c.ellipse(-60, self.height - 120, self.width + 60, self.height + 200, fill=1, stroke=0)

        # Bottom decorative strip
        c.setFillColor(TEAL)
        c.rect(0, 0, self.width, 50, fill=1, stroke=0)

        # Side accent bar
        c.setFillColor(HexColor("#2e86de"))
        c.rect(0, 50, 8, self.height - 50, fill=1, stroke=0)

        # Title text block
        c.setFillColor(white)
        c.setFont("Helvetica-Bold", 26)
        c.drawCentredString(self.width / 2, self.height - 180, "RhD Alloimmunization")
        c.setFont("Helvetica-Bold", 22)
        c.drawCentredString(self.width / 2, self.height - 210, "in Pregnancy")

        c.setFillColor(HexColor("#aed6f1"))
        c.setFont("Helvetica", 13)
        c.drawCentredString(self.width / 2, self.height - 240, "Management — Clinical Summary")

        # Divider
        c.setStrokeColor(HexColor("#aed6f1"))
        c.setLineWidth(1.5)
        c.line(80, self.height - 258, self.width - 80, self.height - 258)

        # Subtitle badges
        badges = [
            ("Flowcharts", MID_BLUE, 130),
            ("Hb Reference Tables", TEAL, 300),
            ("Ward Pearls", PURPLE, 460),
        ]
        for label, col, x in badges:
            c.setFillColor(col)
            c.roundRect(x - 50, self.height - 300, 100, 22, 6, fill=1, stroke=0)
            c.setFillColor(white)
            c.setFont("Helvetica-Bold", 8)
            c.drawCentredString(x, self.height - 292, label)

        # Body description
        c.setFillColor(HexColor("#d6eaf8"))
        c.setFont("Helvetica", 9)
        lines = [
            "Pathophysiology-based quick reference for ward rounds and exam preparation.",
            "Based on UpToDate® — RhD Alloimmunization in Pregnancy: Management",
            "(Literature review current through Jul 2026 | Last updated Mar 25, 2025)"
        ]
        y = self.height - 340
        for line in lines:
            c.drawCentredString(self.width / 2, y, line)
            y -= 14

        # Sections overview box
        c.setFillColor(HexColor("#1a3a5c"))
        c.setStrokeColor(HexColor("#2e6da4"))
        c.setLineWidth(1)
        c.roundRect(60, 160, self.width - 120, 160, 8, fill=1, stroke=1)

        c.setFillColor(HexColor("#aed6f1"))
        c.setFont("Helvetica-Bold", 10)
        c.drawCentredString(self.width / 2, 300, "Contents")
        c.setLineWidth(0.5)
        c.setStrokeColor(HexColor("#2e6da4"))
        c.line(180, 296, self.width - 180, 296)

        sections = [
            "1. Pathophysiology Overview",
            "2. First Alloimmunized Pregnancy — Decision Flowchart",
            "3. MCA-PSV Doppler — Principles & Thresholds",
            "4. Fetal Hemoglobin Reference Table",
            "5. Subsequent Pregnancies — Management Flowchart",
            "6. Bridge Therapies (IVIG / TPE / Nipocalimab)",
            "7. Ward Pearls Quick-Reference",
        ]
        c.setFillColor(white)
        c.setFont("Helvetica", 8.5)
        y_sec = 282
        for sec in sections:
            c.drawString(110, y_sec, sec)
            y_sec -= 16

        # Footer
        c.setFillColor(HexColor("#a0bcd4"))
        c.setFont("Helvetica-Oblique", 7)
        c.drawCentredString(self.width / 2, 20, "For educational use only — not for direct patient care decisions")


class SectionHeader(Flowable):
    """Full-width coloured section header band."""
    def __init__(self, title, subtitle="", color=DARK_BLUE, width=None):
        Flowable.__init__(self)
        self.title = title
        self.subtitle = subtitle
        self.color = color
        self.width = width or (W - 2 * 2 * cm)
        self.height = 38 if subtitle else 28

    def draw(self):
        c = self.canv
        c.setFillColor(self.color)
        c.roundRect(0, 0, self.width, self.height, 5, fill=1, stroke=0)
        c.setFillColor(white)
        c.setFont("Helvetica-Bold", 12)
        y = self.height - 16 if self.subtitle else self.height / 2 - 4
        c.drawString(12, y, self.title)
        if self.subtitle:
            c.setFont("Helvetica", 8)
            c.setFillColor(HexColor("#c8e6f5"))
            c.drawString(12, 8, self.subtitle)


class Flowchart1(Flowable):
    """First Alloimmunized Pregnancy decision flowchart."""
    def __init__(self, width, height=540):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def _box(self, c, x, y, w, h, text, fill_color, text_color=white,
             font="Helvetica-Bold", fsize=7.5, radius=5, stroke_color=None):
        c.setFillColor(fill_color)
        if stroke_color:
            c.setStrokeColor(stroke_color)
            c.setLineWidth(1.2)
        else:
            c.setStrokeColor(fill_color)
            c.setLineWidth(0.5)
        c.roundRect(x, y, w, h, radius, fill=1, stroke=1)
        c.setFillColor(text_color)
        c.setFont(font, fsize)
        lines = text.split("\n")
        total_h = len(lines) * (fsize + 1.5)
        start_y = y + h / 2 + total_h / 2 - fsize
        for line in lines:
            c.drawCentredString(x + w / 2, start_y, line)
            start_y -= (fsize + 1.5)

    def _diamond(self, c, cx, cy, half_w, half_h, text, fill_color, fsize=7):
        c.setFillColor(fill_color)
        c.setStrokeColor(HexColor("#888888"))
        c.setLineWidth(0.8)
        path = c.beginPath()
        path.moveTo(cx, cy + half_h)
        path.lineTo(cx + half_w, cy)
        path.lineTo(cx, cy - half_h)
        path.lineTo(cx - half_w, cy)
        path.close()
        c.drawPath(path, fill=1, stroke=1)
        c.setFillColor(white)
        c.setFont("Helvetica-Bold", fsize)
        lines = text.split("\n")
        total = len(lines) * (fsize + 1.5)
        sy = cy + total / 2 - fsize
        for ln in lines:
            c.drawCentredString(cx, sy, ln)
            sy -= (fsize + 1.5)

    def _arrow(self, c, x1, y1, x2, y2, label="", color=GREY):
        c.setStrokeColor(color)
        c.setLineWidth(1.2)
        c.line(x1, y1, x2, y2)
        # Arrowhead
        dx = x2 - x1
        dy = y2 - y1
        length = math.sqrt(dx*dx + dy*dy)
        if length == 0:
            return
        ux, uy = dx / length, dy / length
        px, py = -uy, ux
        size = 5
        c.setFillColor(color)
        path = c.beginPath()
        path.moveTo(x2, y2)
        path.lineTo(x2 - ux * size + px * size / 2,
                    y2 - uy * size + py * size / 2)
        path.lineTo(x2 - ux * size - px * size / 2,
                    y2 - uy * size - py * size / 2)
        path.close()
        c.drawPath(path, fill=1, stroke=0)
        if label:
            mx, my = (x1 + x2) / 2, (y1 + y2) / 2
            c.setFillColor(GREY)
            c.setFont("Helvetica-Bold", 6.5)
            c.drawCentredString(mx + 8, my + 4, label)

    def draw(self):
        c = self.canv
        W = self.width
        H = self.height
        bw = 130  # box width
        bh = 28   # box height
        cx = W / 2

        # ── Step 1: Start ──
        y = H - 30
        self._box(c, cx - bw/2, y, bw, bh, "RhD-negative mother\nalloimmunized (anti-D +)",
                  DARK_BLUE, fsize=7)

        # ── Arrow down ──
        self._arrow(c, cx, y, cx, y - 18, color=GREY)

        # ── Step 2: Determine fetal RhD ──
        y -= 18 + bh
        self._box(c, cx - bw/2, y, bw, bh, "Determine Fetal RhD Type\n(paternal + cfDNA >10 wks)",
                  MID_BLUE, fsize=7)

        # ── Arrow down ──
        self._arrow(c, cx, y, cx, y - 18, color=GREY)

        # ── Diamond: Fetus RhD? ──
        dy = y - 18 - 24
        self._diamond(c, cx, dy, 80, 24, "Fetus\nRhD positive?", ORANGE, fsize=7.5)

        # ── NO branch: left ──
        self._arrow(c, cx - 80, dy, cx - 80 - 10, dy, color=GREEN)
        self._box(c, cx - 80 - 10 - 100, dy - bh/2, 100, bh,
                  "RhD-NEGATIVE fetus\nNo HDFN monitoring\nneeded",
                  GREEN, fsize=6.5)
        c.setFillColor(GREEN)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx - 80 - 6, dy + 4, "NO")

        # ── YES branch: down ──
        c.setFillColor(RED)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 4, dy - 30, "YES")
        self._arrow(c, cx, dy - 24, cx, dy - 24 - 14, color=RED)

        # ── Step 3: Serial titers ──
        y = dy - 24 - 14 - bh
        self._box(c, cx - bw/2, y, bw, bh,
                  "Serial Indirect Coombs Titer\nMonthly to 24 wks, then q2wks",
                  MID_BLUE, fsize=7)

        # ── Arrow down ──
        self._arrow(c, cx, y, cx, y - 14, color=GREY)

        # ── Diamond: Critical titer? ──
        dy2 = y - 14 - 24
        self._diamond(c, cx, dy2, 80, 24, "Titer ≥ 1:16\n(Critical)?", ORANGE, fsize=7.5)

        # ── NO branch: right (continue monitoring) ──
        self._arrow(c, cx + 80, dy2, cx + 80 + 10, dy2, color=GREEN)
        self._box(c, cx + 80 + 10, dy2 - bh/2, 100, bh,
                  "Continue serial\ntiters (stable)",
                  GREEN, fsize=6.5)
        c.setFillColor(GREEN)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 82, dy2 + 4, "NO")

        # ── YES branch: down ──
        c.setFillColor(RED)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 4, dy2 - 30, "YES")
        self._arrow(c, cx, dy2 - 24, cx, dy2 - 24 - 14, color=RED)

        # ── Step 4: MCA-PSV ──
        y = dy2 - 24 - 14 - bh
        self._box(c, cx - bw/2, y, bw, bh,
                  "STOP titers — Begin MCA-PSV\nDoppler q1-2 wks (≥16 wks)",
                  TEAL, fsize=7)

        # ── Arrow down ──
        self._arrow(c, cx, y, cx, y - 14, color=GREY)

        # ── Diamond: MCA-PSV? ──
        dy3 = y - 14 - 24
        self._diamond(c, cx, dy3, 85, 24, "MCA-PSV\n> 1.5 MoM?", ORANGE, fsize=7.5)

        # ── NO branch (≤1.5): left ──
        self._arrow(c, cx - 85, dy3, cx - 85 - 10, dy3, color=GREEN)
        no_x = cx - 85 - 10 - 110
        self._box(c, no_x, dy3 - bh - 4, 110, bh + 10,
                  "No severe anemia\nAntenatal tests q1wk\nfrom 32 wks\nDeliver 37-38+6 wks",
                  GREEN, fsize=6.5)
        c.setFillColor(GREEN)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx - 85 - 6, dy3 + 4, "≤1.5")

        # ── YES branch (>1.5): right ──
        c.setFillColor(RED)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 87, dy3 + 4, ">1.5")
        self._arrow(c, cx + 85, dy3, cx + 85 + 10, dy3, color=RED)
        yes_x = cx + 85 + 10
        self._box(c, yes_x, dy3 - bh - 4, 110, bh + 10,
                  "Cordocentesis\nCheck fetal Hb\n(have blood ready\nfor IUT)",
                  RED, fsize=6.5)

        # ── From YES box: diamond ──
        y_cord = dy3 - bh - 4 - 18
        self._arrow(c, yes_x + 55, dy3 - bh - 4, yes_x + 55, y_cord - 24, color=RED)
        self._diamond(c, yes_x + 55, y_cord - 24,
                      70, 22, "Hb < 2SD below\nmean for GA?", RED, fsize=6.5)

        # IUT box
        self._arrow(c, yes_x + 55, y_cord - 46, yes_x + 55, y_cord - 46 - 16, color=RED)
        self._box(c, yes_x + 55 - 55, y_cord - 46 - 16 - bh, 110, bh,
                  "IUT (18-35 wks)\nDeliver ~3 wks\nafter last IUT",
                  RED, fsize=6.5)
        c.setFillColor(RED)
        c.setFont("Helvetica-Bold", 6.5)
        c.drawString(yes_x + 57, y_cord - 48, "YES")

        # Recheck box
        yes_x2 = yes_x + 55 + 70 + 5
        if yes_x2 + 85 < W:
            self._arrow(c, yes_x + 55 + 70, y_cord - 24,
                        yes_x2, y_cord - 24, color=GREEN)
            self._box(c, yes_x2, y_cord - 24 - bh/2, 85, bh,
                      "Hb acceptable:\nRecheck in 1-2 wks",
                      GREEN, fsize=6.5)
            c.setFillColor(GREEN)
            c.setFont("Helvetica-Bold", 6.5)
            c.drawString(yes_x + 55 + 72, y_cord - 22, "NO")

        # ── Gestational limit note ──
        c.setFillColor(LIGHT_ORANGE)
        c.setStrokeColor(ORANGE)
        c.setLineWidth(0.8)
        c.roundRect(cx - bw/2, 8, bw + 20, 30, 4, fill=1, stroke=1)
        c.setFillColor(ORANGE)
        c.setFont("Helvetica-Bold", 7)
        c.drawCentredString(cx + 10, 30, "If MCA-PSV >1.5 MoM at ≥35 wks:")
        c.setFont("Helvetica", 6.5)
        c.drawCentredString(cx + 10, 18, "DELIVER directly — do not perform IUT")


class Flowchart2(Flowable):
    """Subsequent Pregnancies management flowchart."""
    def __init__(self, width, height=440):
        Flowable.__init__(self)
        self.width = width
        self.height = height

    def _box(self, c, x, y, w, h, text, fill_color, text_color=white,
             font="Helvetica-Bold", fsize=7.5, radius=5):
        c.setFillColor(fill_color)
        c.setStrokeColor(fill_color)
        c.setLineWidth(0.5)
        c.roundRect(x, y, w, h, radius, fill=1, stroke=1)
        c.setFillColor(text_color)
        c.setFont(font, fsize)
        lines = text.split("\n")
        total_h = len(lines) * (fsize + 1.5)
        start_y = y + h / 2 + total_h / 2 - fsize
        for line in lines:
            c.drawCentredString(x + w / 2, start_y, line)
            start_y -= (fsize + 1.5)

    def _diamond(self, c, cx, cy, half_w, half_h, text, fill_color, fsize=7):
        c.setFillColor(fill_color)
        c.setStrokeColor(HexColor("#888888"))
        c.setLineWidth(0.8)
        path = c.beginPath()
        path.moveTo(cx, cy + half_h)
        path.lineTo(cx + half_w, cy)
        path.lineTo(cx, cy - half_h)
        path.lineTo(cx - half_w, cy)
        path.close()
        c.drawPath(path, fill=1, stroke=1)
        c.setFillColor(white)
        c.setFont("Helvetica-Bold", fsize)
        lines = text.split("\n")
        total = len(lines) * (fsize + 1.5)
        sy = cy + total / 2 - fsize
        for ln in lines:
            c.drawCentredString(cx, sy, ln)
            sy -= (fsize + 1.5)

    def _arrow(self, c, x1, y1, x2, y2, label="", color=GREY):
        c.setStrokeColor(color)
        c.setLineWidth(1.2)
        c.line(x1, y1, x2, y2)
        dx, dy = x2 - x1, y2 - y1
        length = math.sqrt(dx*dx + dy*dy)
        if length == 0:
            return
        ux, uy = dx / length, dy / length
        px, py = -uy, ux
        size = 5
        c.setFillColor(color)
        path = c.beginPath()
        path.moveTo(x2, y2)
        path.lineTo(x2 - ux*size + px*size/2, y2 - uy*size + py*size/2)
        path.lineTo(x2 - ux*size - px*size/2, y2 - uy*size - py*size/2)
        path.close()
        c.drawPath(path, fill=1, stroke=0)
        if label:
            c.setFillColor(GREY)
            c.setFont("Helvetica-Bold", 6.5)
            c.drawCentredString((x1+x2)/2 + 8, (y1+y2)/2 + 4, label)

    def draw(self):
        c = self.canv
        W = self.width
        H = self.height
        cx = W / 2
        bw = 130
        bh = 26

        # Start
        y = H - 25
        self._box(c, cx - bw/2, y, bw, bh,
                  "SUBSEQUENT alloimmunized pregnancy\n(anamnestic immune response expected)",
                  DARK_BLUE, fsize=7)
        self._arrow(c, cx, y, cx, y - 14, color=GREY)

        # cfDNA
        y -= 14 + bh
        self._box(c, cx - bw/2, y, bw, bh,
                  "cfDNA for fetal RHD type\n(early in gestation)",
                  MID_BLUE, fsize=7)
        self._arrow(c, cx, y, cx, y - 14, color=GREY)

        # Titer check
        y -= 14 + bh
        self._box(c, cx - bw/2, y, bw, bh,
                  "Baseline maternal anti-D titer\n(serial titers NOT needed)",
                  MID_BLUE, fsize=7)
        self._arrow(c, cx, y, cx, y - 14, color=GREY)

        # Diamond: titer ≥1028?
        dy_d = y - 14 - 22
        self._diamond(c, cx, dy_d, 80, 22, "Titer ≥ 1:1028\nOR prior HDFN <24 wks?",
                      PURPLE, fsize=7)

        # YES: IVIG/TPE branch
        c.setFillColor(RED)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 4, dy_d - 28, "YES")
        self._arrow(c, cx, dy_d - 22, cx, dy_d - 22 - 14, color=RED)

        y_ivig = dy_d - 22 - 14 - bh - 4
        self._box(c, cx - 110, y_ivig, 220, bh + 10,
                  "IVIG ± Plasma Exchange\nStart 10-12 wks — bridge to IUT feasibility\n(saturates FcRn, reduces placental IgG transport)",
                  PURPLE, fsize=7)
        self._arrow(c, cx, y_ivig, cx, y_ivig - 12, color=RED)

        # MCA-PSV weekly from 15 wks
        y_mca = y_ivig - 12 - bh
        self._box(c, cx - bw/2 - 20, y_mca, bw + 40, bh,
                  "MCA-PSV WEEKLY from 15 wks gestation",
                  RED, fsize=7)

        # NO branch from diamond: standard monitoring
        no_x = cx - 80 - 10 - 115
        self._arrow(c, cx - 80, dy_d, no_x + 115, dy_d, color=GREEN)
        c.setFillColor(GREEN)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx - 78, dy_d + 4, "NO")

        y_prior = dy_d
        # Three sub-branches in a table-like column
        sub_data = [
            ("Prior HDFN ≥24 wks\nor neonatal exchange Tx",  "MCA-PSV weekly\nfrom 16 wks",  MID_BLUE),
            ("Prior neonatal\nphototherapy only",             "MCA-PSV weekly\nfrom 18 wks",  TEAL),
        ]
        start_y = dy_d + 10
        for label, action, col in sub_data:
            self._box(c, no_x, start_y - bh, 115, bh, label, col, fsize=6.5)
            self._box(c, no_x - 115 - 5, start_y - bh, 115, bh, action, col, fsize=6.5)
            self._arrow(c, no_x, start_y - bh/2, no_x - 5, start_y - bh/2, color=col)
            start_y -= bh + 8

        # Converge to MCA-PSV
        self._arrow(c, cx, y_mca, cx, y_mca - 14, color=GREY)
        y_fin = y_mca - 14 - bh - 2
        self._diamond(c, cx, y_fin - 10, 80, 22,
                      "MCA-PSV > 1.5 MoM?", ORANGE, fsize=7.5)
        # YES IUT
        self._arrow(c, cx, y_fin - 32, cx, y_fin - 32 - 14, color=RED)
        c.setFillColor(RED)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 4, y_fin - 34, "YES")

        y_iut2 = y_fin - 32 - 14 - bh
        self._box(c, cx - 65, y_iut2, 130, bh,
                  "IUT (18-35 wks) — confirm Hb\nDeliver ~3 wks after last IUT",
                  RED, fsize=7)

        # NO — deliver 37-38
        self._arrow(c, cx + 80, y_fin - 10, cx + 80 + 10, y_fin - 10, color=GREEN)
        c.setFillColor(GREEN)
        c.setFont("Helvetica-Bold", 7)
        c.drawString(cx + 82, y_fin - 6, "NO")
        self._box(c, cx + 90 + 10, y_fin - 10 - bh/2, 100, bh,
                  "No severe anemia\nDeliver 37-38 wks",
                  GREEN, fsize=7)


class InfoBox(Flowable):
    """Highlighted info/warning box."""
    def __init__(self, title, lines, color=LIGHT_BLUE, title_color=MID_BLUE,
                 width=None, border_color=None):
        Flowable.__init__(self)
        self.title = title
        self.lines = lines
        self.color = color
        self.title_color = title_color
        self.width = width or (W - 4 * cm)
        self.border_color = border_color or title_color
        self.height = 22 + len(lines) * 14 + 10

    def draw(self):
        c = self.canv
        c.setFillColor(self.color)
        c.setStrokeColor(self.border_color)
        c.setLineWidth(1.5)
        c.roundRect(0, 0, self.width, self.height, 6, fill=1, stroke=1)
        # Title
        c.setFillColor(self.title_color)
        c.setFont("Helvetica-Bold", 9)
        c.drawString(10, self.height - 16, self.title)
        # Lines
        c.setFillColor(DARK_GREY)
        c.setFont("Helvetica", 8)
        y = self.height - 30
        for line in self.lines:
            c.drawString(16, y, line)
            y -= 13


class MCAPhysioBox(Flowable):
    """Illustrates the MCA-PSV physiological mechanism."""
    def __init__(self, width, height=110):
        Flowable.__init__(self)
        self.width = width
        self.height = height

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

        # Background
        c.setFillColor(LIGHT_TEAL)
        c.setStrokeColor(TEAL)
        c.setLineWidth(1)
        c.roundRect(0, 0, W, H, 6, fill=1, stroke=1)

        # Title
        c.setFillColor(TEAL)
        c.setFont("Helvetica-Bold", 9)
        c.drawCentredString(W/2, H - 14, "Why Fetal Anemia Elevates MCA-PSV — The Physiological Chain")

        steps = [
            ("Hb falls", DARK_BLUE),
            ("O2 delivery\nreduced", MID_BLUE),
            ("Cardiac output\nincreases", TEAL),
            ("Blood viscosity\ndecreases", TEAL),
            ("MCA blood\nvelocity rises", RED),
            ("PSV > 1.5 MoM\n= Anemia alert", RED),
        ]
        n = len(steps)
        box_w = (W - 20) / n - 6
        box_h = 36
        x = 10
        y_step = H / 2 - box_h / 2 - 8

        for i, (text, col) in enumerate(steps):
            c.setFillColor(col)
            c.roundRect(x, y_step, box_w, box_h, 4, fill=1, stroke=0)
            c.setFillColor(white)
            c.setFont("Helvetica-Bold", 7)
            lines = text.split("\n")
            ty = y_step + box_h / 2 + len(lines) * 4 - 4
            for ln in lines:
                c.drawCentredString(x + box_w / 2, ty, ln)
                ty -= 9
            if i < n - 1:
                ax = x + box_w + 2
                ay = y_step + box_h / 2
                c.setStrokeColor(GREY)
                c.setFillColor(GREY)
                c.setLineWidth(1)
                c.line(ax, ay, ax + 4, ay)
                path = c.beginPath()
                path.moveTo(ax + 4, ay)
                path.lineTo(ax + 1, ay + 3)
                path.lineTo(ax + 1, ay - 3)
                path.close()
                c.drawPath(path, fill=1, stroke=0)
            x += box_w + 6

        c.setFillColor(GREY)
        c.setFont("Helvetica", 7)
        c.drawCentredString(W/2, 8,
            "Both mechanisms (increased CO + reduced viscosity) drive faster flow through cerebral arteries")


# ── Build the PDF ─────────────────────────────────────────────────────────────

def build():
    path = "/tmp/workspace/rh-alloimmunization/RhD_Alloimmunization_Summary.pdf"
    doc = SimpleDocTemplate(
        path, pagesize=A4,
        leftMargin=2*cm, rightMargin=2*cm,
        topMargin=2*cm, bottomMargin=2*cm,
        title="RhD Alloimmunization in Pregnancy — Management Summary",
        author="Educational Summary (UpToDate 2025/26)"
    )

    S = make_styles()
    usable_w = W - 4 * cm
    story = []

    # ─────────────────────────────────────────────────
    # PAGE 1: Cover
    # ─────────────────────────────────────────────────
    story.append(CoverPage(usable_w, 700))
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 2: Pathophysiology Overview
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "1. Pathophysiology Overview",
        "Why does HDFN occur — and why does it worsen with each pregnancy?",
        DARK_BLUE, usable_w
    ))
    story.append(Spacer(1, 8))

    path_data = [
        ["Event", "What Happens", "Clinical Implication"],
        ["Sensitizing\nevent", "RhD-negative mother exposed to RhD-positive RBCs\n(prior delivery, miscarriage, transfusion, needle-sharing)",
         "Primary immune response — IgM then IgG anti-D produced"],
        ["Subsequent\npregnancy", "Anamnestic (secondary) response fires earlier, produces\nhigh-titer IgG anti-D from memory B cells",
         "Fetal anemia develops earlier and is more severe"],
        ["IgG transport", "Anti-D IgG (NOT IgM) crosses placenta via FcRn receptor\non syncytiotrophoblast",
         "FcRn is the therapeutic target for IVIG and nipocalimab"],
        ["Fetal\nhemolysis", "Anti-D coats fetal RhD+ RBCs → extravascular destruction\nby fetal spleen and liver",
         "Leads to fetal anemia, extramedullary hematopoiesis, hydrops"],
        ["Hydrops\ncascade", "Severe anemia → heart failure → capillary leak → ascites,\npleural effusion, skin edema",
         "Mortality very high — prevent by transfusing at moderate anemia"],
    ]
    t = Table(path_data, colWidths=[65, 230, 190])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 7.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_GREY, white]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#cccccc")),
        ("LEFTPADDING", (0, 0), (-1, -1), 5),
        ("RIGHTPADDING", (0, 0), (-1, -1), 5),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("TEXTCOLOR", (0, 1), (0, -1), DARK_BLUE),
    ]))
    story.append(t)
    story.append(Spacer(1, 10))

    # Key pathophys rule box
    story.append(InfoBox(
        "Key Pathophysiology Rules",
        [
            "• Anti-D Ig (Rh immune globulin) ONLY prevents primary sensitization — never give to already-sensitized patients",
            "• IgG crosses placenta; IgM does NOT — this is why anti-D can cause HDFN",
            "• FcRn (neonatal Fc receptor) is the only known transplacental IgG transporter — target for nipocalimab",
            "• Every delivery with a RhD-positive fetus boosts maternal anti-D titer via fetomaternal hemorrhage (anamnestic response)",
        ],
        LIGHT_BLUE, MID_BLUE, usable_w, MID_BLUE
    ))
    story.append(Spacer(1, 10))

    # MCA physiological chain
    story.append(Paragraph("MCA-PSV Physiological Mechanism", S["h2"]))
    story.append(MCAPhysioBox(usable_w, 110))
    story.append(Spacer(1, 6))
    story.append(Paragraph(
        "MCA-PSV is used (not umbilical artery or aorta) because the fetal brain is a flow-priority organ — "
        "cerebral autoregulation ensures the Circle of Willis reflects whole-body hemodynamic state.",
        S["body"]
    ))
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 3: Flowchart 1 — First Pregnancy
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "2. First Alloimmunized Pregnancy — Decision Flowchart",
        "Step-by-step management algorithm with pathophysiological rationale",
        MID_BLUE, usable_w
    ))
    story.append(Spacer(1, 6))
    story.append(Flowchart1(usable_w, 540))
    story.append(Spacer(1, 8))
    story.append(Paragraph(
        "cfDNA = cell-free fetal DNA  |  MCA-PSV = middle cerebral artery peak systolic velocity  |  "
        "MoM = multiples of median (corrected for gestational age)  |  IUT = intrauterine transfusion  |  "
        "GA = gestational age  |  Hb = fetal hemoglobin",
        S["caption"]
    ))
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 4: MCA-PSV details + Titer details
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "3. MCA-PSV Doppler — Principles, Thresholds & Technique",
        "The non-invasive cornerstone of fetal anemia surveillance",
        TEAL, usable_w
    ))
    story.append(Spacer(1, 8))

    mca_data = [
        ["MCA-PSV\n(MoM)", "Interpretation", "Action"],
        ["< 1.4 MoM", "No significant anemia", "Continue q1-2 wk Doppler surveillance"],
        ["1.4 – 1.5 MoM", "Borderline — rising trend", "Increase frequency to 1-2×/wk"],
        ["> 1.5 MoM", "Moderate-severe anemia suspected\n(sensitivity 88-100%, specificity 87-91%)",
         "Cordocentesis to confirm Hb — have IUT blood ready"],
        ["> 1.5 MoM at\n≥ 35+0 wks", "IUT risk > benefit of waiting",
         "DELIVER — evaluate and treat neonate ex utero"],
    ]
    t2 = Table(mca_data, colWidths=[80, 220, 185])
    t2.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), TEAL),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 8),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_TEAL, white]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#aaaaaa")),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("RIGHTPADDING", (0, 0), (-1, -1), 6),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("BACKGROUND", (0, 4), (-1, 4), LIGHT_RED),
        ("FONTNAME", (0, 4), (-1, 4), "Helvetica-Bold"),
        ("TEXTCOLOR", (0, 4), (-1, 4), RED),
    ]))
    story.append(t2)
    story.append(Spacer(1, 8))

    story.append(InfoBox(
        "Critical Technique Points",
        [
            "• Always measure when fetus is in QUIET behavioural state — active movement causes false elevations",
            "• MCA-PSV must be converted to MoM using a gestational-age calculator (perinatology.com)",
            "• After intrauterine transfusions: 1.5 MoM threshold becomes LESS reliable (donor adult Hb)",
            "• Perform at Circle of Willis (axial view of fetal head), angle of insonation as close to 0° as possible",
            "• Sensitivity decreases after 35 weeks gestation — this is why delivery is preferred over IUT at ≥35 wks",
        ],
        LIGHT_TEAL, TEAL, usable_w
    ))
    story.append(Spacer(1, 10))

    story.append(SectionHeader(
        "Indirect Coombs Titer — Key Facts",
        "When to use, when to stop, and the critical titer",
        MID_BLUE, usable_w
    ))
    story.append(Spacer(1, 8))

    titer_data = [
        ["Titer Level", "Significance", "Action"],
        ["< 1:16\n(below critical)", "Risk of mild-moderate anemia only\n(NOT severe)", "Monthly titers to 24 wks, then q2wks"],
        ["1:16\n(critical titer)", "Below this = <50% risk of severe HDFN\nAbove this = fetus at risk for severe anemia",
         "SWITCH to MCA-PSV Doppler — stop serial titers"],
        ["Rising titer", "Repeat weekly until critical titer reached\n(1-dilution variation = likely noise; ≥2 dilutions = real)",
         "Same lab always; run prior sample alongside new sample"],
        ["≥ 1:1028\n(subsequent Px)", "Extreme maternal alloimmunization — fetal anemia\npossible before IUT is technically feasible",
         "Start IVIG ± plasma exchange at 10-12 wks\nMCA-PSV weekly from 15 wks"],
    ]
    t3 = Table(titer_data, colWidths=[80, 225, 180])
    t3.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), MID_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 7.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_BLUE, white]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#aaaaaa")),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("RIGHTPADDING", (0, 0), (-1, -1), 6),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        ("BACKGROUND", (0, 4), (-1, 4), LIGHT_PURPLE),
        ("TEXTCOLOR", (0, 4), (0, 4), PURPLE),
        ("FONTNAME", (0, 4), (0, 4), "Helvetica-Bold"),
    ]))
    story.append(t3)
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 5: Fetal Hb Reference Table
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "4. Fetal Hemoglobin Reference Table",
        "Threshold for IUT: Hb < 2 SD below mean for gestational age | Alternative: Hct < 30%",
        RED, usable_w
    ))
    story.append(Spacer(1, 8))

    # Fetal Hb reference values (established reference, Moise/Mari)
    # Values: Mean Hb, -2SD, Hydrops Hb threshold
    hb_data = [
        ["Gestational Age\n(weeks)", "Mean Hb\n(g/dL)", "−2 SD\n(IUT threshold, g/dL)",
         "Severe Anemia\n(deficit >7 g/dL below mean)", "Hydrops Risk\n(Hb approx.)"],
        ["18", "11.5", "9.0", "< 4.5", "< 5.0"],
        ["20", "12.0", "9.4", "< 5.0", "< 5.0"],
        ["22", "12.5", "9.7", "< 5.5", "< 5.5"],
        ["24", "13.0", "10.2", "< 6.0", "< 5.5"],
        ["26", "13.5", "10.6", "< 6.5", "< 6.0"],
        ["28", "14.0", "11.0", "< 7.0", "< 6.0"],
        ["30", "14.5", "11.4", "< 7.5", "< 6.0"],
        ["32", "15.0", "11.8", "< 8.0", "< 7.0"],
        ["34", "15.5", "12.2", "< 8.5", "< 7.0"],
        ["36", "16.0", "12.5", "< 9.0", "< 7.5"],
        ["38", "16.5", "13.0", "< 9.5", "< 8.0"],
        ["40", "17.0", "13.5", "< 10.0", "< 8.0"],
    ]

    col_colors_hb = [
        [None] + [LIGHT_GREY if i % 2 == 0 else white for i in range(len(hb_data)-1)],
    ]

    t_hb = Table(hb_data, colWidths=[80, 70, 110, 130, 95])
    t_hb.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), RED),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 8),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_GREY, white]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#aaaaaa")),
        ("LEFTPADDING", (0, 0), (-1, -1), 5),
        ("RIGHTPADDING", (0, 0), (-1, -1), 5),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("TEXTCOLOR", (0, 1), (0, -1), DARK_BLUE),
        # Highlight IUT threshold column
        ("BACKGROUND", (2, 0), (2, 0), RED),
        ("TEXTCOLOR", (2, 1), (2, -1), RED),
        ("FONTNAME", (2, 1), (2, -1), "Helvetica-Bold"),
    ]))
    story.append(t_hb)
    story.append(Spacer(1, 6))

    story.append(InfoBox(
        "How to Use This Table in Practice",
        [
            "• Perform cordocentesis when MCA-PSV > 1.5 MoM — obtain fetal blood Hb before transfusing",
            "• If fetal Hb < value in the −2SD column for that gestational age → perform IUT immediately",
            "• If fetal Hb is above −2SD → repeat cordocentesis in 1-2 weeks depending on the value",
            "• IUT is limited to 18-35 weeks gestation; at ≥35 wks deliver instead",
            "• Hematocrit < 30% is an alternative threshold to the −2SD Hb criterion",
            "• Transfuse BEFORE hydrops develops — hydrops = Hb typically < 5 g/dL with very high mortality",
        ],
        LIGHT_RED, RED, usable_w
    ))
    story.append(Spacer(1, 8))

    # Hematocrit reference note
    story.append(Paragraph(
        "<b>Note on reference values:</b> Normal fetal Hb rises with gestation (erythropoiesis matures). "
        "Values shown are approximate and based on the Mari et al. reference population used in the "
        "landmark MCA-PSV studies. Your institution may use slight variants. The −2SD column is the "
        "<b>clinical decision threshold</b>. Transfusing at this point prevents the cascade to severe anemia "
        "and hydrops, which has significantly worse outcomes.",
        S["body"]
    ))
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 6: Subsequent Pregnancies Flowchart
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "5. Subsequent Pregnancies — Management Flowchart",
        "Anamnestic response means earlier, more severe anemia — escalate monitoring accordingly",
        PURPLE, usable_w
    ))
    story.append(Spacer(1, 8))
    story.append(Flowchart2(usable_w, 440))
    story.append(Spacer(1, 6))

    # Monitoring start table
    story.append(Paragraph("When to Start MCA-PSV Monitoring — Stratified by Prior Pregnancy", S["h3"]))
    mon_data = [
        ["Prior Pregnancy Severity", "Start MCA-PSV\nMonitoring at", "Frequency"],
        ["Severe HDFN <24 wks OR titer ≥1:1028",
         "15 weeks", "Weekly throughout"],
        ["Severe HDFN ≥24 wks / preterm birth from MCA >1.5 MoM /\nneonatal exchange transfusion",
         "16 weeks", "Weekly throughout"],
        ["Prior neonatal phototherapy only (mild HDFN)",
         "18 weeks", "Weekly × 3, then q2wks\n(↑ to weekly if 1.4-1.5 MoM)"],
        ["No prior HDFN (first affected pregnancy)",
         "When titer\nreaches 1:16", "Every 1-2 weeks"],
    ]
    t_mon = Table(mon_data, colWidths=[230, 80, 175])
    t_mon.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), PURPLE),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 7.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_PURPLE, white]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#aaaaaa")),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("RIGHTPADDING", (0, 0), (-1, -1), 6),
        ("TOPPADDING", (0, 0), (-1, -1), 5),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
        # Highlight most severe row
        ("BACKGROUND", (0, 1), (-1, 1), LIGHT_RED),
        ("TEXTCOLOR", (1, 1), (1, 1), RED),
        ("FONTNAME", (1, 1), (1, 1), "Helvetica-Bold"),
    ]))
    story.append(t_mon)
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 7: Bridge Therapies
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "6. Bridge Therapies — IVIG, Plasma Exchange, Nipocalimab",
        "For very severe alloimmunization (titer ≥1:1028) and prior loss <24 weeks",
        PURPLE, usable_w
    ))
    story.append(Spacer(1, 8))

    therapy_data = [
        ["Therapy", "Mechanism", "When to Use", "Evidence"],
        ["IVIG\n(Intravenous\nImmunoglobulin)", 
         "Saturates FcRn on syncytiotrophoblast\n→ reduces anti-D transport to fetus.\nAlso accelerates IgG catabolism\n(competes for FcRn recycling)",
         "Start at 10-12 wks.\nContinue until IUT\nfeasible (18 wks)\nor resolution",
         "IPD meta-analysis: delayed 1st IUT\nby 3.19 wks vs prior pregnancy;\nreduced fetal demise (IR 0.23)"],
        ["Therapeutic\nPlasma\nExchange (TPE)",
         "Directly removes circulating\nmaternal anti-D IgG from plasma.\nEffect temporary (rebound occurs)",
         "Combined with IVIG\nto blunt post-TPE\nrebound",
         "Case series/reports only.\nASH guidelines: mainstay = IUT;\nTPE/IVIG if hydrops <20 wks"],
        ["Nipocalimab\n(Investigational)",
         "Monoclonal antibody — specifically\nbinds FcRn and BLOCKS all placental\nIgG transport. Also promotes IgG\ncatabolism (most targeted approach)",
         "Phase 2 only —\nnot yet standard\nof care",
         "Phase 2 (n=13): 54% live birth\n≥32 wks without IUT.\nMaternal anti-D titer decreased.\nNo hydrops in treated group"],
    ]

    t_th = Table(therapy_data, colWidths=[75, 165, 115, 130])
    t_th.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), PURPLE),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 7.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_PURPLE, white]),
        ("GRID", (0, 0), (-1, -1), 0.4, HexColor("#aaaaaa")),
        ("LEFTPADDING", (0, 0), (-1, -1), 6),
        ("RIGHTPADDING", (0, 0), (-1, -1), 6),
        ("TOPPADDING", (0, 0), (-1, -1), 6),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 6),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("TEXTCOLOR", (0, 1), (0, -1), PURPLE),
        ("BACKGROUND", (0, 3), (-1, 3), LIGHT_YELLOW),
        ("TEXTCOLOR", (0, 3), (0, 3), HexColor("#7d5a00")),
    ]))
    story.append(t_th)
    story.append(Spacer(1, 8))

    story.append(InfoBox(
        "FcRn — The Central Therapeutic Target",
        [
            "• FcRn (neonatal Fc receptor) = ONLY known transplacental IgG transporter",
            "• Located on syncytiotrophoblast — binds IgG at acidic endosomal pH, releases at neutral pH on fetal side",
            "• IVIG works by SATURATING FcRn (competitive inhibition of anti-D transport)",
            "• Nipocalimab works by BLOCKING FcRn directly (more complete inhibition, fewer escape)",
            "• Both approaches reduce fetal anti-D exposure — allowing time to reach IUT-feasible gestational age",
        ],
        LIGHT_PURPLE, PURPLE, usable_w
    ))
    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 8: Ward Pearls
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "7. Ward Pearls — Quick Reference",
        "Pathophysiology-based clinical pearls for ward rounds",
        DARK_GREY, usable_w
    ))
    story.append(Spacer(1, 8))

    pearls = [
        ("PEARL 1", "Never give anti-D Ig to a sensitized patient",
         "Anti-D Ig only works as PRIMARY prophylaxis. Once memory B cells exist, "
         "no amount of passive antibody will suppress them. Administration is useless and potentially confusing.",
         LIGHT_RED, RED),
        ("PEARL 2", "Non-paternity is more common than you think — document the discussion",
         "If you assume the father is RhD-negative without cfDNA confirmation, "
         "and non-paternity exists, you will miss a fetus at risk for severe HDFN. "
         "Document the paternity discussion in the medical record.",
         LIGHT_ORANGE, ORANGE),
        ("PEARL 3", "Titers can rise even when the fetus is RhD-negative",
         "The reason is unclear (possibly non-specific B-cell stimulation). "
         "This is why titer is a crude screening tool (specificity ~50-60%). "
         "Always confirm fetal RhD status if not already done when titer hits critical.",
         LIGHT_BLUE, MID_BLUE),
        ("PEARL 4", "Always use the SAME laboratory for serial titers",
         "A 1-dilution change (e.g., 1:8 to 1:16) can represent assay variation, not real antibody rise. "
         "A ≥2-dilution change (e.g., 1:8 to 1:32) is clinically real. "
         "Different labs give different baseline numbers — never compare across labs.",
         LIGHT_TEAL, TEAL),
        ("PEARL 5", "Sinusoidal CTG pattern = severely anemic fetus",
         "The smooth undulating waveform with no beat-to-beat variability is caused by "
         "CNS/brainstem hypoxia from severe anemia affecting cardiac autonomic centers. "
         "This is a Category III tracing — act urgently.",
         LIGHT_RED, RED),
        ("PEARL 6", "Transfuse at moderate anemia — do not wait for hydrops",
         "Hydrops = Hb typically <5 g/dL — at this point the fetal myocardium is failing, "
         "IUT is technically riskier, and mortality is very high. Transfusing at −2SD Hb "
         "prevents the hydrops cascade and gives better outcomes.",
         LIGHT_ORANGE, ORANGE),
        ("PEARL 7", "MCA-PSV accuracy falls with multiple IUTs",
         "After transfusion(s), fetal blood contains mostly adult donor Hb (higher O2 affinity, "
         "different rheological properties). The physiological relationship between Hb and velocity "
         "changes. Do not blindly trust 1.5 MoM in heavily transfused fetuses.",
         LIGHT_BLUE, MID_BLUE),
        ("PEARL 8", "Delayed cord clamping is NOT contraindicated in HDFN",
         "Counterintuitive but supported by RCT data (n=70): delayed clamping improved neonatal "
         "RBC volume at 2 hours without increasing exchange transfusion needs. "
         "The RBC volume benefit outweighs any concern.",
         LIGHT_GREEN, GREEN),
        ("PEARL 9", "Anti-C antibodies alongside anti-D = more aggressive disease",
         "C antigen is co-inherited with D on the same Rh haplotype (DCe). Mothers who have "
         "both anti-D and anti-C have been sensitized to two antigens — synergistically higher "
         "risk for severe fetal anemia and need for IUT. Pre-order crossmatched blood for labor.",
         LIGHT_PURPLE, PURPLE),
        ("PEARL 10", "After 35 weeks — deliver, don't transfuse intrauterinely",
         "MCA-PSV sensitivity for severe anemia decreases after 35 weeks. "
         "IUT procedural risk does not decrease. After 35+0 weeks, "
         "if MCA-PSV >1.5 MoM — proceed to delivery and treat the neonate.",
         LIGHT_RED, RED),
    ]

    for i, (tag, title, text, bg, col) in enumerate(pearls):
        data = [[
            Paragraph(f"<b>{tag}</b>", ParagraphStyle("pt", fontSize=8, textColor=col, fontName="Helvetica-Bold", leading=10)),
            Paragraph(f"<b>{title}</b><br/><font size='7.5'>{text}</font>",
                      ParagraphStyle("pb", fontSize=7.5, leading=11, fontName="Helvetica", textColor=DARK_GREY))
        ]]
        t_p = Table(data, colWidths=[55, usable_w - 55])
        t_p.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, -1), bg),
            ("LEFTPADDING", (0, 0), (-1, -1), 6),
            ("RIGHTPADDING", (0, 0), (-1, -1), 6),
            ("TOPPADDING", (0, 0), (-1, -1), 5),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
            ("VALIGN", (0, 0), (-1, -1), "TOP"),
            ("ROUNDEDCORNERS", [4, 4, 4, 4]),
            ("LINEBELOW", (0, 0), (-1, -1), 0.5, white),
        ]))
        story.append(t_p)
        story.append(Spacer(1, 4))

    story.append(PageBreak())

    # ─────────────────────────────────────────────────
    # PAGE 9: Summary Decision Matrix
    # ─────────────────────────────────────────────────
    story.append(SectionHeader(
        "Summary: 3 Clinical Questions — Applied to Every Patient",
        "The pathophysiology-driven bedside framework",
        DARK_BLUE, usable_w
    ))
    story.append(Spacer(1, 10))

    q_data = [
        ["#", "Clinical Question", "How to Answer", "Implication if Positive"],
        ["1", "Is the fetus\nactually at risk?",
         "Paternal RhD → cfDNA from\n10 wks gestation\n(Sensitivity 99-100%)",
         "If RhD-positive: monitor. If RhD-negative:\nno monitoring needed at all."],
        ["2", "How much antibody\nis circulating?",
         "Maternal indirect Coombs\ntiter (same lab always)",
         "If ≥1:16 (critical): switch entirely to Doppler.\nIf ≥1:1028: bridge therapy (IVIG/TPE)."],
        ["3", "Is the fetus\nactually anemic NOW?",
         "MCA-PSV Doppler q1-2 wks.\nIf >1.5 MoM: cordocentesis",
         "If Hb <−2SD for GA: perform IUT (18-35 wks)\nor deliver if ≥35 wks."],
    ]
    t_q = Table(q_data, colWidths=[20, 120, 165, 180])
    t_q.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), DARK_BLUE),
        ("TEXTCOLOR", (0, 0), (-1, 0), white),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, 0), 8.5),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("FONTNAME", (0, 1), (-1, -1), "Helvetica"),
        ("FONTSIZE", (0, 1), (-1, -1), 8.5),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [LIGHT_BLUE, white]),
        ("GRID", (0, 0), (-1, -1), 0.5, HexColor("#aaaaaa")),
        ("LEFTPADDING", (0, 0), (-1, -1), 7),
        ("RIGHTPADDING", (0, 0), (-1, -1), 7),
        ("TOPPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
        ("FONTNAME", (0, 1), (0, -1), "Helvetica-Bold"),
        ("FONTSIZE", (0, 1), (0, -1), 12),
        ("TEXTCOLOR", (0, 1), (0, -1), DARK_BLUE),
        ("ALIGN", (0, 1), (0, -1), "CENTER"),
        ("FONTNAME", (1, 1), (1, -1), "Helvetica-Bold"),
        ("TEXTCOLOR", (1, 1), (1, -1), DARK_BLUE),
    ]))
    story.append(t_q)
    story.append(Spacer(1, 16))

    # Final summary box
    story.append(InfoBox(
        "Delivery Timing Summary",
        [
            "First pregnancy, no transfusion, MCA-PSV ≤1.5 MoM throughout:  Deliver at 37+0 to 38+6 weeks",
            "First pregnancy, MCA-PSV >1.5 MoM at ≥35+0 weeks:               Deliver immediately (no IUT)",
            "First pregnancy, IUT performed:                                  Deliver ~3 weeks after last IUT at 37-38 weeks",
            "Subsequent pregnancy, no IUT needed:                             Deliver at 37-38 weeks",
            "Any pregnancy with MCA-PSV >1.5 MoM at ≥35+0 weeks:            Deliver — evaluate neonate ex utero",
        ],
        LIGHT_GREEN, GREEN, usable_w
    ))
    story.append(Spacer(1, 10))

    story.append(Paragraph(
        "<i>Source: UpToDate® — RhD alloimmunization in pregnancy: Management. "
        "Kenneth J Moise Jr, MD. Literature review through Jul 2026; last updated Mar 25, 2025. "
        "For educational use only.</i>",
        S["caption"]
    ))

    doc.build(story)
    print(f"PDF created: {path}")
    return path

if __name__ == "__main__":
    build()
Running Command

cd /tmp/workspace/rh-alloimmunization && python3 build_pdf.py 2>&1

Running Command

ls -lh /tmp/workspace/rh-alloimmunization/RhD_Alloimmunization_Summary.pdf && python3 -c " import pdfplumber with pdfplumber.open('/tmp/workspace/rh-alloimmunization/RhD_Alloimmunization_Summary.pdf') as pdf: print(f'Pages: {len(pdf.pages)}') for i, page in enumerate(pdf.pages): t = page.extract_text() print(f'Page {i+1}: {len(t or \"\")} chars') "

Your PDF is ready:

RhD Alloimmunization Summary

PDF Document · PDF


What's inside (9 pages):
PageContent
1Cover page with contents overview
2Pathophysiology overview table + MCA-PSV physiological chain diagram
3First alloimmunized pregnancy - full decision flowchart (step-by-step with branching logic)
4MCA-PSV threshold table + Indirect Coombs titer reference table
5Fetal Hemoglobin Reference Table (18-40 weeks: mean Hb, -2SD IUT threshold, severe anemia level, hydrops risk)
6Subsequent pregnancies flowchart + monitoring start stratification table
7Bridge therapies comparison table (IVIG vs TPE vs Nipocalimab with mechanism + evidence)
810 Ward Pearls (colour-coded by theme with pathophysiological explanation for each)
93-Question bedside framework + delivery timing summary
Everything is colour-coded: red for urgent/critical thresholds, teal for Doppler, purple for subsequent pregnancies and bridge therapies, green for reassuring findings. The flowcharts have branching arrows with YES/NO labels so you can trace any clinical scenario directly.
This is a shared conversation. Sign in to Orris to start your own chat.