Can you generate for me ,everything i need to know abiut midwifery before assessment as a BSN nursing student in second year ,and put them in a link for me.

Asking for Preferences

2

Reading File
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Running Command

mkdir -p /tmp/workspace/midwifery-study-guide && ls /tmp/workspace/midwifery-study-guide/

Writing File

~/midwifery-study-guide/generate_midwifery.py

from docx import Document
from docx.shared import Pt, Inches, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
import datetime

doc = Document()

# ── Page margins ──────────────────────────────────────────────────────────────
for section in doc.sections:
    section.top_margin    = Inches(1)
    section.bottom_margin = Inches(1)
    section.left_margin   = Inches(1.2)
    section.right_margin  = Inches(1.2)

# ── Default Normal style ───────────────────────────────────────────────────────
normal = doc.styles['Normal']
normal.font.name = 'Arial'
normal.font.size = Pt(11)

# ── Heading helpers ────────────────────────────────────────────────────────────
def h1(text):
    p = doc.add_heading(text, level=1)
    p.runs[0].font.color.rgb = RGBColor(0x1A, 0x53, 0x8A)
    p.paragraph_format.space_before = Pt(18)
    p.paragraph_format.space_after  = Pt(6)

def h2(text):
    p = doc.add_heading(text, level=2)
    p.runs[0].font.color.rgb = RGBColor(0x2E, 0x74, 0xB5)
    p.paragraph_format.space_before = Pt(12)
    p.paragraph_format.space_after  = Pt(4)

def h3(text):
    p = doc.add_heading(text, level=3)
    p.runs[0].font.color.rgb = RGBColor(0x1F, 0x49, 0x6D)
    p.paragraph_format.space_before = Pt(8)
    p.paragraph_format.space_after  = Pt(2)

def body(text):
    p = doc.add_paragraph(text)
    p.paragraph_format.space_after = Pt(4)
    return p

def bullet(text, level=0):
    p = doc.add_paragraph(text, style='List Bullet')
    p.paragraph_format.left_indent = Inches(0.3 + 0.2*level)
    p.paragraph_format.space_after = Pt(2)
    return p

def numbered(text, level=0):
    p = doc.add_paragraph(text, style='List Number')
    p.paragraph_format.left_indent = Inches(0.3 + 0.2*level)
    p.paragraph_format.space_after = Pt(2)
    return p

def bold_bullet(label, text):
    p = doc.add_paragraph(style='List Bullet')
    run = p.add_run(label + ': ')
    run.bold = True
    p.add_run(text)
    p.paragraph_format.space_after = Pt(2)
    return p

def note_box(text):
    """A shaded paragraph used as a callout/key-point box."""
    p = doc.add_paragraph()
    p.paragraph_format.left_indent  = Inches(0.3)
    p.paragraph_format.right_indent = Inches(0.3)
    p.paragraph_format.space_before = Pt(4)
    p.paragraph_format.space_after  = Pt(4)
    shading_elm = OxmlElement('w:shd')
    shading_elm.set(qn('w:val'),   'clear')
    shading_elm.set(qn('w:color'), 'auto')
    shading_elm.set(qn('w:fill'),  'DEEAF1')
    p._p.get_or_add_pPr().append(shading_elm)
    run = p.add_run('KEY POINT: ')
    run.bold = True
    run.font.color.rgb = RGBColor(0x1A, 0x53, 0x8A)
    p.add_run(text)
    return p

def add_table(headers, rows):
    table = doc.add_table(rows=1 + len(rows), cols=len(headers))
    table.style = 'Table Grid'
    hdr_cells = table.rows[0].cells
    for i, h in enumerate(headers):
        hdr_cells[i].text = h
        for run in hdr_cells[i].paragraphs[0].runs:
            run.bold = True
        shading = OxmlElement('w:shd')
        shading.set(qn('w:val'),   'clear')
        shading.set(qn('w:color'), 'auto')
        shading.set(qn('w:fill'),  '2E74B5')
        hdr_cells[i].paragraphs[0].runs[0].font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
        hdr_cells[i]._tc.get_or_add_tcPr().append(shading)
    for row_data in rows:
        row_cells = table.add_row().cells
        for i, val in enumerate(row_data):
            row_cells[i].text = val
    doc.add_paragraph()   # space after table

# ══════════════════════════════════════════════════════════════════════════════
#  COVER PAGE
# ══════════════════════════════════════════════════════════════════════════════
cover = doc.add_paragraph()
cover.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = cover.add_run('\n\n\nMIDWIFERY\nCOMPREHENSIVE STUDY GUIDE')
run.bold = True
run.font.size = Pt(26)
run.font.color.rgb = RGBColor(0x1A, 0x53, 0x8A)

sub = doc.add_paragraph()
sub.alignment = WD_ALIGN_PARAGRAPH.CENTER
sub.add_run('BSN Second-Year Nursing Student | Pre-Assessment Reference\n').font.size = Pt(13)

date_p = doc.add_paragraph()
date_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
date_p.add_run(f'Generated: {datetime.date.today().strftime("%B %d, %Y")}').font.size = Pt(11)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  TABLE OF CONTENTS (manual)
# ══════════════════════════════════════════════════════════════════════════════
h1('TABLE OF CONTENTS')
toc_items = [
    ('1', 'Introduction to Midwifery'),
    ('2', 'Female Reproductive Anatomy & Physiology'),
    ('3', 'Conception, Fertilisation & Implantation'),
    ('4', 'Physiological Changes in Pregnancy'),
    ('5', 'Antenatal Care'),
    ('6', 'Fetal Development & Monitoring'),
    ('7', 'Normal Labour & Delivery'),
    ('8', 'Management of the Third Stage of Labour'),
    ('9', 'Postnatal (Postpartum) Care'),
    ('10', 'Neonatal Care & Assessment'),
    ('11', 'Breastfeeding & Infant Nutrition'),
    ('12', 'Obstetric Complications & Emergencies'),
    ('13', 'Pharmacology in Midwifery'),
    ('14', 'Infection Control & Asepsis'),
    ('15', 'Legal, Ethical & Professional Issues'),
    ('16', 'Key Mnemonics & Quick-Reference Tables'),
]
for num, title in toc_items:
    p = doc.add_paragraph()
    run = p.add_run(f'  {num}.  {title}')
    run.font.size = Pt(11)
    p.paragraph_format.space_after = Pt(3)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 1 – INTRODUCTION TO MIDWIFERY
# ══════════════════════════════════════════════════════════════════════════════
h1('1. Introduction to Midwifery')

h2('1.1 Definition')
body('Midwifery is the health science and health profession that deals with pregnancy, childbirth, and the postpartum period (including care of the newborn), besides the sexual and reproductive health of women throughout their lives.')

h2('1.2 Scope of Practice for BSN Nurses in Midwifery')
bullet('Conducting routine antenatal assessments under supervision')
bullet('Assisting with and monitoring normal labour and delivery')
bullet('Providing immediate newborn care')
bullet('Initiating and supporting breastfeeding')
bullet('Providing postnatal care to mother and infant')
bullet('Health education and counselling on family planning, nutrition, hygiene')
bullet('Recognising and escalating obstetric emergencies')

h2('1.3 Key Midwifery Models of Care')
bold_bullet('Woman-centred care', 'Respects the woman\'s individual preferences, needs, and values.')
bold_bullet('Continuity of care', 'The same midwife or team provides care throughout the childbearing continuum.')
bold_bullet('Evidence-based practice', 'Clinical decisions are guided by best available research, clinical expertise, and patient values.')
bold_bullet('Partnership model', 'Collaborative relationship between the midwife, woman, and health team.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 2 – FEMALE REPRODUCTIVE ANATOMY & PHYSIOLOGY
# ══════════════════════════════════════════════════════════════════════════════
h1('2. Female Reproductive Anatomy & Physiology')

h2('2.1 External Genitalia (Vulva)')
bullet('Mons pubis, labia majora, labia minora')
bullet('Clitoris – homologue of penis; highly sensitive erectile tissue')
bullet('Vestibule – contains urethral orifice, vaginal orifice, Bartholin\'s gland openings')
bullet('Perineum – area between vaginal orifice and anus; important in childbirth')

h2('2.2 Internal Organs')
add_table(
    ['Structure', 'Key Features', 'Relevance to Midwifery'],
    [
        ['Vagina', '7-10 cm fibromuscular canal; rugae allow distension', 'Birth canal; pH 3.8-4.5 protects against infection'],
        ['Uterus', 'Pear-shaped; 7.5 x 5 x 2.5 cm (non-pregnant)', 'Grows to accommodate foetus; contracts during labour'],
        ['Cervix', 'Lower cylindrical part of uterus; os opens during labour', 'Effacement & dilation are signs of active labour'],
        ['Fallopian tubes', '10 cm; ampulla is site of fertilisation', 'Ectopic pregnancy risk if occluded'],
        ['Ovaries', 'Paired; produce ova & hormones (oestrogen, progesterone)', 'Ovulation occurs here; site of follicular development'],
    ]
)

h2('2.3 The Menstrual Cycle (Average 28 days)')
numbered('Follicular phase (Days 1-13): FSH stimulates follicular growth; oestrogen rises; endometrium proliferates.')
numbered('Ovulation (Day 14): LH surge triggers release of mature oocyte from Graafian follicle.')
numbered('Luteal phase (Days 15-28): Corpus luteum secretes progesterone; endometrium becomes secretory.')
numbered('Menstruation (Day 1 of next cycle): If no fertilisation, progesterone drops, endometrium sheds.')
note_box('Progesterone maintains the uterine lining in early pregnancy. Its drop before term triggers labour onset.')

h2('2.4 Pelvis')
body('The female pelvis is adapted for childbirth. Key measurements:')
add_table(
    ['Pelvic Type', 'Shape', 'Frequency', 'Significance for Labour'],
    [
        ['Gynaecoid', 'Round/oval', '~50% of women', 'Most favourable for vaginal delivery'],
        ['Android', 'Heart-shaped', '~20%', 'Narrow; associated with instrumental delivery'],
        ['Anthropoid', 'Oval (A-P long)', '~25%', 'Favourable if foetus engages in OP position'],
        ['Platypelloid', 'Flat oval', '~5%', 'Unfavourable; may require caesarean'],
    ]
)
body('Obstetric Conjugate (>10 cm) and transverse diameter (>12 cm) are clinically important.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 3 – CONCEPTION, FERTILISATION & IMPLANTATION
# ══════════════════════════════════════════════════════════════════════════════
h1('3. Conception, Fertilisation & Implantation')

h2('3.1 Fertilisation')
bullet('Sperm survives 3-5 days in female reproductive tract; ovum survives 12-24 hours post-ovulation.')
bullet('Fertilisation occurs in the ampulla of the fallopian tube.')
bullet('Acrosome reaction: sperm releases enzymes to penetrate zona pellucida of oocyte.')
bullet('Fusion of pronuclei (23 + 23 chromosomes) forms diploid zygote (46 chromosomes).')
bullet('Zona reaction prevents polyspermy.')

h2('3.2 Early Development Timeline')
add_table(
    ['Day', 'Event'],
    [
        ['Day 0', 'Fertilisation - zygote formed'],
        ['Day 2-3', 'Cleavage - 2-cell to morula stage; cells called blastomeres'],
        ['Day 4', 'Morula enters uterine cavity'],
        ['Day 5-6', 'Blastocyst forms - inner cell mass (embryoblast) + trophoblast'],
        ['Day 6-10', 'Implantation - blastocyst embeds into posterior wall of uterus (decidua)'],
        ['Day 10-14', 'Trophoblast differentiates into cytotrophoblast & syncytiotrophoblast; hCG produced'],
    ]
)

h2('3.3 Placental Development & Function')
body('The placenta is fully formed by week 12 and reaches its full size (~500g) by term.')
bold_bullet('Functions', 'Nutrition, respiration (gas exchange), excretion, endocrine (hCG, oestrogen, progesterone, hPL), immunological protection (IgG transfer), barrier (partial - some drugs/viruses cross).')
bold_bullet('Placental hormones', 'hCG peaks at 8-10 weeks and is the basis of pregnancy tests. hPL (human placental lactogen) supports foetal growth and maternal metabolism.')
note_box('The placenta does NOT completely protect the foetus. Rubella, CMV, syphilis (Treponema pallidum), Toxoplasma, HIV, and many drugs (alcohol, thalidomide, warfarin) cross the placental barrier.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 4 – PHYSIOLOGICAL CHANGES IN PREGNANCY
# ══════════════════════════════════════════════════════════════════════════════
h1('4. Physiological Changes in Pregnancy')

h2('4.1 Cardiovascular System')
bullet('Cardiac output increases 40-50% (increased stroke volume + heart rate)')
bullet('Heart rate increases by 10-15 bpm above baseline')
bullet('Blood pressure DECREASES in 1st and 2nd trimester (progesterone causes vasodilation); returns to normal in 3rd trimester')
bullet('Blood volume increases by ~45% (plasma volume increases more than RBC mass = dilutional/physiological anaemia)')
bullet('Supine hypotension syndrome: gravid uterus compresses inferior vena cava in supine position - position woman in left lateral tilt')

h2('4.2 Haematological Changes')
add_table(
    ['Parameter', 'Change in Pregnancy', 'Clinical Relevance'],
    [
        ['Haemoglobin', 'Decreases (110-140 g/L is normal range)', 'Iron-deficiency anaemia is most common'],
        ['WBC', 'Increases (up to 16 x10^9/L)', 'Physiological leucocytosis; difficult to use as infection marker'],
        ['Platelets', 'Slightly decreases (~10%)', 'Watch for thrombocytopenia'],
        ['Fibrinogen', 'Increases significantly', 'Hypercoagulable state - DVT/PE risk'],
        ['Clotting factors', 'II, VII, VIII, X increase', 'Protective against haemorrhage at delivery but increases VTE risk'],
        ['Serum iron', 'Decreases', 'Iron supplementation often needed'],
    ]
)

h2('4.3 Respiratory System')
bullet('Tidal volume increases by 40% (diaphragm elevated by uterus)')
bullet('Respiratory rate minimally changes but minute ventilation increases')
bullet('PaCO2 decreases (compensated respiratory alkalosis) - facilitates CO2 transfer from foetus to mother')
bullet('Oxygen consumption increases by 20%')
bullet('Dyspnoea is common in late pregnancy - normal finding')

h2('4.4 Renal System')
bullet('GFR increases by 50% from 1st trimester (increased blood flow to kidneys)')
bullet('Serum creatinine and urea DECREASE (therefore "normal" values may mask renal disease)')
bullet('Glucosuria may occur even with normal blood glucose (reduced renal threshold) - does NOT confirm diabetes')
bullet('Ureteral dilation (progesterone effect + compression by uterus) increases UTI risk')
note_box('Normal serum creatinine in pregnancy is 44-80 µmol/L (lower than non-pregnant normal). A creatinine of 90 µmol/L may indicate renal impairment in a pregnant woman.')

h2('4.5 Gastrointestinal System')
bullet('Nausea and vomiting (morning sickness): peaks weeks 8-10; caused by hCG and oestrogen')
bullet('Hyperemesis gravidarum: severe persistent vomiting causing dehydration, ketosis, and weight loss - requires hospitalisation')
bullet('Progesterone relaxes lower oesophageal sphincter → heartburn (GORD) very common')
bullet('Gastric emptying slowed → aspiration risk under anaesthesia (RSI protocol required)')
bullet('Constipation: progesterone slows bowel motility; iron supplements worsen it')
bullet('Haemorrhoids: common due to pelvic pressure and constipation')

h2('4.6 Musculoskeletal System')
bullet('Relaxin (from corpus luteum) loosens pelvic ligaments → facilitates delivery but causes symphysis pubis dysfunction')
bullet('Centre of gravity shifts anteriorly → lumbar lordosis → low back pain very common')
bullet('Diastasis recti (separation of rectus abdominis) may occur')

h2('4.7 Skin Changes')
bullet('Linea nigra: dark midline abdominal line (hyperpigmentation from MSH/oestrogen)')
bullet('Chloasma (melasma): "mask of pregnancy" - facial hyperpigmentation')
bullet('Striae gravidarum (stretch marks): purple/red, later silvery-white')
bullet('Spider angiomata and palmar erythema: normal in pregnancy (raised oestrogen)')

h2('4.8 Endocrine Changes')
add_table(
    ['Hormone', 'Source', 'Function in Pregnancy'],
    [
        ['hCG', 'Syncytiotrophoblast', 'Maintains corpus luteum; basis of pregnancy test'],
        ['Oestrogen (oestriol)', 'Placenta (from foetal DHEAS)', 'Uterine growth, breast development, skin changes'],
        ['Progesterone', 'Corpus luteum then placenta', 'Maintains endometrium, suppresses uterine contractions, smooth muscle relaxation'],
        ['hPL', 'Placenta', 'Insulin resistance (nutrient partitioning to foetus), lipolysis'],
        ['Prolactin', 'Anterior pituitary', 'Prepares breasts for lactation'],
        ['Relaxin', 'Corpus luteum', 'Ligament relaxation, cervical ripening'],
    ]
)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 5 – ANTENATAL CARE
# ══════════════════════════════════════════════════════════════════════════════
h1('5. Antenatal Care')

h2('5.1 Goals of Antenatal Care')
bullet('Monitor maternal and foetal well-being throughout pregnancy')
bullet('Identify and manage risk factors and complications early')
bullet('Provide health education and preparation for birth and parenthood')
bullet('Promote healthy lifestyle: nutrition, exercise, smoking cessation, alcohol avoidance')

h2('5.2 Antenatal Visit Schedule (WHO Recommendations)')
add_table(
    ['Gestational Age', 'Contact', 'Key Activities'],
    [
        ['8-12 weeks', '1st visit', 'Confirm pregnancy, history, blood tests, USS dating, booking'],
        ['16 weeks', '2nd visit', 'Review blood results, blood pressure, foetal movements discussed'],
        ['20 weeks', '3rd visit', 'Anomaly scan (structural USS), review placental position'],
        ['24-26 weeks', '4th visit', 'BP, urinalysis, symphysis-fundal height (SFH) measurement'],
        ['28 weeks', '5th visit', 'GTT (if risk factors), Anti-D if Rh-negative, iron/haemoglobin check'],
        ['30-32 weeks', '6th visit', 'BP, urinalysis, SFH, foetal presentation'],
        ['34-36 weeks', '7th visit', 'Birth plan discussion, GBS screening, presentation confirmed'],
        ['38-40 weeks', '8th visit', 'Assessment for induction if post-dates, cervical assessment'],
        ['41 weeks', '9th visit', 'Offer membrane sweep; discuss induction of labour'],
    ]
)

h2('5.3 Booking Visit Assessment')
h3('History')
bullet('LMP (last menstrual period) and EDD calculation: Naegele\'s Rule = LMP + 9 months + 7 days (or LMP + 280 days)')
bullet('Obstetric history: gravidity (G), parity (P), previous complications, caesarean scars')
bullet('Medical/surgical history: diabetes, hypertension, cardiac disease, thromboembolic disease')
bullet('Family history: genetic conditions, twins, diabetes, hypertension')
bullet('Social history: domestic violence screening, substance use, housing, support network')
bullet('Medication and allergy review')

h3('Physical Examination')
bullet('Weight, height, BMI')
bullet('Blood pressure (both arms at first visit)')
bullet('Abdominal examination: fundal height, foetal lie/presentation from 28 weeks')
bullet('Breast examination (as appropriate)')

h3('Investigations at Booking')
add_table(
    ['Investigation', 'Purpose'],
    [
        ['Full blood count (FBC)', 'Baseline Hb, detect anaemia, thrombocytopenia'],
        ['Blood group & Rh factor', 'Identify Rh-negative women; antibody screen'],
        ['Rubella immune status', 'Susceptible women offered vaccination postnatally'],
        ['Syphilis serology (VDRL/RPR)', 'Screen for congenital syphilis prevention'],
        ['HIV screening', 'Prevent vertical (mother-to-child) transmission'],
        ['Hepatitis B surface antigen', 'Newborn prophylaxis if positive'],
        ['Mid-stream urine (MSU)', 'Asymptomatic bacteriuria screen; treat to prevent pyelonephritis'],
        ['Thyroid function (TSH)', 'Hypothyroidism common; untreated causes developmental problems'],
        ['Haemoglobin electrophoresis', 'Screen for sickle cell, thalassaemia in high-risk populations'],
        ['First trimester combined screening', 'PAPP-A + free beta-hCG + nuchal translucency (11-13+6 wks) for Trisomy 21, 18, 13'],
        ['Random blood glucose / HbA1c', 'Screen for pre-existing diabetes'],
    ]
)

h2('5.4 Symphysis-Fundal Height (SFH)')
body('SFH is measured in centimetres from the pubic symphysis to the fundus of the uterus. It broadly correlates with gestational age (in weeks) after 20 weeks.')
add_table(
    ['Gestational Age', 'Expected Fundal Height / Landmark'],
    [
        ['12 weeks', 'Just above pubic symphysis'],
        ['16 weeks', 'Midway between symphysis and umbilicus'],
        ['20 weeks', 'At umbilicus (~20 cm SFH)'],
        ['28 weeks', '~28 cm (2-3 cm above umbilicus)'],
        ['36 weeks', 'At xiphisternum (~36 cm)'],
        ['40 weeks', 'Slightly lower (engagement drops fundal height)'],
    ]
)
note_box('SFH should be plotted on a customised growth chart. SFH more than 3 cm below or above expected triggers USS referral for foetal growth assessment (IUGR or macrosomia).')

h2('5.5 Foetal Lie, Presentation, Position, Engagement')
bold_bullet('Lie', 'Relationship of long axis of foetus to long axis of uterus: Longitudinal, Transverse, Oblique.')
bold_bullet('Presentation', 'Part of the foetus that overlies the pelvic brim: Cephalic (vertex most common), Breech, Shoulder, Face, Brow.')
bold_bullet('Position', 'Relationship of the denominator (occiput in vertex) to the maternal pelvis: OA (occiput anterior) is optimal; OP (posterior) causes prolonged labour.')
bold_bullet('Engagement', 'When the widest diameter of the presenting part has passed through the pelvic brim. Expressed in fifths palpable abdominally: 2/5 or less = engaged.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 6 – FOETAL DEVELOPMENT & MONITORING
# ══════════════════════════════════════════════════════════════════════════════
h1('6. Foetal Development & Monitoring')

h2('6.1 Embryonic & Foetal Development by Trimester')
add_table(
    ['Period', 'Weeks', 'Key Milestones'],
    [
        ['Embryonic', '1-8', 'Organogenesis; most vulnerable to teratogens; neural tube closes at week 4; heart beats by week 6'],
        ['Early foetal', '9-12', 'All organs formed; fingers/toes visible; external genitalia differentiate; foetus ~9 cm, 45g'],
        ['2nd trimester', '13-27', 'Foetal movements (quickening) felt by mother ~18-20 weeks; viability threshold ~22-24 wks; lanugo and vernix caseosa appear'],
        ['3rd trimester', '28-40', 'Rapid weight gain (brown fat laid down); surfactant production (matures ~35 wks); foetus ~50 cm, ~3400g at term'],
    ]
)

h2('6.2 Amniotic Fluid')
bullet('Produced by foetal kidneys (mainly) and lung fluid from ~16 weeks')
bullet('Normal volume: 500-1500 mL at term; AFI 8-25 cm (amniotic fluid index)')
bold_bullet('Oligohydramnios (AFI < 5 cm)', 'Causes: foetal renal agenesis (Potter sequence), IUGR, post-dates, PPROM. Risk: cord compression, foetal deformity.')
bold_bullet('Polyhydramnios (AFI > 25 cm)', 'Causes: foetal anomalies (GI atresia, NTDs, anencephaly), macrosomia, GDM, idiopathic. Risk: preterm labour, cord prolapse, malpresentation.')

h2('6.3 Cardiotocography (CTG)')
body('CTG (electronic foetal monitoring) records foetal heart rate (FHR) and uterine contractions simultaneously.')
h3('Baseline FHR Parameters (NICE Classification)')
add_table(
    ['Feature', 'Normal (Reassuring)', 'Non-Reassuring', 'Abnormal'],
    [
        ['Baseline FHR', '110-160 bpm', '100-109 or 161-180 bpm', '<100 or >180 bpm'],
        ['Baseline variability', '5-25 bpm', '3-4 bpm for ≥40 min', '<3 bpm for >30 min'],
        ['Accelerations', 'Present (≥2 in 20 min)', 'Absence (if non-reassuring)', 'N/A'],
        ['Decelerations', 'None / early', 'Variable / single prolonged', 'Late / atypical variable / >3 min prolonged'],
    ]
)
note_box('Early decelerations (mirror contractions) = head compression = NORMAL. Late decelerations (start after peak of contraction, slow return) = uteroplacental insufficiency = CONCERNING. Variable decelerations = cord compression.')

h2('6.4 Foetal Movement Monitoring')
bullet('Mother should perceive ≥10 movements in 12 hours (Cardiff count-to-10 method)')
bullet('Reduced foetal movements (RFM) must be assessed urgently - CTG minimum; USS if needed')
bullet('Absence of foetal movements for >2 hours should prompt immediate review')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 7 – NORMAL LABOUR & DELIVERY
# ══════════════════════════════════════════════════════════════════════════════
h1('7. Normal Labour & Delivery')

h2('7.1 Definition & Onset of Labour')
body('Labour is defined as the process of progressive cervical dilation and effacement, driven by regular uterine contractions, leading to the birth of the baby and expulsion of the placenta.')
bullet('Onset: spontaneous at 37-42 weeks (term pregnancy)')
bullet('Prodromal (latent) labour: irregular contractions; cervix effacing but not yet in active labour')

h2('7.2 Premonitory Signs of Labour')
bullet('Lightening: descent of presenting part into pelvis (engagement) - 2-4 weeks before labour in primigravidas')
bullet('Braxton Hicks contractions: irregular, painless, "practice" contractions')
bullet('Cervical show: blood-stained mucus plug expulsion')
bullet('Rupture of membranes (ROM): gush or trickle of amniotic fluid')
bullet('Nesting instinct and low backache')

h2('7.3 The Three Stages of Labour')
h3('First Stage: Cervical Dilation')
add_table(
    ['Phase', 'Cervical Dilation', 'Features', 'Duration'],
    [
        ['Latent phase', '0-3 cm', 'Irregular contractions becoming regular; cervix effacing; may last many hours', 'Primi: up to 20 hours; Multi: up to 14 hours'],
        ['Active phase', '4-10 cm', 'Regular contractions q2-3 min, lasting 45-60 sec; expected progress ≥0.5 cm/hour', 'Primi: average 8 hours; Multi: average 5 hours'],
        ['Transition', '8-10 cm', 'Most intense contractions; urge to push may begin; complete dilation at 10 cm', 'Usually 15-60 minutes'],
    ]
)

h3('Second Stage: Expulsion of Foetus')
bullet('From full cervical dilation (10 cm) to delivery of the baby')
bullet('Active pushing begins when presenting part is low and maternal urge to push is present')
bullet('Duration: Primi: up to 3 hours (with epidural); Multi: up to 2 hours')
bullet('The 7 cardinal movements of labour (in vertex presentation): Engagement, Descent, Flexion, Internal rotation, Extension (delivery of head), External rotation (restitution), Expulsion (delivery of shoulders and body)')
note_box('The foetal head undergoes FLEXION first (chin to chest), which presents the smallest diameter (suboccipitobregmatic ~9.5 cm) to the pelvis.')

h3('Third Stage: Delivery of Placenta')
bullet('From delivery of baby to complete delivery of placenta and membranes')
bullet('Duration: Active management - within 30 minutes; Physiological management - up to 60 minutes')
bullet('Signs of placental separation: uterus becomes globular and rises, umbilical cord lengthens, gush of blood, uterus becomes firmer')

h2('7.4 Partograph')
body('The partograph is a graphical record of labour progress used in all hospital deliveries. It records:')
bullet('Foetal heart rate (every 30 minutes in active labour)')
bullet('Amniotic fluid (colour and presence; membranes intact/ruptured/absent)')
bullet('Cervical dilation plotted against time (alert and action lines)')
bullet('Descent of presenting part (in fifths palpable abdominally)')
bullet('Contractions (frequency, duration, strength)')
bullet('Maternal vital signs (BP, pulse, temperature, urine output)')
note_box('Alert line: expected progress of 1 cm/hour from 4 cm. Action line: 4 hours to the right of alert line. Crossing the action line indicates need for medical review and possible intervention.')

h2('7.5 Pain Relief in Labour')
add_table(
    ['Method', 'Type', 'Notes'],
    [
        ['TENS (transcutaneous electrical nerve stimulation)', 'Non-pharmacological', 'Safe; most effective in early labour'],
        ['Water (hydrotherapy)', 'Non-pharmacological', 'Warm bath/birth pool; reduces pain perception'],
        ['Entonox (50% N2O + 50% O2)', 'Pharmacological - inhaled', 'Self-administered; provides rapid short-duration analgesia; causes dizziness/nausea'],
        ['Pethidine (meperidine)', 'Pharmacological - opioid IM', 'Causes maternal sedation and neonatal respiratory depression; Naloxone reversal'],
        ['Epidural analgesia', 'Regional block', 'Most effective; may slow labour; may cause hypotension; requires IV access, CTG monitoring'],
        ['Spinal block', 'Regional block', 'Used for caesarean section; rapid onset; single dose'],
    ]
)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 8 – MANAGEMENT OF THE THIRD STAGE
# ══════════════════════════════════════════════════════════════════════════════
h1('8. Management of the Third Stage of Labour')

h2('8.1 Active vs Physiological Management')
add_table(
    ['', 'Active Management', 'Physiological Management'],
    [
        ['Definition', 'Uterotonic + CCT + fundal massage', 'Awaiting spontaneous placental expulsion without uterotonic'],
        ['Uterotonic', 'Oxytocin 10 IU IM (or IV) within 1 min of birth', 'None given routinely'],
        ['Cord clamping', 'Delayed at least 60 seconds post-delivery', 'Cord not clamped until pulsation stops'],
        ['Cord traction', 'Controlled cord traction (CCT) after signs of separation', 'No traction; mother delivers placenta with pushing'],
        ['Duration', 'Placenta within 30 minutes', 'Up to 60 minutes'],
        ['PPH risk', 'Reduces risk by ~60%', 'Higher risk of PPH'],
        ['Recommendation', 'WHO/NICE recommended for all women', 'May be chosen by low-risk women'],
    ]
)

h2('8.2 Examination of the Placenta')
bullet('Weight: term placenta ~500-600g, ~1/6th of foetal weight')
bullet('Maternal surface: cotyledons (15-30); should be complete; deep red; examine for missing pieces (retained placenta risk)')
bullet('Foetal surface: smooth, shiny, greyish-blue; membranes should be complete')
bullet('Umbilical cord: ~50 cm long; normally contains 2 arteries + 1 vein (mnemonic: AVA = artery vein artery / 2 arteries 1 vein)')
note_box('A single umbilical artery (2-vessel cord) is associated with foetal renal and cardiac anomalies. Document all findings and report to medical staff.')

h2('8.3 Perineal Repair')
add_table(
    ['Degree', 'Structures Involved', 'Management'],
    [
        ['1st degree', 'Skin and superficial perineal muscles only', 'May not need suturing; observe'],
        ['2nd degree', 'Perineal muscles involved (not external anal sphincter)', 'Suture with absorbable material (e.g., Vicryl Rapide)'],
        ['3rd degree', 'External anal sphincter (EAS) partially/fully involved', 'Surgical repair; broad-spectrum antibiotics; laxatives'],
        ['4th degree', 'EAS + internal anal sphincter + rectal mucosa', 'Surgical repair in theatre; specialist referral'],
    ]
)
body('Episiotomy: surgical incision of perineum (mediolateral preferred); used to expedite delivery or prevent severe tearing; requires anaesthesia and repair.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 9 – POSTNATAL CARE
# ══════════════════════════════════════════════════════════════════════════════
h1('9. Postnatal (Postpartum) Care')

h2('9.1 Definitions')
bold_bullet('Puerperium', 'The period from delivery until 6 weeks postpartum during which the reproductive organs return to their pre-pregnant state (involution).')
bold_bullet('Involution', 'Process of the uterus returning to pre-pregnant size. Fundus should descend 1-2 cm/day from umbilicus level (at day 1) to pelvic organ by day 10-14.')

h2('9.2 Immediate (First 2 Hours) Postpartum Assessment')
bullet('Vital signs every 15 minutes for first hour, then every 30 minutes')
bullet('Uterine fundal height and tone (massage if boggy = atony)')
bullet('Lochia: amount, colour, odour')
bullet('Perineum: intact, suture lines, haematoma')
bullet('Bladder: encourage voiding within 4-6 hours; retention is common')
bullet('Pain assessment and management')
bullet('Bonding and skin-to-skin contact facilitation')
bullet('Initiation of breastfeeding within 1 hour of birth')

h2('9.3 Lochia')
add_table(
    ['Stage', 'Timing', 'Colour', 'Composition'],
    [
        ['Lochia rubra', 'Days 1-3', 'Red (bloody)', 'Blood, decidua, trophoblastic debris'],
        ['Lochia serosa', 'Days 4-10', 'Pink/brown', 'Serum, leukocytes, wound exudate'],
        ['Lochia alba', 'Day 10 to 4-6 weeks', 'White/yellowish', 'Leukocytes, decidua, epithelial cells'],
    ]
)
note_box('Heavy bright red bleeding after day 3, offensive odour, or prolonged lochia suggests retained products or infection. Escalate immediately.')

h2('9.4 Postpartum Observations (6 weeks)')
bullet('Day 1-2: BUBBLE-HE assessment: Breasts, Uterus, Bladder, Bowels, Lochia, Episiotomy/perineum, Homans sign (DVT), Emotional status')
bullet('Weight: return to pre-pregnancy weight average 6-12 months')
bullet('Blood pressure: hypertension may persist or develop in the first few days')
bullet('Depression screening: Edinburgh Postnatal Depression Scale (EPDS) at 2-6 weeks')

h2('9.5 Postpartum Blues vs Depression vs Psychosis')
add_table(
    ['Condition', 'Timing', 'Features', 'Management'],
    [
        ['Baby Blues', 'Days 3-5', 'Tearfulness, labile mood, anxiety; self-limiting', 'Reassurance, support; resolves by day 10'],
        ['Postnatal Depression (PND)', '2 weeks to 12 months', 'Low mood, anhedonia, poor bonding, sleep disturbance beyond new-parent norm', 'EPDS screen; counselling; antidepressants (SSRIs - sertraline preferred as minimal breast milk transfer)'],
        ['Postpartum Psychosis', 'Within 2-4 weeks', 'Hallucinations, delusions, confusion, severe mood swings; EMERGENCY', 'Urgent psychiatric admission; may need separation from baby for safety'],
    ]
)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 10 – NEONATAL CARE & ASSESSMENT
# ══════════════════════════════════════════════════════════════════════════════
h1('10. Neonatal Care & Assessment')

h2('10.1 Immediate Newborn Care (Transition)')
numbered('Dry and stimulate: dry with warm towel, stimulate by rubbing back and soles of feet')
numbered('Assess: breathing (should start within 30 seconds), colour, tone, heart rate')
numbered('Clamp and cut cord: delayed cord clamping (≥1 minute) recommended to increase iron stores')
numbered('Skin-to-skin: place baby on mother\'s chest; promotes bonding, thermoregulation, breastfeeding initiation')
numbered('Vitamin K: 1 mg IM at birth (or oral); prevents Haemorrhagic Disease of the Newborn (HDN)')
numbered('Identify: attach ID bands; document time of birth, sex, birth weight')

h2('10.2 APGAR Score')
body('Assessed at 1 minute and 5 minutes of life. Each of 5 parameters scored 0-2.')
add_table(
    ['Sign', '0', '1', '2'],
    [
        ['Appearance (skin colour)', 'Blue/pale all over', 'Blue extremities, pink body', 'Completely pink'],
        ['Pulse (heart rate)', 'Absent', '<100 bpm', '≥100 bpm'],
        ['Grimace (reflex irritability)', 'No response', 'Grimace', 'Cry / cough / sneeze'],
        ['Activity (muscle tone)', 'Limp', 'Some flexion', 'Active motion'],
        ['Respiration', 'Absent', 'Weak, irregular', 'Strong cry'],
    ]
)
body('Total score 0-10:')
bullet('7-10 = Normal; reassess at 5 min and 10 min if initial concerns')
bullet('4-6 = Moderate depression; stimulate, give O2, consider resuscitation')
bullet('0-3 = Severe depression; immediate resuscitation (ABCD: Airway, Breathing, Circulation, Drugs)')

h2('10.3 Normal Newborn Vital Signs & Parameters')
add_table(
    ['Parameter', 'Normal Range'],
    [
        ['Birth weight', '2,500 - 4,000 g (term)'],
        ['Length', '48-52 cm'],
        ['Head circumference', '33-37 cm'],
        ['Heart rate', '120-160 bpm'],
        ['Respiratory rate', '40-60 breaths/minute'],
        ['Temperature (axillary)', '36.5 - 37.5 °C'],
        ['Blood glucose', '>2.6 mmol/L (screen if risk factors)'],
        ['Expected weight loss', 'Up to 10% in first 3-5 days; regained by day 10-14'],
    ]
)

h2('10.4 Neonatal Reflexes')
add_table(
    ['Reflex', 'How to Elicit', 'Normal Response', 'Disappears'],
    [
        ['Rooting', 'Stroke cheek', 'Turns head towards stimulus, opens mouth', '3-4 months'],
        ['Sucking', 'Place finger/nipple in mouth', 'Rhythmic sucking', '4 months (voluntary)'],
        ['Moro (startle)', 'Sudden movement / head drop', 'Arms abduct and extend, then embrace', '3-6 months'],
        ['Grasp (palmar)', 'Place finger in palm', 'Fingers curl around object', '3-6 months'],
        ['Babinski', 'Stroke lateral sole foot', 'Big toe extends upward, fan other toes', '1-2 years'],
        ['Stepping', 'Hold upright, feet touch surface', 'Stepping movements', '2-3 months'],
    ]
)
note_box('Absent or asymmetric Moro reflex may indicate brachial plexus injury (Erb\'s palsy), clavicle fracture, or CNS problem. Asymmetric grasp may indicate hemiplegia or brachial plexus injury.')

h2('10.5 Neonatal Jaundice (Icterus Neonatorum)')
bold_bullet('Physiological jaundice', 'Appears day 2-3, peaks day 4-5, resolves by day 10-14. Due to haemolysis of foetal Hb + immature hepatic conjugation.')
bold_bullet('Pathological jaundice', 'Appears within first 24 hours = ALWAYS pathological; or persists beyond 14 days. Causes: haemolytic disease (ABO/Rh incompatibility), G6PD deficiency, infection, biliary atresia.')
body('Management: phototherapy (blue-green light 430-490 nm wavelength) is first-line. Exchange transfusion for severe cases.')
note_box('Jaundice within 24 hours of life is always pathological until proven otherwise. Immediate investigation (Coombs test, bilirubin levels, blood group) and escalation required.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 11 – BREASTFEEDING
# ══════════════════════════════════════════════════════════════════════════════
h1('11. Breastfeeding & Infant Nutrition')

h2('11.1 WHO Recommendations')
bullet('Exclusive breastfeeding for the first 6 months of life')
bullet('Continued breastfeeding alongside complementary foods until 2 years and beyond')

h2('11.2 Physiology of Lactation')
bold_bullet('Prolactin', 'Produced by anterior pituitary; stimulated by infant suckling; drives milk production (galactopoiesis).')
bold_bullet('Oxytocin', 'Released from posterior pituitary in response to suckling (let-down reflex); causes myoepithelial cell contraction and milk ejection.')
bold_bullet('Colostrum', 'First milk (days 1-3); thick, yellowish; high in immunoglobulins (IgA), lactoferrin, growth factors, protein. Promotes gut colonisation and immune protection.')
bold_bullet('Transitional milk', 'Days 3-14; increasing volume, decreasing protein and IgA.')
bold_bullet('Mature milk', 'After 2 weeks; foremilk (watery, quenches thirst) followed by hindmilk (high fat, promotes satiety and growth).')

h2('11.3 Benefits of Breastfeeding')
h3('For Baby')
bullet('Reduces risk of: SIDS, gastroenteritis, respiratory infections, otitis media, necrotising enterocolitis (NEC), obesity, type 2 diabetes, allergies')
bullet('Optimal nutrition matched to infant developmental needs')
bullet('Promotes bonding and cognitive development')
h3('For Mother')
bullet('Reduces postpartum haemorrhage risk (oxytocin effect)')
bullet('Promotes uterine involution')
bullet('Reduces risk of breast and ovarian cancer')
bullet('Delays return of ovulation (LAM method) - not reliable contraception')
bullet('Promotes weight loss')

h2('11.4 Correct Latch Assessment')
body('LATCH score: Latch, Audible swallowing, Type of nipple, Comfort, Hold. Each 0-2, max 10.')
bullet('Infant\'s mouth wide open (140-degree angle)')
bullet('Lower lip flanged outward')
bullet('Chin touching breast; most of areola visible above upper lip')
bullet('Audible swallowing; no nipple pain after initial latch')
bullet('Cheeks rounded (not sunken)')

h2('11.5 Common Breastfeeding Problems')
add_table(
    ['Problem', 'Cause', 'Management'],
    [
        ['Sore/cracked nipples', 'Poor latch', 'Correct latch; nipple cream; air dry nipples; lanolin'],
        ['Engorgement', 'Milk buildup; poor drainage', 'Frequent feeding; warm compress before; cold compress after; hand express to soften areola'],
        ['Mastitis', 'Blocked duct + infection (Staph aureus)', 'Continue breastfeeding; flucloxacillin 500 mg QID 10 days; warm compress; analgesia'],
        ['Breast abscess', 'Untreated mastitis', 'I&D or needle aspiration + antibiotics; may need to temporarily cease feeding from affected breast'],
        ['Insufficient milk', 'Poor latch/positioning, infrequent feeding', 'Increase feeding frequency; improve latch; skin-to-skin; review formula supplementation only if indicated'],
        ['Thrush (Candida)', 'C. albicans on nipples/infant mouth', 'Miconazole/nystatin for baby\'s mouth and mother\'s nipples simultaneously'],
    ]
)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 12 – OBSTETRIC COMPLICATIONS & EMERGENCIES
# ══════════════════════════════════════════════════════════════════════════════
h1('12. Obstetric Complications & Emergencies')

h2('12.1 Hypertensive Disorders of Pregnancy')
add_table(
    ['Condition', 'Definition', 'Key Features', 'Management'],
    [
        ['Gestational HTN', 'BP ≥140/90 after 20 weeks; NO proteinuria; NO systemic features', 'New-onset HTN; monitor closely', 'Antihypertensives (labetalol, nifedipine, methyldopa); monitoring'],
        ['Pre-eclampsia (PE)', 'BP ≥140/90 after 20 wks + proteinuria ≥0.3g/24h OR organ dysfunction', 'Headache, visual disturbance, epigastric pain, oedema', 'MgSO4 (seizure prophylaxis); antihypertensives; delivery is cure'],
        ['Eclampsia', 'Seizures in pre-eclamptic patient (or post-delivery)', 'Tonic-clonic seizures; can occur ante/intra/postpartum', 'MgSO4 IV loading dose 4g; maintain airway; deliver baby'],
        ['HELLP Syndrome', 'Haemolysis + Elevated Liver enzymes + Low Platelets', 'RUQ pain, malaise, thrombocytopenia', 'Urgent delivery; steroids if <34 weeks; platelet transfusion if <50'],
        ['Chronic HTN', 'BP ≥140/90 before 20 weeks or pre-existing', 'May superimpose PE', 'Antihypertensives; low-dose aspirin from 12 wks'],
    ]
)
note_box('Give LOW-DOSE ASPIRIN (75-150 mg/day from 12 weeks) to ALL women with high risk factors for pre-eclampsia (previous PE, CKD, diabetes, autoimmune disease, chronic HTN, multifetal gestation).')

h2('12.2 Antepartum Haemorrhage (APH)')
body('APH is bleeding from the genital tract after 20 weeks gestation and before delivery of the baby.')
bold_bullet('Placenta Praevia', 'Placenta lying partially or completely over internal os. Painless, bright red PV bleeding (no uterine tenderness). Confirmed by USS. Management: no vaginal examination; bed rest; steroids if <34 wks; planned caesarean section at 36-37 weeks for major praevia.')
bold_bullet('Placental Abruption', 'Premature separation of normally sited placenta. Painful, dark red bleeding (may be concealed). Hard, board-like uterus. Foetal distress. Management: IV access, FBC, crossmatch, Kleihauer test; urgent delivery; manage DIC if present.')
bold_bullet('Vasa Praevia', 'Foetal blood vessels crossing the internal os (extremely rare). Sudden painless haemorrhage at membrane rupture. High foetal mortality. Management: elective caesarean at 35-36 weeks.')

h2('12.3 Postpartum Haemorrhage (PPH)')
body('PPH = blood loss ≥500 mL after vaginal delivery or ≥1000 mL after caesarean section within 24 hours.')
h3('The 4 T\'s of PPH Causes')
add_table(
    ['T', 'Cause', 'Frequency', 'Management'],
    [
        ['Tone', 'Uterine atony (most common ~80%)', '80%', 'Uterine massage, oxytocin, ergometrine, carboprost, misoprostol, balloon tamponade, B-Lynch suture, hysterectomy'],
        ['Tissue', 'Retained placenta or clots', '10%', 'Manual removal of placenta (MROP); uterine exploration; curettage'],
        ['Trauma', 'Cervical/vaginal/perineal lacerations, uterine rupture', '7%', 'Surgical repair; compression sutures'],
        ['Thrombin', 'Coagulopathy (DIC, thrombocytopenia)', '3%', 'FFP, cryoprecipitate, platelets, tranexamic acid'],
    ]
)
note_box('HAEMOSTASIS mnemonic for PPH management: H-call for Help, A-Assess/Resuscitate, E-Establish IV access x2/FBC/crossmatch, M-Massage uterus, O-Oxytocin 10 IU IV, S-Second-line uteronic (ergometrine/carboprost), T-Tamponade, A-Apply compression sutures, S-Systemic embolisation, I-Interventional radiology, S-Subtotal hysterectomy.')

h2('12.4 Pre-term Labour (PTL)')
bullet('Definition: labour before 37+0 weeks gestation')
bullet('Causes: infection/chorioamnionitis, PPROM, cervical incompetence, uterine anomaly, multiple pregnancy, smoking, previous PTL')
bold_bullet('Investigations', 'Foetal fibronectin (fFN) swab, transvaginal USS of cervical length (<25 mm = high risk), MSU, HVS, FBC, CRP')
bold_bullet('Management', 'Tocolysis (nifedipine or atosiban <34 weeks); Corticosteroids (betamethasone 12 mg IM x2 doses 24 hours apart <34+6 wks for lung maturity); MgSO4 for foetal neuroprotection if <32 weeks; GBS prophylaxis (benzylpenicillin if positive swab)')

h2('12.5 Premature Rupture of Membranes (PROM / PPROM)')
bold_bullet('PROM', 'Membrane rupture at term (≥37 wks) before onset of labour. Offer induction within 24 hours if no spontaneous labour (infection risk).')
bold_bullet('PPROM', 'Membrane rupture before 37 weeks. High risk of infection (chorioamnionitis), cord prolapse, prematurity. Management: admission; swabs; antibiotics (erythromycin 250 mg QID x10 days); corticosteroids if <34 weeks; expectant management until ~34 weeks unless infection or foetal compromise.')

h2('12.6 Cord Prolapse')
body('Umbilical cord descends through cervix ahead of or alongside presenting part after membrane rupture. Medical emergency - foetal hypoxia from cord compression.')
bullet('Risk factors: malpresentation (breech, transverse), polyhydramnios, multiparity, unengaged presenting part, artificial ROM with high head, prematurity')
bold_bullet('Management (ABCDE)', 'A - Alert team immediately; B - Call for help/emergency bell; C - Cord: manually elevate presenting part off cord with gloved hand; D - Position: knee-chest or exaggerated Sims position; E - Emergency caesarean section. Do NOT attempt to replace cord into uterus.')

h2('12.7 Shoulder Dystocia')
body('Impaction of foetal anterior shoulder behind maternal pubic symphysis after delivery of the foetal head. Obstetric emergency.')
bullet('Risk factors: macrosomia (>4 kg), GDM, prolonged 2nd stage, instrumental delivery, previous shoulder dystocia')
h3('HELPERR Mnemonic')
bullet('H - Call for Help')
bullet('E - Evaluate for Episiotomy (only if access needed)')
bullet('L - Legs (McRoberts manoeuvre: hyperflexion of maternal thighs onto abdomen)')
bullet('P - Suprapubic Pressure (Rubin II: firm downward pressure on foetal anterior shoulder)')
bullet('E - Enter (internal rotational manoeuvres: Rubin II, Woods screw, Reverse Woods)')
bullet('R - Remove the posterior arm (deliver posterior arm to reduce diameter)')
bullet('R - Roll the patient (Gaskin all-fours manoeuvre)')
note_box('McRoberts + suprapubic pressure resolves ~90% of shoulder dystocia cases. Document carefully - exact time of head-to-body delivery interval.')

h2('12.8 Gestational Diabetes Mellitus (GDM)')
bold_bullet('Definition', 'Glucose intolerance first detected or first onset during pregnancy.')
bold_bullet('Screening', 'OGTT (75g oral glucose tolerance test) at 24-28 weeks for moderate-risk; earlier for high-risk. Diagnosis: fasting ≥5.1 mmol/L or 1-hour ≥10 mmol/L or 2-hour ≥8.5 mmol/L (IADPSG criteria).')
bold_bullet('Maternal risks', 'PE, UTI, caesarean section, type 2 DM later (50% within 10 years).')
bold_bullet('Foetal/neonatal risks', 'Macrosomia, shoulder dystocia, stillbirth, hypoglycaemia, respiratory distress, polycythaemia, jaundice.')
bold_bullet('Management', 'Medical nutrition therapy first; metformin or insulin if targets not met (fasting <5.3, 1-hr <7.8, 2-hr <6.4 mmol/L). Monitor foetal growth. Deliver at 38-39 weeks.')

h2('12.9 Ectopic Pregnancy')
body('Implantation of embryo outside the uterine cavity. 95% in fallopian tube (ampulla most common).')
bullet('Risk factors: previous ectopic, PID/salpingitis, tubal surgery, IUD in situ, IVF, smoking')
bullet('Symptoms: amenorrhoea, unilateral pelvic pain, vaginal bleeding (subacute); severe pain + haemodynamic collapse (rupture = SURGICAL EMERGENCY)')
bullet('Diagnosis: serum hCG (rising but below expected levels) + transvaginal USS (no intrauterine sac, adnexal mass, free fluid)')
bold_bullet('Management', 'Expectant (if hCG <1000, asymptomatic, small mass), methotrexate IM (if hCG <5000, no rupture, no cardiac activity), surgical (laparoscopic salpingectomy/salpingotomy - preferred, or open if unstable).')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 13 – PHARMACOLOGY IN MIDWIFERY
# ══════════════════════════════════════════════════════════════════════════════
h1('13. Pharmacology in Midwifery')

h2('13.1 Routine Medications in Pregnancy')
add_table(
    ['Drug', 'Indication', 'Dose', 'Notes'],
    [
        ['Folic acid', 'Neural tube defect prevention', '400 mcg/day preconception to 12 wks; 5 mg/day if high risk', 'Begin before conception if planned'],
        ['Iron (ferrous sulfate)', 'Iron-deficiency anaemia', '200 mg TDS', 'Take with Vit C; constipation side effect; avoid with antacids'],
        ['Calcium + Vitamin D', 'Bone health; pre-eclampsia prevention', '1-1.5 g Ca/day + 400 IU Vit D', 'Especially in at-risk populations'],
        ['Low-dose aspirin', 'Pre-eclampsia prevention', '75-150 mg/day from 12 weeks', 'High-risk women only; stop at 36 weeks'],
        ['Anti-D immunoglobulin', 'Rh sensitisation prevention', '500 IU IM at 28 wks and again postnatally (within 72h)', 'All Rh-negative women; after any sensitising event'],
    ]
)

h2('13.2 Uterotonics (Labour & PPH)')
add_table(
    ['Drug', 'Class', 'Dose/Route', 'Indication', 'Side Effects'],
    [
        ['Oxytocin (Syntocinon)', 'Oxytocin agonist', '10 IU IM or IV bolus; or 5-20 IU in 500 mL infusion', 'Induction of labour; active 3rd stage management; PPH treatment', 'Hypotension (rapid IV), water retention (high dose), uterine hyperstimulation'],
        ['Ergometrine', 'Ergot alkaloid', '500 mcg IM (or Syntometrine = oxytocin 5 IU + ergometrine 500 mcg)', 'Active 3rd stage; PPH 2nd line', 'Contraindicated in hypertension; nausea/vomiting; vasoconstriction'],
        ['Misoprostol', 'PGE1 analogue', '600-800 mcg oral/sublingual/rectal', 'PPH (WHO essential medicine); cervical ripening', 'Pyrexia, shivering, GI disturbance'],
        ['Carboprost (Hemabate)', 'PGF2-alpha analogue', '250 mcg IM q15 min (max 8 doses = 2 mg)', 'PPH refractory to oxytocin/ergometrine', 'Contraindicated in asthma; diarrhoea, flushing, bronchospasm'],
        ['Tranexamic acid', 'Antifibrinolytic', '1 g IV within 3 hours of delivery', 'PPH adjunct (WOMAN trial)', 'Thrombotic risk; nausea'],
    ]
)

h2('13.3 Tocolytics (Suppress Preterm Labour)')
add_table(
    ['Drug', 'Class', 'Dose', 'Notes'],
    [
        ['Nifedipine', 'Calcium channel blocker', '20 mg oral loading; 10-20 mg TDS', 'First-line; headache, flushing, palpitations'],
        ['Atosiban (Tractocile)', 'Oxytocin receptor antagonist', 'IV infusion protocol', 'Fewer side effects; expensive; first-line in Europe'],
        ['Indomethacin', 'NSAID (COX inhibitor)', 'Oral/rectal', '<32 weeks only; risk of premature ductus arteriosus closure'],
    ]
)

h2('13.4 Magnesium Sulphate (MgSO4)')
bold_bullet('Indications', 'Eclampsia treatment and prevention; foetal neuroprotection in preterm labour <32 weeks.')
bold_bullet('Loading dose', '4 g IV over 5-10 minutes; maintenance 1-2 g/hour infusion.')
bold_bullet('Monitoring', 'Hourly urine output (>25 mL/hr), respiratory rate (>12/min), patellar reflexes (must be present), serum Mg levels (therapeutic 2-3.5 mmol/L).')
bold_bullet('Toxicity signs', 'Loss of patellar reflexes (first sign), respiratory depression, cardiac arrest.')
bold_bullet('Antidote', 'Calcium gluconate 1 g (10 mL of 10%) IV slowly.')

h2('13.5 Drugs to AVOID in Pregnancy')
add_table(
    ['Drug', 'Risk'],
    [
        ['Warfarin (esp. 1st trimester)', 'Warfarin embryopathy; foetal haemorrhage; use LMWH instead'],
        ['ACE inhibitors / ARBs', 'Foetal renal agenesis, oligohydramnios, skull ossification defect'],
        ['NSAIDs (3rd trimester)', 'Premature ductus arteriosus closure, oligohydramnios'],
        ['Tetracyclines', 'Tooth discolouration and bone growth inhibition in foetus'],
        ['Aminoglycosides (Gentamicin)', 'Foetal ototoxicity (8th nerve damage)'],
        ['Methotrexate', 'Teratogen; foetal death; used to treat ectopic pregnancy postconception'],
        ['Thalidomide', 'Classic teratogen: phocomelia (limb reduction defects)'],
        ['Alcohol', 'Foetal Alcohol Spectrum Disorder (FASD); no safe level'],
        ['Isotretinoin (Roaccutane)', 'Severe teratogen: craniofacial, cardiac, CNS malformations'],
        ['Lithium', 'Ebstein\'s anomaly (tricuspid valve malformation)'],
    ]
)

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 14 – INFECTION CONTROL & ASEPSIS
# ══════════════════════════════════════════════════════════════════════════════
h1('14. Infection Control & Asepsis in Midwifery')

h2('14.1 Standard Precautions')
bullet('Hand hygiene: WHO 5 Moments (before patient contact, before aseptic procedure, after body fluid exposure, after patient contact, after contact with patient surroundings)')
bullet('PPE: gloves, apron, eye protection, surgical mask as appropriate')
bullet('Safe sharps disposal: never re-sheath; sharps bin at point of care')
bullet('Sterile technique for: catheterisation, IV insertion, perineal repair, invasive procedures')

h2('14.2 TORCH Infections in Pregnancy')
add_table(
    ['Organism', 'Maternal Symptoms', 'Foetal/Neonatal Effects', 'Management'],
    [
        ['T - Toxoplasma gondii', 'Usually asymptomatic; flu-like', 'Hydrocephalus, chorioretinitis, intracranial calcifications', 'Avoid cat litter/undercooked meat; spiramycin or pyrimethamine-sulfa treatment'],
        ['O - Other (Syphilis, HBV, HIV, Zika, Listeria)', 'Variable', 'Variable - see specific sections', 'Specific treatments - see antenatal screening'],
        ['R - Rubella', 'Rash, lymphadenopathy', 'CRS: cataracts, deafness, cardiac defects (PDA, pulmonary stenosis), microcephaly', 'No treatment; MMR vaccination prevents; avoid contact in 1st trimester'],
        ['C - CMV (Cytomegalovirus)', 'Often asymptomatic', 'Most common congenital infection; hearing loss, microcephaly, periventricular calcifications', 'Ganciclovir/valganciclovir in severe neonatal disease'],
        ['H - Herpes Simplex', 'Painful vesicles (primary)', 'Neonatal herpes (encephalitis, disseminated) especially if primary infection at delivery', 'Aciclovir; caesarean if active lesions at onset of labour'],
    ]
)

h2('14.3 Group B Streptococcus (GBS)')
bullet('Leading cause of early-onset neonatal sepsis in developed countries')
bullet('~25% of women colonised in genital/rectal tract')
bullet('Vertical transmission at birth causes neonatal pneumonia, sepsis, meningitis')
bullet('Screening: rectovaginal swab at 35-37 weeks (some countries universal screen; others risk-factor-based)')
bold_bullet('Intrapartum antibiotics (IAP)', 'Benzylpenicillin IV 3 g loading then 1.5 g IV q4h in labour. Clindamycin if penicillin allergy.')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 15 – LEGAL, ETHICAL & PROFESSIONAL ISSUES
# ══════════════════════════════════════════════════════════════════════════════
h1('15. Legal, Ethical & Professional Issues')

h2('15.1 Informed Consent in Obstetrics')
bullet('Must be voluntary, informed, and from a competent patient')
bullet('Women have the right to refuse ANY procedure including caesarean section')
bullet('Emergency: if capacity lacking and woman unable to consent, act in best interests')
bullet('Montgomery ruling (2015, UK): must disclose ALL material risks, not just those the clinician deems important')

h2('15.2 Documentation')
bullet('Contemporaneous records: document at the time or as soon as possible after the event')
bullet('All CTG traces must be stored securely and retained (minimum 25 years)')
bullet('Partograph must be completed at every birth')
bullet('Clearly document ALL assessments, interventions, and communication with the woman and team')
bullet('"If it is not documented, it was not done."')

h2('15.3 Mandatory Reporting')
bullet('Safeguarding concerns (child protection): suspected domestic violence, female genital mutilation, substance misuse endangering foetus')
bullet('Maternal deaths must be reported to national surveillance systems (e.g. MBRRACE-UK)')
bullet('Serious incidents (unexpected maternal or neonatal harm/death) trigger formal investigation')

h2('15.4 Confidentiality')
bullet('All patient information is confidential')
bullet('Sharing without consent requires: patient consent, legal requirement (court order), or overriding public interest (e.g., child protection)')
bullet('GDPR (in UK/EU) governs data handling; health records are special category data')

h2('15.5 Cultural Competence')
bullet('Acknowledge religious/cultural beliefs (e.g., refusal of blood products by Jehovah\'s Witnesses)')
bullet('Use professional interpreters, never family members, for clinical communication')
bullet('Female circumcision/FGM: illegal in UK; mandatory referral; deinfibulation before birth')
bullet('Respect birth preferences while ensuring safety')

doc.add_page_break()

# ══════════════════════════════════════════════════════════════════════════════
#  SECTION 16 – MNEMONICS & QUICK REFERENCE
# ══════════════════════════════════════════════════════════════════════════════
h1('16. Key Mnemonics & Quick-Reference Tables')

h2('16.1 Essential Mnemonics')
add_table(
    ['Mnemonic', 'What It Stands For', 'Context'],
    [
        ['APGAR', 'Appearance, Pulse, Grimace, Activity, Respiration', 'Newborn assessment at 1 and 5 minutes'],
        ['4 T\'s of PPH', 'Tone, Tissue, Trauma, Thrombin', 'Causes of postpartum haemorrhage'],
        ['HELPERR', 'Help, Episiotomy, Legs, Pressure, Enter, Remove arm, Roll', 'Shoulder dystocia management'],
        ['BUBBLE-HE', 'Breasts, Uterus, Bladder, Bowels, Lochia, Episiotomy, Homans, Emotional', 'Postpartum assessment'],
        ['TORCH', 'Toxoplasma, Other, Rubella, CMV, HSV', 'Congenital infections'],
        ['AVA', '2 Arteries, 1 Vein in Arteries, Vein, Arteries', 'Umbilical cord vessels (2A1V)'],
        ['PROM / PPROM', 'Premature/Pre-term rupture of membranes', 'Distinguish term vs preterm'],
        ['IUGR', 'Intrauterine Growth Restriction', 'SFH <3cm expected, USS referral'],
        ['GDM', 'Gestational Diabetes Mellitus', 'OGTT screen at 24-28 wks'],
        ['LAM', 'Lactational Amenorrhoea Method', 'Natural contraception - not reliable beyond 6 months'],
    ]
)

h2('16.2 Vital Signs Quick Reference')
add_table(
    ['Parameter', 'Non-pregnant Adult', 'Pregnant (Normal)', 'Newborn'],
    [
        ['Heart rate', '60-100 bpm', '70-110 bpm', '120-160 bpm'],
        ['BP systolic', '90-140 mmHg', 'Decreases in T1/T2; returns in T3', '60-90 mmHg'],
        ['Resp rate', '12-20/min', '14-20/min', '40-60/min'],
        ['Temperature', '36.5-37.5 °C', '36.5-37.5 °C', '36.5-37.5 °C'],
        ['O2 saturation', '>95%', '>95%', '>95% (after 10 min)'],
    ]
)

h2('16.3 Emergency Drugs Quick Reference')
add_table(
    ['Drug', 'Emergency Use', 'Dose'],
    [
        ['Oxytocin', 'PPH / active 3rd stage', '10 IU IM or IV'],
        ['Ergometrine', 'PPH (if no hypertension)', '500 mcg IM'],
        ['MgSO4', 'Eclampsia', '4 g IV over 5-10 min; then 1-2 g/hr'],
        ['Calcium gluconate', 'MgSO4 toxicity antidote', '1 g IV (10 mL of 10%) over 10 min'],
        ['Naloxone', 'Opioid-induced neonatal respiratory depression', '0.1 mg/kg IM/IV/SC'],
        ['Vitamin K', 'HDN prevention', '1 mg IM at birth'],
        ['Benzylpenicillin', 'GBS intrapartum prophylaxis', '3 g IV loading then 1.5 g q4h'],
        ['Betamethasone', 'Foetal lung maturity <34+6 wks', '12 mg IM x2 doses 24 hours apart'],
        ['Tranexamic acid', 'PPH adjunct', '1 g IV within 3 hours of delivery'],
    ]
)

h2('16.4 Key Normal Pregnancy Values')
add_table(
    ['Test', 'Normal in Pregnancy', 'Note'],
    [
        ['Haemoglobin', '≥110 g/L', 'WHO definition of anaemia in pregnancy <110 g/L 1st/3rd tri; <105 g/L 2nd tri'],
        ['Serum creatinine', '44-80 µmol/L', 'Lower than non-pregnant due to raised GFR'],
        ['Blood pressure', '<140/90 mmHg', 'Drops in T1/T2; rises back T3; >140/90 = gestational HTN'],
        ['Fasting glucose', '<5.1 mmol/L', 'GDM threshold (IADPSG)'],
        ['AFI', '8-25 cm', '<5 = oligohydramnios; >25 = polyhydramnios'],
        ['Platelet count', '>150 x10^9/L', '<100 x10^9/L requires haematology review'],
        ['TSH', '0.1-2.5 mIU/L (1st tri)', 'Lower in 1st tri; each trimester has different reference ranges'],
        ['Foetal heart rate', '110-160 bpm', 'Outside this = concerning; investigate'],
    ]
)

# ── Footer ────────────────────────────────────────────────────────────────────
doc.add_paragraph()
p = doc.add_paragraph()
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = p.add_run('— End of Midwifery Study Guide —\nPrepared for BSN Second-Year Assessment Preparation')
run.font.size = Pt(10)
run.font.color.rgb = RGBColor(0x70, 0x70, 0x70)
run.italic = True

# ── Save ──────────────────────────────────────────────────────────────────────
out_path = '/tmp/workspace/midwifery-study-guide/Midwifery_Comprehensive_Study_Guide_BSN.docx'
doc.save(out_path)
print(f"Saved: {out_path}")
Running Command

cd /tmp/workspace/midwifery-study-guide && python3 generate_midwifery.py

Running Command

ls -lh /tmp/workspace/midwifery-study-guide/

Your comprehensive midwifery study guide is ready. Download it here:

Midwifery Comprehensive Study Guide BSN

Word Document · DOCX


Here is a full summary of everything packed into the document (63 KB, fully formatted Word file):

What's Inside - All 16 Sections

#SectionWhat You'll Find
1Introduction to MidwiferyDefinition, scope of practice for BSN nurses, models of care
2Female Reproductive Anatomy & PhysiologyVulva, vagina, uterus, cervix, ovaries, the menstrual cycle, pelvis types (gynaecoid, android, anthropoid, platypelloid)
3Conception, Fertilisation & ImplantationDay-by-day development table, placental functions, TORCH placental barrier rule
4Physiological Changes in PregnancyCardiovascular, haematological, respiratory, renal, GI, musculoskeletal, skin, endocrine - all with tables
5Antenatal CareWHO visit schedule, booking visit assessment, investigation table, SFH landmarks, foetal lie/presentation/position/engagement
6Foetal Development & MonitoringTrimester milestones, amniotic fluid (oligo/poly), CTG interpretation table (NICE classification), foetal movement monitoring
7Normal Labour & DeliveryStages of labour with durations, premonitory signs, 7 cardinal movements, partograph use, pain relief options
8Third Stage ManagementActive vs physiological management table, placenta examination, perineal tear degrees + episiotomy
9Postnatal CareBUBBLE-HE assessment, lochia table (rubra/serosa/alba), postpartum blues vs PND vs psychosis comparison
10Neonatal Care & AssessmentAPGAR scoring table, newborn normal values, neonatal reflexes table, physiological vs pathological jaundice
11BreastfeedingLactation physiology, WHO recommendations, benefits, latch assessment, common problems + management table
12Obstetric Complications & EmergenciesPre-eclampsia/eclampsia/HELLP, APH (placenta praevia vs abruption), PPH (4 T's + HAEMOSTASIS), preterm labour, PPROM, cord prolapse, shoulder dystocia (HELPERR), GDM, ectopic pregnancy
13Pharmacology in MidwiferyRoutine pregnancy drugs, uterotonics, tocolytics, MgSO4 protocol, drugs to AVOID in pregnancy
14Infection ControlTORCH infections table, GBS - intrapartum prophylaxis protocol, standard precautions
15Legal & Ethical IssuesInformed consent, documentation standards, mandatory reporting, confidentiality, cultural competence
16Mnemonics & Quick ReferenceAPGAR, 4 T's, HELPERR, BUBBLE-HE, TORCH, vital signs table, emergency drugs doses, normal pregnancy lab values

Quick tip for your assessment: Focus especially on Sections 7 (labour stages + partograph), 12 (emergencies - shoulder dystocia HELPERR and PPH 4 T's are frequent exam topics), 10 (APGAR scoring), and 13 (MgSO4 protocol and drugs to avoid in pregnancy). Good luck!

Create a summary PDF for quick bedside reference

Reading File
Writing File

~/midwifery-study-guide/generate_bedside_pdf.py

"""
Midwifery Bedside Quick-Reference PDF
BSN Second-Year Nursing Students
Built with ReportLab
"""

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

# ── Palette ───────────────────────────────────────────────────────────────────
NAVY     = HexColor('#1A3A5C')
BLUE     = HexColor('#2E74B5')
LTBLUE   = HexColor('#D6E8F7')
TEAL     = HexColor('#1B6B72')
LTTEAL   = HexColor('#D0F0F3')
RED      = HexColor('#C0392B')
LTRED    = HexColor('#FADBD8')
ORANGE   = HexColor('#E67E22')
LTORANGE = HexColor('#FDEBD0')
GREEN    = HexColor('#1E8449')
LTGREEN  = HexColor('#D5F5E3')
PURPLE   = HexColor('#6C3483')
LTPURPLE = HexColor('#E8DAEF')
GREY     = HexColor('#F0F2F5')
DKGREY   = HexColor('#4A4A4A')
YELLOW   = HexColor('#F9E79F')

W, H = A4  # 595 x 842 pts

# ── Page template with header/footer ─────────────────────────────────────────
def make_doc(path):
    doc = SimpleDocTemplate(
        path,
        pagesize=A4,
        leftMargin=1.2*cm, rightMargin=1.2*cm,
        topMargin=2.2*cm, bottomMargin=1.8*cm,
        title="Midwifery Bedside Quick-Reference",
        author="Orris Medical Study Tools"
    )
    return doc

def on_page(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(NAVY)
    canvas.rect(0, H - 1.6*cm, W, 1.6*cm, fill=1, stroke=0)
    canvas.setFillColor(white)
    canvas.setFont("Helvetica-Bold", 11)
    canvas.drawString(1.2*cm, H - 1.1*cm, "MIDWIFERY  BEDSIDE  QUICK-REFERENCE")
    canvas.setFont("Helvetica", 9)
    canvas.drawRightString(W - 1.2*cm, H - 1.1*cm, "BSN Year 2  |  Pre-Assessment Edition")
    # Footer bar
    canvas.setFillColor(NAVY)
    canvas.rect(0, 0, W, 1.2*cm, fill=1, stroke=0)
    canvas.setFillColor(white)
    canvas.setFont("Helvetica", 8)
    canvas.drawString(1.2*cm, 0.45*cm, "For educational use only – not a substitute for clinical judgement")
    canvas.drawRightString(W - 1.2*cm, 0.45*cm, f"Page {doc.page}")
    canvas.restoreState()

# ── Style helpers ─────────────────────────────────────────────────────────────
base = getSampleStyleSheet()

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

TITLE_STYLE   = S('Heading1', fontSize=17, textColor=NAVY, spaceAfter=4,
                   fontName='Helvetica-Bold', leading=20)
SEC_STYLE     = S('Heading2', fontSize=12, textColor=white, spaceAfter=0,
                   fontName='Helvetica-Bold', leading=14, leftIndent=4)
SUB_STYLE     = S('Heading3', fontSize=10, textColor=NAVY, spaceAfter=2,
                   fontName='Helvetica-Bold', leading=12)
BODY_STYLE    = S('Normal', fontSize=8.5, textColor=DKGREY, spaceAfter=2,
                   leading=11, fontName='Helvetica')
BOLD_STYLE    = S('Normal', fontSize=8.5, textColor=black, spaceAfter=2,
                   leading=11, fontName='Helvetica-Bold')
SMALL_STYLE   = S('Normal', fontSize=7.5, textColor=DKGREY, spaceAfter=1,
                   leading=10, fontName='Helvetica')
CENTER_STYLE  = S('Normal', fontSize=9, textColor=DKGREY, alignment=TA_CENTER,
                   leading=12, fontName='Helvetica')
KEY_LABEL     = S('Normal', fontSize=8, textColor=RED, fontName='Helvetica-Bold',
                   leading=10)

# ── Flowable builders ─────────────────────────────────────────────────────────
def section_header(text, color=BLUE):
    """Coloured bar section heading."""
    data = [[Paragraph(text, SEC_STYLE)]]
    t = Table(data, colWidths=[W - 2.4*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0,0), (-1,-1), color),
        ('TOPPADDING',    (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
        ('LEFTPADDING',   (0,0), (-1,-1), 6),
        ('RIGHTPADDING',  (0,0), (-1,-1), 6),
        ('ROUNDEDCORNERS', [3]),
    ]))
    return [t, Spacer(1, 3)]

def alert_box(text, bg=LTRED, border=RED, label="EMERGENCY"):
    """Coloured alert / key-point box."""
    content = f'<font color="#{border.hexval()[1:]}"><b>{label}:</b></font> {text}'
    data = [[Paragraph(content, BODY_STYLE)]]
    t = Table(data, colWidths=[W - 2.4*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND',    (0,0), (-1,-1), bg),
        ('LINEABOVE',     (0,0), (-1,0),  1.5, border),
        ('LINEBEFORE',    (0,0), (0,-1),  3,   border),
        ('TOPPADDING',    (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING',   (0,0), (-1,-1), 8),
        ('RIGHTPADDING',  (0,0), (-1,-1), 8),
    ]))
    return [t, Spacer(1, 4)]

def key_box(text, bg=LTBLUE, border=BLUE):
    return alert_box(text, bg=bg, border=border, label="KEY POINT")

def make_table(headers, rows, col_widths=None, hdr_color=BLUE, alt=True):
    """Generic styled table."""
    usable = W - 2.4*cm
    if col_widths is None:
        col_widths = [usable / len(headers)] * len(headers)
    data = [[Paragraph(str(h), S('Normal', fontSize=8, textColor=white,
                                  fontName='Helvetica-Bold', leading=10))
             for h in headers]]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(c), SMALL_STYLE) for c in row])
    style = [
        ('BACKGROUND',    (0,0),  (-1,0),  hdr_color),
        ('ROWBACKGROUNDS',(0,1),  (-1,-1), [white, GREY] if alt else [white]),
        ('GRID',          (0,0),  (-1,-1), 0.3, HexColor('#BBBBBB')),
        ('TOPPADDING',    (0,0),  (-1,-1), 3),
        ('BOTTOMPADDING', (0,0),  (-1,-1), 3),
        ('LEFTPADDING',   (0,0),  (-1,-1), 4),
        ('RIGHTPADDING',  (0,0),  (-1,-1), 4),
        ('VALIGN',        (0,0),  (-1,-1), 'TOP'),
    ]
    t = Table(data, colWidths=col_widths)
    t.setStyle(TableStyle(style))
    return [t, Spacer(1, 5)]

def bullet_table(items, two_col=False):
    """Compact bullet list, optionally 2-column."""
    usable = W - 2.4*cm
    if not two_col or len(items) <= 4:
        data = [[Paragraph(f'• {item}', SMALL_STYLE)] for item in items]
        t = Table(data, colWidths=[usable])
        t.setStyle(TableStyle([('TOPPADDING',(0,0),(-1,-1),1),
                                ('BOTTOMPADDING',(0,0),(-1,-1),1),
                                ('LEFTPADDING',(0,0),(-1,-1),4),
                                ('RIGHTPADDING',(0,0),(-1,-1),4)]))
    else:
        mid = (len(items) + 1) // 2
        left = items[:mid]
        right = items[mid:]
        while len(right) < len(left):
            right.append('')
        data = [[Paragraph(f'• {l}' if l else '', SMALL_STYLE),
                 Paragraph(f'• {r}' if r else '', SMALL_STYLE)]
                for l, r in zip(left, right)]
        t = Table(data, colWidths=[usable/2, usable/2])
        t.setStyle(TableStyle([('TOPPADDING',(0,0),(-1,-1),1),
                                ('BOTTOMPADDING',(0,0),(-1,-1),1),
                                ('LEFTPADDING',(0,0),(-1,-1),4)]))
    return [t, Spacer(1, 4)]

def mnemonic_box(mnemonic, expansions, bg=LTPURPLE, border=PURPLE):
    """Box showing mnemonic letter by letter."""
    lines = ''.join(
        f'<b><font color="#{border.hexval()[1:]}">{let}</font></b> — {exp}   '
        for let, exp in expansions
    )
    data = [[Paragraph(f'<b>{mnemonic}</b>', S('Normal', fontSize=10,
                        textColor=border, fontName='Helvetica-Bold', leading=12)),
             Paragraph(lines, SMALL_STYLE)]]
    t = Table(data, colWidths=[2.2*cm, W - 2.4*cm - 2.2*cm])
    t.setStyle(TableStyle([
        ('BACKGROUND',    (0,0), (-1,-1), bg),
        ('LINEABOVE',     (0,0), (-1,0),  1, border),
        ('LINEBEFORE',    (0,0), (0,-1),  3, border),
        ('TOPPADDING',    (0,0), (-1,-1), 5),
        ('BOTTOMPADDING', (0,0), (-1,-1), 5),
        ('LEFTPADDING',   (0,0), (-1,-1), 6),
        ('VALIGN',        (0,0), (-1,-1), 'MIDDLE'),
    ]))
    return [t, Spacer(1, 4)]

def hr():
    return [HRFlowable(width='100%', thickness=0.5, color=HexColor('#CCCCCC')), Spacer(1,3)]

# ══════════════════════════════════════════════════════════════════════════════
#  BUILD CONTENT
# ══════════════════════════════════════════════════════════════════════════════
story = []

# ── COVER ─────────────────────────────────────────────────────────────────────
story.append(Spacer(1, 1.5*cm))
cover_title_data = [[Paragraph(
    '<font color="#1A3A5C"><b>MIDWIFERY<br/>BEDSIDE QUICK-REFERENCE</b></font>',
    S('Normal', fontSize=28, fontName='Helvetica-Bold',
      leading=34, alignment=TA_CENTER)
)]]
ct = Table(cover_title_data, colWidths=[W - 2.4*cm])
ct.setStyle(TableStyle([
    ('BACKGROUND', (0,0), (-1,-1), LTBLUE),
    ('TOPPADDING',    (0,0), (-1,-1), 18),
    ('BOTTOMPADDING', (0,0), (-1,-1), 18),
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
]))
story.append(ct)
story.append(Spacer(1, 0.4*cm))
story.append(Paragraph(
    '<font color="#2E74B5">BSN Second-Year Nursing Student  |  Pre-Assessment Edition  |  July 2026</font>',
    CENTER_STYLE))
story.append(Spacer(1, 0.8*cm))

# quick index
index_items = [
    ('1', 'Vital Signs & Normal Values',        '2'),
    ('2', 'Pregnancy Milestones & SFH',         '2'),
    ('3', 'Antenatal Investigations',           '2'),
    ('4', 'CTG Interpretation',                 '3'),
    ('5', 'Stages of Labour',                   '3'),
    ('6', 'Partograph Alert Lines',             '3'),
    ('7', 'Pain Relief in Labour',              '4'),
    ('8', 'APGAR Score',                        '4'),
    ('9', 'Neonatal Reflexes',                  '4'),
    ('10','Neonatal Jaundice',                  '4'),
    ('11','Postpartum Assessment (BUBBLE-HE)',   '5'),
    ('12','Lochia Chart',                       '5'),
    ('13','Breastfeeding Quick Guide',          '5'),
    ('14','PPH – 4 T\'s & Management',          '6'),
    ('15','Pre-eclampsia / Eclampsia',          '6'),
    ('16','Shoulder Dystocia – HELPERR',        '6'),
    ('17','Cord Prolapse',                      '7'),
    ('18','Emergency Drugs & Doses',            '7'),
    ('19','Drugs to Avoid in Pregnancy',        '7'),
    ('20','Key Mnemonics',                      '8'),
]
mid = len(index_items)//2
left_col  = index_items[:mid]
right_col = index_items[mid:]
while len(right_col) < len(left_col):
    right_col.append(('','',''))

idx_data = []
for (n1,t1,p1),(n2,t2,p2) in zip(left_col, right_col):
    l = Paragraph(f'<b>{n1}.</b> {t1} ........... <b>{p1}</b>', SMALL_STYLE) if n1 else Paragraph('', SMALL_STYLE)
    r = Paragraph(f'<b>{n2}.</b> {t2} ........... <b>{p2}</b>', SMALL_STYLE) if n2 else Paragraph('', SMALL_STYLE)
    idx_data.append([l, r])

col_w = (W - 2.4*cm) / 2
idx_t = Table(idx_data, colWidths=[col_w, col_w])
idx_t.setStyle(TableStyle([
    ('TOPPADDING',    (0,0), (-1,-1), 2),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
    ('LEFTPADDING',   (0,0), (-1,-1), 4),
    ('LINEABOVE',     (0,0), (-1,0),  0.5, BLUE),
    ('LINEBELOW',     (0,-1),(-1,-1), 0.5, BLUE),
]))
story.append(Paragraph('<b>Quick Index</b>', SUB_STYLE))
story.append(idx_t)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 2  –  VITALS / SFH / ANTENATAL INVESTIGATIONS
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('1. VITAL SIGNS & NORMAL VALUES IN PREGNANCY', TEAL)
story += make_table(
    ['Parameter',       'Non-pregnant',      'Pregnant',              'Newborn'],
    [
        ['Heart rate',      '60-100 bpm',        '70-110 bpm (+10-15)',   '120-160 bpm'],
        ['BP',              '<140/90 mmHg',      'Falls T1/T2; rises T3', '60-90 / 40-60'],
        ['Resp rate',       '12-20/min',         '14-20/min',             '40-60/min'],
        ['Temperature',     '36.5-37.5 °C',      '36.5-37.5 °C',         '36.5-37.5 °C'],
        ['Hb',              '120-160 g/L',       '≥110 g/L (WHO)',        '145-225 g/L'],
        ['Creatinine',      '62-115 µmol/L',     '44-80 µmol/L (↓)',      '—'],
        ['Fasting glucose', '<5.6 mmol/L',       '<5.1 mmol/L (GDM cut)', '≥2.6 mmol/L'],
        ['AFI',             'N/A',               '8-25 cm',               '—'],
        ['Foetal HR (CTG)', '—',                 '—',                     '110-160 bpm'],
    ],
    col_widths=[4.2*cm, 3.5*cm, 4.5*cm, 3.5*cm],
    hdr_color=TEAL
)

story += section_header('2. PREGNANCY MILESTONES & SYMPHYSIS-FUNDAL HEIGHT', BLUE)
story += make_table(
    ['Weeks', 'Fundal Height Landmark',    'Key Events'],
    [
        ['8-10',  'Not palpable abdominally',   'hCG peaks; morning sickness peaks'],
        ['12',    'Just above pubic symphysis',  'End of 1st trimester; all organs formed'],
        ['16',    'Midway symph-umbilicus',      'Anomaly scan ordered; AFP screen'],
        ['20',    'At umbilicus (~20 cm)',       'Anomaly USS; quickening felt by primigravida'],
        ['24-26', '22-26 cm',                   'Viability threshold; GDM screening'],
        ['28',    '~28 cm',                     'Anti-D if Rh-neg; iron check; GTT'],
        ['32',    '~30-32 cm',                  'Presentation check; growth USS if concerns'],
        ['36',    'At xiphisternum (~36 cm)',   'GBS swab; birth plan; check presentation'],
        ['38-40', 'Slightly lower (engagement)','Await spontaneous labour; membrane sweep at 40 wks'],
        ['41+',   'Variable',                   'Offer induction; post-dates monitoring'],
    ],
    col_widths=[1.8*cm, 5.5*cm, 8.4*cm],
    hdr_color=BLUE
)
story.append(Paragraph(
    '<b>Naegele\'s Rule:</b> EDD = LMP + 9 months + 7 days  (or LMP + 280 days)',
    BODY_STYLE))
story.append(Spacer(1, 4))

story += section_header('3. ANTENATAL INVESTIGATIONS AT BOOKING', NAVY)
story += make_table(
    ['Investigation',               'Purpose / Action if Abnormal'],
    [
        ['FBC',                     'Baseline Hb; <110 g/L = anaemia → iron/folate'],
        ['Blood group & Rh factor', 'Anti-D prophylaxis if Rh-negative'],
        ['Antibody screen',         'Alloimmunisation; haemolytic disease of newborn risk'],
        ['Rubella IgG',             'Non-immune → MMR postnatally (NOT in pregnancy)'],
        ['Syphilis (VDRL/RPR)',     'Treat with benzylpenicillin; prevent congenital syphilis'],
        ['HIV',                     'ART to prevent MTCT; elective caesarean if VL >1000'],
        ['Hepatitis B sAg',         'Positive → newborn HBV vaccine + HBIG at birth'],
        ['MSU (mid-stream urine)',  'Asymptomatic bacteriuria → treat (pyelonephritis prevention)'],
        ['TSH',                     'Hypothyroidism → levothyroxine; developmental risk if untreated'],
        ['HbA1c / random glucose',  'Pre-existing diabetes screen'],
        ['Hb electrophoresis',      'Sickle cell / thalassaemia in at-risk populations'],
        ['1st trimester combined',  'PAPP-A + free β-hCG + NT USS (11-13+6 wks) → T21/T18/T13 risk'],
    ],
    col_widths=[5.5*cm, 10.2*cm],
    hdr_color=NAVY
)

story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 3  –  CTG / STAGES OF LABOUR / PARTOGRAPH
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('4. CTG INTERPRETATION (NICE CLASSIFICATION)', TEAL)
story += make_table(
    ['Feature',         'Normal (Reassuring)',     'Non-Reassuring',             'Abnormal'],
    [
        ['Baseline FHR', '110-160 bpm',            '100-109 or 161-180 bpm',     '<100 or >180 bpm'],
        ['Variability',  '5-25 bpm',               '3-4 bpm for ≥40 min',        '<3 bpm >30 min; sinusoidal'],
        ['Accelerations','≥2 in 20 min',           'None (if non-reassuring)',   'Absent with other features'],
        ['Decelerations','None / early only',      'Variable / single prolonged', 'Late, atypical variable, >3 min prolonged'],
    ],
    col_widths=[3.2*cm, 4.0*cm, 4.5*cm, 4.0*cm],
    hdr_color=TEAL
)
story += alert_box(
    'Early decels = head compression (NORMAL). '
    'Late decels = uteroplacental insufficiency (CONCERNING). '
    'Variable decels = cord compression. '
    'Prolonged decel >3 min = call for help + in utero resuscitation.',
    bg=LTTEAL, border=TEAL, label='CTG RULE'
)

story += section_header('5. STAGES OF LABOUR', BLUE)
story += make_table(
    ['Stage',               'Definition',                         'Primigravida',   'Multigravida'],
    [
        ['1st – Latent',    '0–3 cm dilation; irregular contractions',   'Up to 20 hrs',   'Up to 14 hrs'],
        ['1st – Active',    '4–10 cm; ≥0.5 cm/hr progress expected',    'Avg 8 hrs',      'Avg 5 hrs'],
        ['Transition',      '8–10 cm; intense; urge to push',           '15-60 min',      '15-30 min'],
        ['2nd',             'Full dilation → delivery of baby',         'Up to 3 hrs',    'Up to 2 hrs'],
        ['3rd',             'Delivery of baby → delivery of placenta',  '≤30 min (active)','≤30 min (active)'],
    ],
    col_widths=[3.0*cm, 6.5*cm, 3.0*cm, 3.2*cm],
    hdr_color=BLUE
)
story.append(Paragraph(
    '<b>7 Cardinal Movements (Vertex):</b> Engagement → Descent → Flexion → Internal rotation → '
    'Extension (head delivery) → External rotation (restitution) → Expulsion (shoulders/body)',
    BODY_STYLE))
story.append(Spacer(1, 4))

story += section_header('6. PARTOGRAPH – ALERT & ACTION LINES', NAVY)
story += make_table(
    ['Line',        'Definition',                                  'Action'],
    [
        ['Alert line',  '1 cm/hr progress from 4 cm active labour',   'Increase monitoring frequency; review hydration, position'],
        ['Action line', '4 hours to the right of the alert line',     'Immediate medical review; consider ARM, oxytocin augmentation, or caesarean section'],
    ],
    col_widths=[2.5*cm, 7.0*cm, 6.2*cm],
    hdr_color=NAVY
)
story += bullet_table([
    'Foetal HR documented every 30 min (active labour)',
    'Liquor colour documented: C = clear, M = meconium, B = blood',
    'Contractions: shade in frequency, duration, strength every 30 min',
    'BP/Pulse every 30 min; Temperature every 4 hours',
    'Urine output every 2-4 hours',
], two_col=True)

story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 4  –  PAIN RELIEF / APGAR / NEONATAL REFLEXES / JAUNDICE
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('7. PAIN RELIEF IN LABOUR', TEAL)
story += make_table(
    ['Method',          'Type',         'Key Points',                            'Cautions'],
    [
        ['TENS',         'Non-pharm',    'Best in early labour; patient controlled', 'Not for water birth'],
        ['Hydrotherapy', 'Non-pharm',    'Warm bath/pool; reduces pain perception',  'Continuous CTG not possible in pool'],
        ['Entonox',      'Inhaled',      '50% N₂O + 50% O₂; self-admin; rapid onset','Dizziness, nausea, do not store'],
        ['Pethidine',    'Opioid IM',    '75-150 mg IM; sedation; works 20-45 min',  'Neonatal resp depression → Naloxone 0.1 mg/kg'],
        ['Epidural',     'Regional',     'Most effective; continuous infusion option','Hypotension; urinary retention; slows labour; requires IV access + CTG'],
        ['Spinal',       'Regional',     'Single shot; used for caesarean section',   'Rapid hypotension; headache (PDPH)'],
    ],
    col_widths=[2.8*cm, 2.2*cm, 5.8*cm, 4.9*cm],
    hdr_color=TEAL
)

story += section_header('8. APGAR SCORE  (1 min & 5 min)', BLUE)
story += make_table(
    ['Sign',            '0',              '1',                    '2'],
    [
        ['Appearance',  'Blue/pale all',  'Blue extremities, pink body', 'Completely pink'],
        ['Pulse (HR)',  'Absent',         '<100 bpm',             '≥100 bpm'],
        ['Grimace',     'No response',    'Grimace',              'Cry / cough / sneeze'],
        ['Activity',    'Limp',           'Some flexion',         'Active motion'],
        ['Respiration', 'Absent',         'Weak, irregular',      'Strong cry'],
    ],
    col_widths=[3.2*cm, 3.5*cm, 4.8*cm, 4.2*cm],
    hdr_color=BLUE
)
story += bullet_table([
    '7-10 = Normal – reassess if any concerns',
    '4-6 = Moderate depression – O₂, stimulate, prepare resuscitation',
    '0-3 = Severe depression – IMMEDIATE full resuscitation (Airway, Breathing, Circulation, Drugs)',
])

story += section_header('9. NEONATAL PRIMITIVE REFLEXES', NAVY)
story += make_table(
    ['Reflex',    'Elicit',                     'Normal Response',                    'Gone By'],
    [
        ['Rooting',   'Stroke cheek',           'Turns to stimulus, opens mouth',     '3-4 months'],
        ['Moro',      'Head drop/startle',       'Arms abduct/extend → embrace',       '3-6 months'],
        ['Grasp',     'Finger in palm',          'Fingers curl around object',         '3-6 months'],
        ['Babinski',  'Stroke lateral sole',     'Big toe up, fan other toes',         '1-2 years'],
        ['Stepping',  'Feet touch surface',      'Stepping movements',                 '2-3 months'],
    ],
    col_widths=[2.4*cm, 4.0*cm, 5.5*cm, 3.8*cm],
    hdr_color=NAVY
)
story += alert_box(
    'Absent or ASYMMETRIC Moro reflex = investigate for brachial plexus injury (Erb\'s palsy), clavicle fracture, or CNS problem.',
    bg=LTRED, border=RED, label='ALERT'
)

story += section_header('10. NEONATAL JAUNDICE', TEAL)
story += make_table(
    ['Type',            'Timing',           'Causes',                          'Treatment'],
    [
        ['Physiological', 'Day 2-3 onset, peaks day 4-5, gone by day 14', 'Haemolysis of foetal Hb + immature liver', 'Phototherapy if above treatment threshold'],
        ['Pathological',  'WITHIN 24 HOURS (always pathological)', 'ABO/Rh incompatibility, G6PD, infection, biliary atresia', 'Urgent Coombs, bilirubin, blood group; phototherapy/exchange transfusion'],
    ],
    col_widths=[2.5*cm, 4.0*cm, 5.8*cm, 3.4*cm],
    hdr_color=TEAL
)
story += key_box('Jaundice within 24 hours of birth = ALWAYS pathological until proven otherwise. Escalate immediately.')

story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 5  –  POSTNATAL / LOCHIA / BREASTFEEDING
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('11. POSTNATAL ASSESSMENT – BUBBLE-HE', BLUE)
story += make_table(
    ['Letter', 'Area',        'What to Assess'],
    [
        ['B', 'Breasts',      'Engorgement, nipple cracking, signs of mastitis, colostrum/milk flow, latch assistance'],
        ['U', 'Uterus',       'Fundal height (descends 1-2 cm/day), tone (boggy = atony → massage), tenderness'],
        ['B', 'Bladder',      'Voiding within 4-6 hrs of delivery; urinary retention common; bladder distension palpation'],
        ['B', 'Bowels',       'Constipation common; encourage fluids, fibre; first bowel motion by day 3'],
        ['L', 'Lochia',       'Colour, amount, odour – see lochia table below'],
        ['E', 'Episiotomy',   'REEDA scale: Redness, Oedema, Ecchymosis, Discharge, Approximation; check sutures'],
        ['H', 'Homans sign',  'Calf pain on dorsiflexion (DVT screen) – low sensitivity; assess + escalate if positive'],
        ['E', 'Emotional',    'EPDS (Edinburgh Postnatal Depression Scale) at 2-6 weeks; assess bonding'],
    ],
    col_widths=[1.0*cm, 2.5*cm, 12.2*cm],
    hdr_color=BLUE
)

story += section_header('12. LOCHIA REFERENCE CHART', NAVY)
story += make_table(
    ['Stage',         'Timing',       'Colour',     'Composition'],
    [
        ['Lochia Rubra',  'Days 1-3',   'Red (bloody)', 'Blood, decidua, trophoblastic debris'],
        ['Lochia Serosa', 'Days 4-10',  'Pink / brown', 'Serum, leukocytes, wound exudate'],
        ['Lochia Alba',   'Day 10 – 6 wks', 'White / yellow', 'Leukocytes, decidua, epithelial cells'],
    ],
    col_widths=[3.5*cm, 3.0*cm, 3.0*cm, 6.2*cm],
    hdr_color=NAVY
)
story += alert_box(
    'Heavy bright-red bleeding after day 3, offensive smell, or fever with lochia = retained products / endometritis → escalate urgently.',
    bg=LTRED, border=RED, label='ALERT'
)

story += section_header('13. BREASTFEEDING QUICK GUIDE', TEAL)
story.append(Paragraph(
    '<b>WHO:</b> Exclusive breastfeeding to 6 months; continue to 2 years with complementary foods.',
    BODY_STYLE))
story.append(Spacer(1, 3))
story += make_table(
    ['Milk Stage',      'Timing',       'Key Features'],
    [
        ['Colostrum',   'Days 1-3',     'Thick, yellow; high IgA, lactoferrin, growth factors; small volumes normal'],
        ['Transitional','Days 3-14',    'Volume increases; protein/IgA decrease; fat increases'],
        ['Mature milk', 'After 2 wks',  'Foremilk (thirst) → Hindmilk (fat-rich, satiety/growth)'],
    ],
    col_widths=[3.0*cm, 2.5*cm, 10.2*cm],
    hdr_color=TEAL
)
story.append(Paragraph('<b>Correct Latch Signs:</b>', BOLD_STYLE))
story += bullet_table([
    'Mouth wide open (≥140°)',
    'Lower lip flanged outward',
    'Chin touching breast',
    'Audible swallowing',
    'Cheeks rounded (not sunken)',
    'Minimal nipple pain after initial latch',
], two_col=True)
story += make_table(
    ['Problem',          'Cause',                   'Action'],
    [
        ['Sore/cracked nipples', 'Poor latch',       'Correct latch; air dry; lanolin cream'],
        ['Engorgement',          'Milk build-up',    'Frequent feeds; warm compress before; cold after; hand express to soften'],
        ['Mastitis',             'Blocked duct + Staph aureus', 'Continue feeding; flucloxacillin 500 mg QID x10 days; analgesia'],
        ['Breast abscess',       'Untreated mastitis','I&D or needle aspiration + antibiotics; specialist referral'],
        ['Thrush',               'Candida',           'Miconazole/nystatin for BOTH baby mouth AND mother\'s nipples simultaneously'],
    ],
    col_widths=[3.5*cm, 4.0*cm, 8.2*cm],
    hdr_color=TEAL
)

story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 6  –  PPH / PRE-ECLAMPSIA / SHOULDER DYSTOCIA
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('14. POSTPARTUM HAEMORRHAGE (PPH) – THE 4 T\'s', RED)
story += alert_box(
    'PPH = blood loss ≥500 mL (vaginal) or ≥1000 mL (caesarean) within 24 hours. '
    'Primary PPH: within 24 hrs. Secondary PPH: 24 hrs – 6 weeks.',
    bg=LTRED, border=RED, label='DEFINITION'
)
story += make_table(
    ['T',       'Cause',              'Frequency', 'First-line Management'],
    [
        ['TONE',    'Uterine atony',   '~80%',    'Bimanual uterine compression + oxytocin 10 IU IV/IM, then ergometrine, then carboprost, then balloon tamponade'],
        ['TISSUE',  'Retained placenta/clots', '~10%', 'Manual removal of placenta (MROP) under anaesthesia; uterine exploration'],
        ['TRAUMA',  'Lacerations, rupture', '~7%', 'Repair cervical/vaginal/perineal tears; uterine compression sutures (B-Lynch)'],
        ['THROMBIN','Coagulopathy/DIC', '~3%',    'FFP, cryoprecipitate, platelets; tranexamic acid 1 g IV'],
    ],
    col_widths=[1.8*cm, 4.0*cm, 2.5*cm, 7.4*cm],
    hdr_color=RED
)
story += alert_box(
    'H-Help. A-Assess/resuscitate. E-Establish 2x IV + FBC/crossmatch. '
    'M-Massage uterus. O-Oxytocin. S-Second uterotonic. T-Tamponade. A-Apply compression suture. '
    'S-Systemic embolisation. I-Interventional radiology. S-Subtotal hysterectomy.',
    bg=LTRED, border=RED, label='HAEMOSTASIS MNEMONIC'
)

story += section_header('15. HYPERTENSIVE DISORDERS IN PREGNANCY', NAVY)
story += make_table(
    ['Condition',         'Criteria',                             'Key Features',            'Management'],
    [
        ['Gestational HTN',   'BP ≥140/90 after 20 wks; NO proteinuria', 'Headache common', 'Labetalol/nifedipine/methyldopa; monitor'],
        ['Pre-eclampsia',     'BP ≥140/90 + proteinuria ≥0.3 g/24h OR organ dysfunction', 'Headache, visual changes, epigastric pain, oedema, ↑urate', 'MgSO₄ (seizure prophylaxis); antihypertensives; DELIVER (cure)'],
        ['Eclampsia',         'Tonic-clonic seizures in pre-eclamptic patient', 'Can be ante/intra/post-partum', 'MgSO₄ 4 g IV over 5-10 min → 1-2 g/hr; protect airway; deliver baby'],
        ['HELLP',             'Haemolysis + Elevated LFTs + Low Platelets', 'RUQ pain, malaise, ↑LDH, ↓Hb', 'Urgent delivery; steroids if <34 wks; platelets if <50'],
    ],
    col_widths=[2.8*cm, 4.8*cm, 3.5*cm, 4.6*cm],
    hdr_color=NAVY
)
story += key_box(
    'MgSO₄ monitoring: Resp rate >12/min, patellar reflexes PRESENT, urine output >25 mL/hr. '
    'Toxicity antidote = Calcium gluconate 1 g (10 mL of 10%) IV slowly.'
)
story += key_box(
    'Aspirin 75-150 mg/day from 12 weeks for ALL high-risk PE women (previous PE, chronic HTN, diabetes, CKD, multifetal, autoimmune).',
    bg=LTORANGE, border=ORANGE
)

story += section_header('16. SHOULDER DYSTOCIA – HELPERR', RED)
story += mnemonic_box('HELPERR', [
    ('H', 'Call for Help immediately'),
    ('E', 'Evaluate for Episiotomy (if needed for access)'),
    ('L', 'Legs – McRoberts manoeuvre (hyperflexion of thighs on abdomen)'),
    ('P', 'Suprapubic Pressure (Rubin II) – downward on anterior shoulder'),
    ('E', 'Enter – internal rotational manoeuvres (Woods screw, Reverse Woods)'),
    ('R', 'Remove the posterior arm'),
    ('R', 'Roll – Gaskin all-fours manoeuvre'),
], bg=LTRED, border=RED)
story += alert_box(
    'McRoberts + suprapubic pressure resolves ~90% of cases. '
    'Document HEAD-TO-BODY delivery interval precisely. '
    'Neonatal team must attend. Anticipate: brachial plexus injury, fractures, neonatal hypoxia.',
    bg=LTRED, border=RED, label='CRITICAL'
)

story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 7  –  CORD PROLAPSE / EMERGENCY DRUGS / DRUGS TO AVOID
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('17. CORD PROLAPSE – IMMEDIATE MANAGEMENT', RED)
story += alert_box(
    'OBSTETRIC EMERGENCY. Cord compression → foetal hypoxia. '
    'Do NOT push cord back into uterus.',
    bg=LTRED, border=RED, label='EMERGENCY'
)
story += bullet_table([
    '1. Call for HELP immediately – emergency bell/team',
    '2. Relieve pressure: gloved hand inserted to manually elevate presenting part off cord',
    '3. Position: knee-chest (best) or exaggerated Sims position',
    '4. Fill bladder (500 mL saline via catheter) – lifts presenting part off cord',
    '5. Keep cord warm and moist – do not compress or manipulate',
    '6. Give O₂ to mother via face mask',
    '7. EMERGENCY CAESAREAN SECTION as soon as possible',
    '8. Document foetal HR every 5 minutes until delivery',
])

story += section_header('18. EMERGENCY DRUGS & DOSES', TEAL)
story += make_table(
    ['Drug',                'Indication',                        'Dose / Route'],
    [
        ['Oxytocin (Syntocinon)',   'Active 3rd stage / PPH',   '10 IU IM or IV; infusion 20-40 IU in 500 mL'],
        ['Ergometrine',             'PPH (2nd line)',            '500 mcg IM or IV – AVOID if hypertension'],
        ['Carboprost (Hemabate)',   'PPH refractory',           '250 mcg IM q15 min, max 8 doses – AVOID in asthma'],
        ['Misoprostol',             'PPH (resource-limited)',   '600-800 mcg sublingual / rectal'],
        ['Tranexamic acid',         'PPH adjunct',              '1 g IV within 3 hours of delivery (WOMAN trial)'],
        ['MgSO₄',                  'Eclampsia / neuroprotection','4 g IV load over 5-10 min; then 1-2 g/hr'],
        ['Calcium gluconate',       'MgSO₄ toxicity ANTIDOTE',  '1 g (10 mL of 10%) IV over 10 min'],
        ['Benzylpenicillin',        'GBS intrapartum prophylaxis','3 g IV loading; then 1.5 g IV q4h in labour'],
        ['Betamethasone',           'Foetal lung maturity <35 wks','12 mg IM × 2 doses, 24 hours apart'],
        ['Naloxone',                'Neonatal opioid depression', '0.1 mg/kg IM/IV/SC/ET'],
        ['Vitamin K',               'HDN prevention (newborn)',  '1 mg IM at birth (all newborns)'],
        ['Nifedipine',              'Tocolysis PTL / acute HTN', '20 mg oral load; 10-20 mg TDS (tocolysis)'],
        ['Labetalol',               'Acute severe hypertension', '200 mg oral; IV 20 mg bolus then infusion'],
    ],
    col_widths=[4.2*cm, 5.0*cm, 6.5*cm],
    hdr_color=TEAL
)

story += section_header('19. DRUGS TO AVOID IN PREGNANCY', RED)
story += make_table(
    ['Drug / Class',        'Risk to Foetus'],
    [
        ['Warfarin (esp. T1)',       'Embryopathy; foetal haemorrhage → use LMWH'],
        ['ACE inhibitors / ARBs',   'Renal agenesis, oligohydramnios, skull defects'],
        ['NSAIDs (T3)',              'Premature ductus arteriosus closure; oligohydramnios'],
        ['Tetracyclines',            'Tooth discolouration; bone growth inhibition'],
        ['Aminoglycosides',          'Foetal ototoxicity (8th cranial nerve)'],
        ['Methotrexate',             'Major teratogen; foetal death'],
        ['Isotretinoin',             'Severe teratogen: craniofacial, cardiac, CNS malformations'],
        ['Thalidomide',              'Phocomelia (limb reduction defects) – classic teratogen'],
        ['Lithium',                  'Ebstein\'s anomaly (tricuspid valve)'],
        ['Alcohol (any amount)',     'Foetal Alcohol Spectrum Disorder (FASD) – no safe level'],
    ],
    col_widths=[5.0*cm, 10.7*cm],
    hdr_color=RED
)

story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# PAGE 8  –  MNEMONICS SUMMARY
# ══════════════════════════════════════════════════════════════════════════════

story += section_header('20. KEY MNEMONICS AT A GLANCE', PURPLE)
story.append(Spacer(1, 3))

story += mnemonic_box('APGAR', [
    ('A','Appearance (colour)'), ('P','Pulse (HR)'), ('G','Grimace (reflex)'),
    ('A','Activity (tone)'),    ('R','Respiration')
], bg=LTPURPLE, border=PURPLE)

story += mnemonic_box('4 T\'s PPH', [
    ('T','Tone (atony 80%)'), ('T','Tissue (retained placenta 10%)'),
    ('T','Trauma (lacerations 7%)'), ('T','Thrombin (coagulopathy 3%)')
], bg=LTRED, border=RED)

story += mnemonic_box('HELPERR', [
    ('H','Help'), ('E','Episiotomy'), ('L','Legs (McRoberts)'),
    ('P','Pressure suprapubic'), ('E','Enter (rotational)'),
    ('R','Remove posterior arm'), ('R','Roll (Gaskin)')
], bg=LTRED, border=RED)

story += mnemonic_box('BUBBLE-HE', [
    ('B','Breasts'), ('U','Uterus'), ('B','Bladder'), ('B','Bowels'),
    ('L','Lochia'), ('E','Episiotomy'), ('H','Homans'), ('E','Emotional')
], bg=LTBLUE, border=BLUE)

story += mnemonic_box('TORCH', [
    ('T','Toxoplasma'), ('O','Other (Syphilis/HBV/HIV/Zika)'),
    ('R','Rubella'), ('C','CMV'), ('H','HSV (Herpes Simplex)')
], bg=LTORANGE, border=ORANGE)

story += mnemonic_box('HAEMOSTASIS', [
    ('H','Help'), ('A','Assess/Resuscitate'), ('E','Establish IV x2'),
    ('M','Massage uterus'), ('O','Oxytocin'), ('S','Second uterotonic'),
    ('T','Tamponade'), ('A','Apply B-Lynch suture'), ('S','Systemic embolisation'),
    ('I','Interventional radiology'), ('S','Subtotal hysterectomy')
], bg=LTRED, border=RED)

story.append(Spacer(1, 0.3*cm))
story += section_header('POSTPARTUM MENTAL HEALTH – QUICK COMPARISON', NAVY)
story += make_table(
    ['Condition',         'Onset',        'Features',                          'Management'],
    [
        ['Baby Blues',        'Days 3-5',     'Tearfulness, labile mood; SELF-LIMITING by day 10', 'Reassurance, rest, support'],
        ['PND',               '2 wks–12 mths','Low mood, anhedonia, poor bonding; EPDS ≥10 = screen', 'Sertraline (1st line SSRI in BF); counselling; CBT'],
        ['Postpartum Psychosis','24 hrs–4 wks','Hallucinations, delusions, confusion; EMERGENCY', 'Urgent psychiatric admission; may need baby separation'],
    ],
    col_widths=[3.0*cm, 2.5*cm, 5.5*cm, 4.7*cm],
    hdr_color=NAVY
)

story.append(Spacer(1, 0.4*cm))
# final note
final_data = [[Paragraph(
    '<font color="#1A3A5C"><b>REMEMBER: </b></font>'
    'This card is a quick-reference prompt — always apply clinical judgement, '
    'follow your institution\'s protocols, and escalate early when in doubt. '
    '<b>When in doubt, call for help.</b>',
    BODY_STYLE
)]]
ft = Table(final_data, colWidths=[W - 2.4*cm])
ft.setStyle(TableStyle([
    ('BACKGROUND',    (0,0), (-1,-1), YELLOW),
    ('LINEABOVE',     (0,0), (-1,0),  2, ORANGE),
    ('TOPPADDING',    (0,0), (-1,-1), 8),
    ('BOTTOMPADDING', (0,0), (-1,-1), 8),
    ('LEFTPADDING',   (0,0), (-1,-1), 10),
    ('RIGHTPADDING',  (0,0), (-1,-1), 10),
]))
story.append(ft)

# ══════════════════════════════════════════════════════════════════════════════
#  BUILD
# ══════════════════════════════════════════════════════════════════════════════
out = '/tmp/workspace/midwifery-study-guide/Midwifery_Bedside_QuickReference.pdf'
doc = make_doc(out)
doc.build(story, onFirstPage=on_page, onLaterPages=on_page)
print(f"Saved: {out}")
Running Command

cd /tmp/workspace/midwifery-study-guide && python3 generate_bedside_pdf.py 2>&1

Editing File

~/midwifery-study-guide/generate_bedside_pdf.py

Successfully replaced 1 instance(s) of the string in '/tmp/workspace/midwifery-study-guide/generate_bedside_pdf.py'
Editing File

~/midwifery-study-guide/generate_bedside_pdf.py

Successfully replaced 1 instance(s) of the string in '/tmp/workspace/midwifery-study-guide/generate_bedside_pdf.py'
Running Command

grep -n "hexval" /tmp/workspace/midwifery-study-guide/generate_bedside_pdf.py

Running Command

cd /tmp/workspace/midwifery-study-guide && python3 generate_bedside_pdf.py 2>&1

Running Command

ls -lh /tmp/workspace/midwifery-study-guide/

Your bedside reference PDF is ready. Download it here:

Midwifery Bedside QuickReference

PDF Document · PDF


Here's what's packed into the 8 colour-coded pages (31 KB):
PageColourContents
CoverNavy/BlueQuick index with page numbers
2Teal/BlueVital signs table, SFH milestones by week, Naegele's rule, booking investigations
3Teal/Blue/NavyCTG classification (NICE), stages of labour with durations, partograph alert & action lines
4Teal/Blue/NavyPain relief comparison, APGAR scoring table, neonatal reflexes, jaundice (physio vs patho)
5Blue/Navy/TealBUBBLE-HE postnatal assessment, lochia chart, breastfeeding milk stages, common BF problems
6Red/NavyPPH 4 T's table + HAEMOSTASIS mnemonic, hypertensive disorders (HTN/PE/eclampsia/HELLP), shoulder dystocia HELPERR
7Red/TealCord prolapse steps, emergency drugs & doses, drugs to avoid in pregnancy
8Purple/MixedAll key mnemonics (APGAR, 4T's, HELPERR, BUBBLE-HE, TORCH, HAEMOSTASIS), postpartum mental health comparison
Design features:
  • Coloured section headers for fast scanning at bedside
  • Red alert boxes for emergencies
  • Blue key-point boxes for clinical pearls
  • All tables fit within page width - no horizontal scrolling
  • Header and footer on every page with page number

I need you to give case studies for to familiarise with for my assessment

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