attachment
attachment

Give information about all topics in short releted to surgery subject

analyse_media
Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Here is a complete, organized summary of all surgery topics from your notes:

Surgery Topics - Quick Reference


🟠 HEPATOBILIARY SYSTEM

1. Hepatomegaly

Enlargement of the liver (>15 cm span). Causes include infections (viral hepatitis, amoebic abscess), malignancy, fatty liver, heart failure, and haematological disorders. Confirmed by imaging (USG/CT).

2. Amoebic Liver Abscess

  • Cause: Entamoeba histolytica (via portal route from colon)
  • Features: RUQ pain, fever, tender hepatomegaly; "anchovy sauce" pus
  • Dx: USG (single large abscess, usually right lobe), serology
  • Rx: Metronidazole; aspiration if no response
  • Sabiston Textbook of Surgery

3. Pyogenic Liver Abscess

  • Cause: Bacteria via biliary tree (most common), portal vein, or hematogenous route; E. coli, Klebsiella
  • Features: Fever, RUQ pain, jaundice; mainly in 50s-60s
  • Pathogenesis: Ascending cholangitis, biliary obstruction, cryptogenic
  • Rx: IV antibiotics + percutaneous/surgical drainage
  • Sabiston Textbook of Surgery, Mulholland & Greenfield's Surgery

4. Hydatid Cyst (Echinococcosis)

  • Cause: Echinococcus granulosus; dog (definitive host) → sheep/humans (intermediate host)
  • Location: Right lobe of liver (75%); usually solitary
  • Features: Asymptomatic until complication (rupture, biliary communication, anaphylaxis)
  • Dx: USG (daughter cysts, hydatid sand, calcification); serology
  • Rx: PAIR (Puncture-Aspiration-Injection-Reaspiration) or surgery
  • Sabiston Textbook of Surgery

5. Actinomycosis (Hepatic)

  • Cause: Actinomyces israelii (gram +ve anaerobe)
  • Features: Indolent hepatic abscess with "sulfur granules"; sinus tract formation
  • Rx: Prolonged penicillin + surgical drainage

6. Gallstone (Cholelithiasis)

  • Types: Cholesterol (80%) and pigment stones
  • Risk factors (5 Fs): Fat, Female, Forty, Fertile, Fair
  • Pathogenesis: Excess biliary cholesterol or chronic hemolysis
  • Features: Biliary colic, RUQ pain after fatty meals
  • Rx: Laparoscopic cholecystectomy
  • Robbins & Kumar Basic Pathology

7. Cholecystitis

  • Acute: Gallstone impaction in cystic duct; Murphy's sign +ve; fever
  • Chronic: Repeated attacks → thickened GB wall, Rokitansky-Aschoff sinuses
  • Complications: Empyema, perforation, Mirizzi syndrome
  • Rx: Laparoscopic cholecystectomy (early within 72 hrs preferred)
  • Bailey and Love's Surgery

8. Gallbladder Carcinoma (Ca. GB)

  • Associated with gallstones (80%), porcelain GB, choledochal cyst
  • Presents late with jaundice, RUQ mass, weight loss
  • Poor prognosis; resection only curative option

9. Jaundice (Surgical)

  • Obstructive (surgical): Pale stools, dark urine, ↑ direct bilirubin, ↑ ALP
  • Causes: Choledocholithiasis, Ca. head of pancreas, biliary stricture, cholangiocarcinoma
  • Dx: LFTs, USG, MRCP, ERCP
  • Rx: Treat underlying cause; ERCP stenting for palliation

🟡 SPLEEN

10. Splenomegaly

  • Causes: Infections (malaria, EBV), haematological (lymphoma, CML), portal HTN
  • Features: Dragging pain, early satiety; hypersplenism (pancytopenia)
  • Rx: Treat cause; splenectomy for hypersplenism or trauma

11. Splenic Artery Aneurysm

  • Most common visceral artery aneurysm; 2x more common in women
  • Usually incidental; rupture causes sudden abdominal pain (mimics splenic rupture)
  • High risk in pregnancy (25% rupture during 3rd trimester - near 100% fetal mortality)
  • Rx: Endovascular embolization or stenting preferred; splenectomy in young patients
  • Bailey and Love's Surgery

12. Splenic Infarct

  • Causes: Myeloproliferative disease, sickle cell, splenic vein thrombosis
  • Features: LUQ pain, left shoulder tip pain
  • CT: Wedge-shaped perfusion defect; treatment is conservative

13. Cyst of Spleen

  • Primary (true): Epidermoid; lined by epithelium
  • Secondary (false/pseudocyst): Post-traumatic/post-infarct; no epithelial lining
  • Parasitic: Hydatid cyst
  • Rx: Observation if small; splenectomy or cyst excision if large/symptomatic

🔵 PANCREAS

14. Pancreatitis (Acute & Chronic)

  • Acute: Gallstones (most common), alcohol; raised serum amylase/lipase; Ranson's criteria for severity
    • Features: Epigastric pain radiating to back, vomiting, Grey Turner/Cullen signs in severe disease
    • Rx: IV fluids, analgesia, early enteral nutrition within 48 hrs; ERCP for biliary cause
  • Chronic: Alcohol (most common); calcifications, ductal dilatation; steatorrhea, DM
    • Rx: Low-fat diet, enzyme supplementation, pancreatic duct drainage (ERCP/surgery)
  • Sabiston Textbook of Surgery

15. Ca. Pancreas (Pancreatic Carcinoma)

  • 90% ductal adenocarcinoma; head of pancreas (70%)
  • Features: Painless progressive jaundice, weight loss, Courvoisier's sign (palpable GB)
  • Prognosis is very poor (5-yr survival ~10%)
  • Rx: Whipple's operation (pancreaticoduodenectomy) if resectable; most are inoperable at diagnosis

16. Pancreatic Abscess

  • Circumscribed pus collection near pancreas; complication of acute pancreatitis (infected ANC or WON)
  • Rx: Endoscopic internal drainage, or percutaneous drainage + antibiotics
  • Bailey and Love's Surgery

17. Pancreatic Calculus, Fistula, Cyst, Trauma, Anomalies

  • Pseudocyst: Fluid collection after acute pancreatitis; "no epithelial lining"; best drained endoscopically if >6 cm or symptomatic
  • Fistula: Pancreatic duct disruption → internal (ascites) or external fistula
  • Annular pancreas: Congenital anomaly; ring of pancreatic tissue around duodenum causing obstruction

🟢 THORACIC SURGERY

18. Pneumothorax

  • Air in pleural space; spontaneous (tall thin young males, blebs) or traumatic
  • Tension pneumothorax: Life-threatening; tracheal deviation, absent breath sounds; needle decompression 2nd ICS MCL then ICD
  • Rx: Small/stable - observation; symptomatic - ICD (2nd ICS MCL or 5th ICS AAL)

19. Pleural Effusion & Tapping (Thoracocentesis)

  • Fluid in pleural space; transudate (CCF, cirrhosis) vs exudate (infection, malignancy)
  • Light's criteria: Exudate if protein ratio >0.5, LDH ratio >0.6
  • Tap at 8th/9th ICS, posterior axillary line, above upper border of rib (avoids neurovascular bundle)

20. Hemothorax

  • Blood in pleural space; from trauma, great vessel injury
  • Massive: >1.5 L; Rx = ICD; if >1.5L output or persistent, surgical thoracotomy
  • Sabiston Textbook of Surgery

21. Bronchoscopy

  • Rigid or flexible; used for diagnosis (biopsy, BAL) and therapy (foreign body removal, stenting)
  • Indications: Hemoptysis, suspected lung cancer, endobronchial lesion

22. Flail Chest & Stove-In Chest

  • Flail chest: 3+ ribs fractured in 2+ places → paradoxical movement of chest wall
  • Stove-in chest: Multiple rib fractures with underlying pulmonary contusion
  • Rx: Analgesia, mechanical ventilation (if respiratory failure), splinting

23. Emphysema (Surgical/Subcutaneous)

  • Air in subcutaneous tissues (post-trauma, post-procedure) or obstructive lung disease
  • Surgical emphysema: Crepitus on palpation; manage underlying cause (usually ICD resolves it)

24. Lung Abscess

  • Suppurative necrosis within lung parenchyma
  • Causes: Aspiration (most common), pneumonia, bronchial obstruction
  • Features: Fever, cough with foul-smelling sputum, haemoptysis; CXR = cavity with air-fluid level
  • Rx: IV antibiotics (prolonged, 4-6 weeks), postural drainage; surgery rarely needed

25. Intercostal Tube Drainage (ICD)

  • Indications: Pneumothorax, hemothorax, empyema, pleural effusion
  • Site: 5th ICS, anterior axillary line (safe triangle); or 2nd ICS MCL for pneumothorax
  • Use underwater seal drainage; monitor output; remove when <100 mL/day drainage

26. ARDS (Acute Respiratory Distress Syndrome)

  • Non-cardiogenic pulmonary edema from inflammatory lung injury
  • Causes: Sepsis, trauma, aspiration, pancreatitis
  • Criteria (Berlin): Bilateral opacities, PaO2/FiO2 <300, within 1 week of insult
  • Rx: Lung-protective ventilation (low tidal volume 6 mL/kg), prone positioning, supportive care

27. Stiff Lung (Pulmonary Fibrosis)

  • Progressive fibrotic scarring of lungs; restrictive pattern on PFTs
  • Causes: IPF, sarcoidosis, hypersensitivity pneumonitis, post-ARDS
  • Rx: Antifibrotics (pirfenidone, nintedanib); lung transplant in advanced disease

28. Pulmonary Embolism

  • Thrombus (usually from DVT) lodges in pulmonary artery
  • Features: Sudden dyspnoea, pleuritic chest pain, haemoptysis, tachycardia
  • Dx: CTPA (gold standard); D-dimer (sensitive, not specific); V/Q scan
  • Rx: Anticoagulation (LMWH/DOAC); thrombolysis for massive PE; embolectomy rarely

29. Lung Cyst

  • Congenital (bronchogenic cyst) or acquired; may cause recurrent infections or tension
  • Rx: Surgical excision if symptomatic

30. Mediastinal/Chest Wall Tumors & Pancoast Tumor

  • Pancoast (Superior Sulcus) Tumor: Apical lung cancer
    • Features: Shoulder/arm pain, Horner's syndrome (ptosis, miosis, anhidrosis), rib erosion
    • Rx: Chemoradiation + surgery
  • Mediastinal masses (4 Ts): Thymoma (ant.), Teratoma (ant.), Thyroid (ant.), Terrible lymphoma (post.)

31. Diaphragmatic Hernia

  • Congenital (Bochdalek): Left posterolateral; bowel in chest; respiratory distress at birth
  • Hiatus hernia: Sliding (most common) or paraesophageal; GERD symptoms
  • Traumatic: Left sided more common; bowel loops visible on CXR above diaphragm
  • Rx: Surgical repair

32. Cardiac Tamponade

  • Fluid in pericardial sac compressing heart → ↓ cardiac output
  • Beck's triad: Hypotension + raised JVP + muffled heart sounds
  • Dx: ECG (electrical alternans), echocardiogram
  • Rx: Emergency pericardiocentesis

33. Pericarditis

  • Inflammation of pericardium; sharp chest pain relieved by leaning forward
  • ECG: Diffuse saddle-shaped ST elevation; PR depression
  • Rx: NSAIDs + colchicine; drain if large effusion

34. Valvular Heart Disease (mentioned in notes)

  • Surgical relevance: Aortic stenosis, mitral regurgitation
  • Rx: Valve repair or replacement (open or TAVI for aortic)

🔴 RENAL & UROLOGICAL SURGERY

35. Haematuria

  • Blood in urine; frank (visible) or microscopic
  • Causes (surgical): Stones, TCC, RCC, infections, trauma
  • Initial Dx: Urine microscopy, USG, CT urogram, cystoscopy
  • Horseshoe kidney is associated with increased risk of haematuria and infections

36. Horseshoe Kidney

  • Fusion of lower poles of both kidneys across midline (most common renal fusion anomaly)
  • Associated with VUJ obstruction, recurrent infections, stones, Wilms tumor risk
  • Usually an incidental finding; treat complications

37. PCKD (Polycystic Kidney Disease)

  • ADPKD (Adult): Chromosome 16 (PKD1); bilateral multiple cysts; hypertension, flank pain, haematuria; associated with berry aneurysms; CRF in 5th decade
  • ARPKD (Childhood): Rare; presents at birth; poor prognosis
  • Rx: BP control, manage complications; renal transplant for ESRD

38. Renal Carbuncle

  • Cortical abscess; usually haematogenous spread from skin (S. aureus) or UTI
  • Features: Fever, flank pain; CT confirms abscess
  • Rx: IV antibiotics; percutaneous drainage if >3 cm

39. Renal TB

  • Haematogenous spread from primary lung focus; most common cause of sterile pyuria
  • Features: Frequency, dysuria, haematuria, "putty kidney" (calcification on XR)
  • Dx: Morning urine AFB x3, culture; CT IVU
  • Rx: ATT (6-9 months); surgery for obstructive complications

40. Hydronephrosis

  • Dilatation of renal pelvis and calyces due to obstruction
  • Causes: PUJ obstruction, stones, BPH, stricture, tumour
  • Features: Loin pain; may be asymptomatic; reduced renal function
  • Dx: USG (first line); CT/IVU; MAG3 renogram for functional assessment
  • Rx: Relieve obstruction; pyeloplasty for PUJ

41. Pyonephrosis

  • Infected hydronephrosis with suppurative destruction of renal parenchyma; nearly total loss of function
  • Features: Very ill patient; high fever, chills, severe flank pain
  • Dx: USG (fluid-debris levels), CT
  • Rx: Emergency decompression (percutaneous nephrostomy) + IV antibiotics; later nephrectomy if kidney non-functional
  • Campbell Walsh Wein Urology

42. Perinephric Abscess

  • Abscess extending beyond renal capsule, within Gerota's fascia
  • Causes: Rupture of cortical abscess, infected urine, hematogenous (E. coli, Proteus, S. aureus); DM in 1/3 patients
  • Features: Fever >5 days, flank mass, CVAT; psoas abscess = hip flexion deformity
  • Dx: CT (gold standard); USG
  • Rx: IV antibiotics + CT-guided percutaneous drainage or open surgical drainage
  • Campbell Walsh Wein Urology

43. Renal Calculus (Nephrolithiasis)

  • Types: Calcium oxalate (most common), uric acid, struvite, cystine
  • Features: Renal colic (loin to groin), haematuria, CVAT
  • Dx: Non-contrast CT KUB (gold standard); USG; XR KUB
  • Rx: Analgesia (diclofenac); <5 mm pass spontaneously; ESWL/URS/PCNL based on size/location

44. Wilms Tumor (Nephroblastoma)

  • Most common renal malignancy of childhood (peak 3-4 years)
  • Associated syndromes: WAGR, Beckwith-Wiedemann, Denys-Drash (all with WT1 gene)
  • Components: Blastemal, epithelial, stromal (triphasic histology)
  • Features: Abdominal mass (crosses midline), haematuria; CT for staging
  • Rx: Nephrectomy + chemotherapy (vincristine, actinomycin D); excellent prognosis (>85%)
  • Robbins & Kumar Basic Pathology, Sabiston Textbook of Surgery

45. Grawitz Tumor (Renal Cell Carcinoma)

  • Most common adult renal malignancy; arises from proximal tubular cells
  • Classic triad: Haematuria + flank pain + palpable mass (only 10% present with all three)
  • Paraneoplastic: Polycythaemia, hypercalcaemia, hypertension
  • Associated with VHL gene mutation
  • Rx: Radical nephrectomy; targeted therapy (sunitinib) for metastatic disease

46. Hydronephrosis + Hydroureter

  • See #40 above; add ureteric cause (stone, stricture, external compression by tumour/lymph nodes)

47. Pyonephrosis (repeated see #41)


Summary Table

SystemKey Topics
LiverAmoebic abscess, Pyogenic abscess, Hydatid cyst, Actinomycosis, Hepatomegaly
BiliaryGallstone, Cholecystitis, Ca. GB, Jaundice
SpleenSplenomegaly, Splenic artery aneurysm, Infarct, Cyst
PancreasPancreatitis (acute/chronic), Ca. Pancreas, Pseudocyst, Abscess
ThoraxPneumothorax, Hemothorax, Pleural effusion, Lung abscess, ICD, Diaphragmatic hernia, PE, ARDS, Flail chest, Pancoast tumor
HeartCardiac tamponade, Pericarditis, Valvular disease
KidneyHaematuria, Horseshoe kidney, PCKD, Renal carbuncle, Renal TB, Hydronephrosis, Pyonephrosis, Perinephric abscess, Renal calculus
Renal TumorsWilms tumor (child), Grawitz/RCC (adult)

All information drawn from Sabiston Textbook of Surgery, Bailey and Love's Surgery, Campbell Walsh Wein Urology, Robbins & Kumar Basic Pathology, and Mulholland & Greenfield's Surgery.

Create a quick reference PDF of surgical indications and treatments for each topic

Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null && mkdir -p /home/daytona/workspace/surg…

Writing File

~/surgery-pdf/create_surgery_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, KeepTogether, PageBreak
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.pdfgen import canvas
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from reportlab.platypus.frames import Frame

OUTPUT = "/home/daytona/workspace/surgery-pdf/Surgery_Quick_Reference.pdf"

# ── Color palette ──────────────────────────────────────────────────────────────
C_HEADER    = colors.HexColor("#1A3C5E")   # Deep navy
C_SUBHEAD   = colors.HexColor("#2E7DBF")   # Steel blue
C_ACCENT    = colors.HexColor("#E8502A")   # Surgical red-orange
C_GOLD      = colors.HexColor("#D4A017")   # Gold for highlights
C_BG_LIGHT  = colors.HexColor("#EEF4FA")   # Light blue bg
C_BG_ORANGE = colors.HexColor("#FFF3EB")   # Light orange bg
C_ROW_ALT   = colors.HexColor("#F7F9FC")   # Table alt row
C_WHITE     = colors.white
C_DARK      = colors.HexColor("#1C1C1C")
C_GRAY      = colors.HexColor("#666666")
C_DIVIDER   = colors.HexColor("#CCDDEE")

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

def make_style(name, parent_name="Normal", **kwargs):
    base = styles[parent_name]
    return ParagraphStyle(name, parent=base, **kwargs)

TITLE_STYLE = make_style("DocTitle", fontSize=26, textColor=C_WHITE,
    alignment=TA_CENTER, fontName="Helvetica-Bold", spaceAfter=4)

SUBTITLE_STYLE = make_style("DocSubtitle", fontSize=11, textColor=colors.HexColor("#BBDDFF"),
    alignment=TA_CENTER, fontName="Helvetica", spaceAfter=2)

SECTION_STYLE = make_style("Section", fontSize=13, textColor=C_WHITE,
    fontName="Helvetica-Bold", spaceBefore=4, spaceAfter=4,
    leftIndent=0, leading=16)

TOPIC_STYLE = make_style("Topic", fontSize=10.5, textColor=C_HEADER,
    fontName="Helvetica-Bold", spaceBefore=8, spaceAfter=2, leading=14)

BODY_STYLE = make_style("Body", fontSize=9, textColor=C_DARK,
    fontName="Helvetica", spaceAfter=2, leading=12, alignment=TA_JUSTIFY)

BULLET_STYLE = make_style("Bullet", fontSize=9, textColor=C_DARK,
    fontName="Helvetica", leftIndent=12, spaceAfter=1, leading=12,
    bulletIndent=4)

LABEL_STYLE = make_style("Label", fontSize=8.5, textColor=C_ACCENT,
    fontName="Helvetica-Bold", spaceAfter=0, leading=11)

FOOTER_STYLE = make_style("Footer", fontSize=7.5, textColor=C_GRAY,
    alignment=TA_CENTER, fontName="Helvetica-Oblique")

# ── Page numbering ─────────────────────────────────────────────────────────────
class NumberedCanvas(canvas.Canvas):
    def __init__(self, *args, **kwargs):
        canvas.Canvas.__init__(self, *args, **kwargs)
        self._saved_page_states = []

    def showPage(self):
        self._saved_page_states.append(dict(self.__dict__))
        self._startPage()

    def save(self):
        num_pages = len(self._saved_page_states)
        for state in self._saved_page_states:
            self.__dict__.update(state)
            self.draw_page_number(num_pages)
            canvas.Canvas.showPage(self)
        canvas.Canvas.save(self)

    def draw_page_number(self, page_count):
        if self._pageNumber == 1:
            return
        self.saveState()
        self.setFont("Helvetica", 7.5)
        self.setFillColor(C_GRAY)
        self.drawCentredString(A4[0]/2, 18*mm,
            f"Surgery Quick Reference  •  Page {self._pageNumber} of {page_count}")
        self.setStrokeColor(C_DIVIDER)
        self.setLineWidth(0.5)
        self.line(20*mm, 22*mm, A4[0]-20*mm, 22*mm)
        self.restoreState()

# ── Document ───────────────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=18*mm, rightMargin=18*mm,
    topMargin=18*mm, bottomMargin=28*mm,
    title="Surgery Quick Reference",
    author="Orris Medical AI"
)

story = []
W = A4[0] - 36*mm  # usable width

# ── Helper functions ───────────────────────────────────────────────────────────
def section_banner(text, color=C_HEADER):
    tbl = Table([[Paragraph(text, SECTION_STYLE)]], colWidths=[W])
    tbl.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), color),
        ("TOPPADDING",    (0,0), (-1,-1), 6),
        ("BOTTOMPADDING", (0,0), (-1,-1), 6),
        ("LEFTPADDING",   (0,0), (-1,-1), 10),
        ("RIGHTPADDING",  (0,0), (-1,-1), 10),
        ("ROUNDEDCORNERS", [4]),
    ]))
    return tbl

def topic_card(number, name, indication_lines, treatment_lines, bg=C_WHITE):
    """Build a 2-column card: Indications | Treatment"""
    ind_content = [Paragraph(f"<b><font color='#{C_ACCENT.hexval()[2:]}'>Indications</font></b>", LABEL_STYLE)]
    for line in indication_lines:
        ind_content.append(Paragraph(f"• {line}", BULLET_STYLE))

    tx_content = [Paragraph(f"<b><font color='#{C_SUBHEAD.hexval()[2:]}'>Treatment</font></b>", LABEL_STYLE)]
    for line in treatment_lines:
        tx_content.append(Paragraph(f"• {line}", BULLET_STYLE))

    header_p = Paragraph(f"<b>{number}. {name}</b>", TOPIC_STYLE)

    # inner 2-col table
    inner = Table(
        [[ind_content, tx_content]],
        colWidths=[W*0.47, W*0.47],
        hAlign="LEFT"
    )
    inner.setStyle(TableStyle([
        ("VALIGN",       (0,0), (-1,-1), "TOP"),
        ("LEFTPADDING",  (0,0), (-1,-1), 6),
        ("RIGHTPADDING", (0,0), (-1,-1), 6),
        ("TOPPADDING",   (0,0), (-1,-1), 4),
        ("BOTTOMPADDING",(0,0), (-1,-1), 4),
        ("BACKGROUND",   (0,0), (0,0), C_BG_LIGHT),
        ("BACKGROUND",   (1,0), (1,0), C_BG_ORANGE),
        ("BOX",          (0,0), (0,0), 0.4, C_DIVIDER),
        ("BOX",          (1,0), (1,0), 0.4, C_DIVIDER),
        ("ROUNDEDCORNERS", [3]),
    ]))

    outer = Table(
        [[header_p], [inner]],
        colWidths=[W],
        hAlign="LEFT"
    )
    outer.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (0,0), C_WHITE),
        ("TOPPADDING",   (0,0), (-1,-1), 2),
        ("BOTTOMPADDING",(0,0), (-1,-1), 2),
        ("LEFTPADDING",  (0,0), (-1,-1), 0),
        ("RIGHTPADDING", (0,0), (-1,-1), 0),
        ("BOX",          (0,0), (-1,-1), 0.6, C_DIVIDER),
        ("LINEBELOW",    (0,0), (0,0), 0.4, C_SUBHEAD),
    ]))
    return KeepTogether([outer, Spacer(1, 4)])

# ══════════════════════════════════════════════════════════════════════════════
# COVER PAGE
# ══════════════════════════════════════════════════════════════════════════════
cover_bg = Table(
    [[Paragraph("SURGERY", make_style("CoverBig", fontSize=42,
                textColor=C_WHITE, fontName="Helvetica-Bold", alignment=TA_CENTER)),
      ]],
    colWidths=[W]
)
cover_tbl = Table(
    [[
        Paragraph("SURGERY", make_style("CvrH", fontSize=40, textColor=C_WHITE,
                  fontName="Helvetica-Bold", alignment=TA_CENTER, spaceAfter=6)),
    ]],
    colWidths=[W]
)
cover_tbl.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(-1,-1), C_HEADER),
    ("TOPPADDING", (0,0),(-1,-1), 30),
    ("BOTTOMPADDING",(0,0),(-1,-1), 10),
]))

cover_sub = Table(
    [[
        Paragraph("Quick Reference: Surgical Indications & Treatments",
                  make_style("CvrS", fontSize=14, textColor=C_WHITE,
                             fontName="Helvetica-Bold", alignment=TA_CENTER)),
    ]],
    colWidths=[W]
)
cover_sub.setStyle(TableStyle([
    ("BACKGROUND", (0,0),(-1,-1), C_SUBHEAD),
    ("TOPPADDING", (0,0),(-1,-1), 12),
    ("BOTTOMPADDING",(0,0),(-1,-1), 12),
]))

cover_topics = Table(
    [[
        Paragraph("47 Topics  •  Hepatobiliary  •  Spleen  •  Pancreas  •  Thorax  •  Renal & Urological",
                  make_style("CvrT", fontSize=9.5, textColor=C_GRAY,
                             alignment=TA_CENTER, fontName="Helvetica")),
    ]],
    colWidths=[W]
)
cover_topics.setStyle(TableStyle([
    ("TOPPADDING", (0,0),(-1,-1), 10),
    ("BOTTOMPADDING",(0,0),(-1,-1), 10),
    ("BOX", (0,0),(-1,-1), 0.5, C_DIVIDER),
]))

story += [
    cover_tbl,
    cover_sub,
    Spacer(1, 12),
    cover_topics,
    Spacer(1, 10),
    Paragraph("Based on: Sabiston • Bailey & Love • Campbell Walsh Wein • Robbins & Kumar",
              make_style("CvrRef", fontSize=8, textColor=C_GRAY, alignment=TA_CENTER)),
    PageBreak()
]

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 1 — HEPATOBILIARY
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_banner("🔶  SECTION 1: HEPATOBILIARY SYSTEM", C_HEADER))
story.append(Spacer(1, 6))

topics_hepato = [
    (1, "Hepatomegaly", 
     ["Symptomatic hepatomegaly (pain, abdominal distension)",
      "Unexplained hepatomegaly requiring tissue diagnosis",
      "Hepatomegaly with obstructive features"],
     ["Treat underlying cause (abscess drainage, antivirals, diuretics)",
      "Ultrasound-guided liver biopsy if cause unclear",
      "Surgical decompression if obstructive cause"]),

    (2, "Amoebic Liver Abscess",
     ["Single large abscess with positive serology",
      "No response to metronidazole after 5-7 days",
      "Risk of rupture (>10 cm, left lobe, thin wall)"],
     ["Metronidazole 800 mg TDS × 7-10 days (first line)",
      "Aspiration if no response, large cyst, or risk of rupture",
      "Open drainage rarely needed (rupture, secondary infection)"]),

    (3, "Pyogenic Liver Abscess",
     ["Confirmed hepatic abscess on imaging",
      "Failed conservative management",
      "Multiple abscesses or underlying biliary pathology"],
     ["IV antibiotics (ceftriaxone + metronidazole)",
      "Percutaneous drainage (CT/USG-guided) - first line",
      "Open surgical drainage if percutaneous fails or biliary source",
      "ERCP/biliary stenting for biliary obstruction"]),

    (4, "Hydatid Cyst (Liver)",
     ["Symptomatic cyst or cyst >5 cm",
      "Complicated cyst (infected, rupture risk, biliary communication)",
      "Failed medical therapy"],
     ["Albendazole 400 mg BD × 1 month pre-op (sterilizes cyst)",
      "PAIR procedure (Puncture-Aspiration-Injection-Reaspiration)",
      "Surgical: cystectomy or pericystectomy if complicated",
      "Scolicidal agents injected intra-operatively (hypertonic saline)"]),

    (5, "Actinomycosis (Hepatic)",
     ["Hepatic abscess with sinus tracts, sulfur granules",
      "Failure to respond to standard antibiotics"],
     ["Prolonged penicillin G IV × 4-6 weeks, then oral amoxicillin × 6-12 months",
      "Surgical drainage of abscess + excision of sinus tracts"]),
]

for t in topics_hepato:
    story.append(topic_card(*t))

story.append(Spacer(1, 6))
story.append(section_banner("🔶  BILIARY SYSTEM", C_SUBHEAD))
story.append(Spacer(1, 6))

topics_biliary = [
    (6, "Gallstone Disease (Cholelithiasis)",
     ["Symptomatic gallstones (biliary colic)",
      "Acute cholecystitis, empyema, Mirizzi syndrome",
      "Gallstone pancreatitis; Ca. GB association"],
     ["Laparoscopic cholecystectomy (gold standard)",
      "ERCP + sphincterotomy for CBD stones (choledocholithiasis)",
      "Open cholecystectomy if laparoscopic not feasible",
      "Ursodeoxycholic acid for medical dissolution (selected cases)"]),

    (7, "Cholecystitis (Acute)",
     ["Acute cholecystitis confirmed on USG (Murphy's sign +ve, thickened GB wall)",
      "Empyema, perforation, or Mirizzi syndrome",
      "Failure to improve with conservative treatment"],
     ["Early laparoscopic cholecystectomy within 72 hrs (preferred)",
      "IV antibiotics (cefuroxime + metronidazole) for 24-48 hrs pre-op",
      "Percutaneous cholecystostomy if unfit for surgery",
      "Interval cholecystectomy after 6 weeks if delayed"]),

    (8, "Ca. Gallbladder",
     ["Incidental finding post-cholecystectomy (T1b or higher)",
      "Pre-op suspected or confirmed Ca. GB with resectable disease",
      "Obstructive jaundice from Ca. GB"],
     ["T1a: Cholecystectomy alone",
      "T1b-T3: Extended cholecystectomy (liver bed resection + lymphadenectomy)",
      "ERCP stenting for palliative jaundice relief",
      "Gemcitabine + cisplatin for unresectable/metastatic disease"]),

    (9, "Jaundice (Obstructive/Surgical)",
     ["Obstructive jaundice with bile duct stones",
      "Malignant obstruction (Ca. head of pancreas, cholangiocarcinoma)",
      "Biliary stricture post-surgery or injury"],
     ["ERCP + stone extraction / sphincterotomy for choledocholithiasis",
      "Whipple's operation for resectable periampullary Ca.",
      "Biliary bypass (hepaticojejunostomy) for benign stricture",
      "ERCP/PTC stenting for malignant obstruction (palliative)",
      "Pre-operative biliary drainage if bilirubin >250 μmol/L"]),
]

for t in topics_biliary:
    story.append(topic_card(*t))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 2 — SPLEEN
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("🟣  SECTION 2: SPLEEN", C_HEADER))
story.append(Spacer(1, 6))

topics_spleen = [
    (10, "Splenomegaly",
     ["Massive splenomegaly with hypersplenism (pancytopenia)",
      "Splenic vein thrombosis with portal hypertension",
      "Trauma to enlarged spleen"],
     ["Treat underlying cause (anti-malarials, chemotherapy, etc.)",
      "Splenectomy for symptomatic hypersplenism",
      "Pre-op vaccinations mandatory: pneumococcus, Hib, meningococcus",
      "Post-splenectomy: prophylactic penicillin V lifelong"]),

    (11, "Splenic Artery Aneurysm",
     ["Aneurysm >2 cm in any patient",
      "Any size aneurysm in pregnant women or women of childbearing age",
      "Symptomatic aneurysm (pain, rupture)"],
     ["Endovascular embolization or stenting (preferred, minimally invasive)",
      "Open ligation + splenectomy if endovascular not feasible",
      "Emergency laparotomy + splenectomy for rupture",
      "Observation with serial imaging for elderly with calcified aneurysm <2 cm"]),

    (12, "Splenic Infarct",
     ["Symptomatic infarct with persistent pain",
      "Septic infarct forming abscess"],
     ["Conservative: analgesia, anticoagulation (if thromboembolic cause)",
      "Splenectomy only for septic infarct/abscess formation"]),

    (13, "Cyst of Spleen",
     ["Symptomatic cyst (pain, early satiety)",
      "Cyst >5 cm or rapidly growing",
      "Parasitic hydatid cyst of spleen"],
     ["Laparoscopic partial splenectomy or cyst excision (preferred)",
      "Total splenectomy if cyst involves most of spleen",
      "Albendazole + surgery for hydatid cyst",
      "Observation for small asymptomatic true cysts"]),
]

for t in topics_spleen:
    story.append(topic_card(*t))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 3 — PANCREAS
# ══════════════════════════════════════════════════════════════════════════════
story.append(Spacer(1, 6))
story.append(section_banner("🟠  SECTION 3: PANCREAS", C_HEADER))
story.append(Spacer(1, 6))

topics_pancreas = [
    (14, "Acute Pancreatitis",
     ["Biliary pancreatitis (gallstones in CBD)",
      "Severe pancreatitis with necrosis (infected pancreatic necrosis)",
      "Failure of conservative management, abdominal compartment syndrome"],
     ["IV fluids, analgesia (opioids), NBM initially",
      "Early enteral nutrition within 48 hrs (nasojejunal if needed)",
      "ERCP within 72 hrs for biliary cause",
      "IV antibiotics (carbapenems) only for infected necrosis",
      "Step-up approach: percutaneous drain → endoscopic necrosectomy → surgery"]),

    (15, "Chronic Pancreatitis",
     ["Intractable pain not responding to medical therapy",
      "Pancreatic duct dilatation >7 mm (chain of lakes)",
      "Biliary or duodenal obstruction; pseudocyst; suspicion of malignancy"],
     ["Low-fat diet + pancreatic enzyme supplementation + fat-soluble vitamins",
      "ERCP + stenting for duct decompression (first line interventional)",
      "Puestow procedure (lateral pancreaticojejunostomy) for dilated duct",
      "Whipple's or Beger procedure for head-predominant disease",
      "Total pancreatectomy + islet autotransplantation (last resort)"]),

    (16, "Ca. Pancreas",
     ["Resectable tumor (no vascular invasion, no distant mets)",
      "Obstructive jaundice requiring palliation",
      "Gastric outlet obstruction from tumor"],
     ["Whipple's operation (pancreaticoduodenectomy) - only curative option",
      "Distal pancreatectomy for body/tail tumors",
      "ERCP stenting for palliative jaundice",
      "Gastrojejunostomy for gastric outlet obstruction",
      "Gemcitabine + nab-paclitaxel for unresectable/adjuvant chemotherapy"]),

    (17, "Pancreatic Abscess",
     ["Infected walled-off necrosis (WON) on CT",
      "Clinical deterioration despite antibiotics",
      "Gas bubbles on CT (pathognomonic of infection)"],
     ["IV antibiotics (carbapenems) as bridge",
      "Endoscopic transgastric drainage (preferred for retrogastric WON)",
      "Percutaneous CT-guided drainage for peripheral collections",
      "Video-assisted retroperitoneal debridement (VARD) if endoscopy fails",
      "Open necrosectomy only as last resort"]),

    (18, "Pancreatic Pseudocyst / Fistula / Cyst",
     ["Pseudocyst >6 cm persisting >6 weeks with symptoms",
      "Pancreatic fistula with ductal disruption",
      "External fistula with persistent drainage"],
     ["Endoscopic cystogastrostomy (first line for pseudocyst)",
      "EUS-guided drainage with lumen-apposing stent",
      "Octreotide + TPN for pancreatic fistula",
      "ERCP stenting across disruption for fistula",
      "Surgical internal drainage (Roux-en-Y) if endoscopy fails"]),
]

for t in topics_pancreas:
    story.append(topic_card(*t))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 4 — THORACIC SURGERY
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("🔵  SECTION 4: THORACIC SURGERY", C_HEADER))
story.append(Spacer(1, 6))

topics_thorax = [
    (19, "Pneumothorax",
     ["Spontaneous pneumothorax >2 cm rim (BTS criteria) or symptomatic",
      "Tension pneumothorax (any size - emergency)",
      "Traumatic pneumothorax; bilateral pneumothorax"],
     ["Tension: Immediate needle decompression 2nd ICS MCL → ICD",
      "Large/symptomatic: ICD at 5th ICS anterior axillary line (safe triangle)",
      "Small/stable: Aspiration or observation + O2",
      "Recurrent: Video-assisted thoracoscopic surgery (VATS) + pleurodesis"]),

    (20, "Pleural Effusion & Tapping",
     ["Large effusion causing respiratory compromise",
      "Diagnostic uncertainty (exudate vs transudate - Light's criteria)",
      "Parapneumonic effusion or empyema"],
     ["Therapeutic aspiration (thoracocentesis): 8-9th ICS, post-axillary line",
      "ICD for parapneumonic effusion / empyema",
      "Intrapleural fibrinolytics (streptokinase) for loculated empyema",
      "VATS decortication for stage III empyema (organized)"]),

    (21, "Hemothorax",
     ["Traumatic hemothorax with respiratory compromise",
      "Massive hemothorax (>1.5 L)",
      "Ongoing blood loss >200 mL/hr for 2-4 hrs via chest drain"],
     ["ICD: 5th ICS, anterior axillary line (large-bore 28-32 Fr)",
      "IV fluid resuscitation + blood transfusion",
      "Emergency thoracotomy: if >1.5 L immediate drainage OR ongoing >200 mL/hr",
      "VATS for retained hemothorax after 5-7 days"]),

    (22, "Bronchoscopy (Indications)",
     ["Haemoptysis (all causes require bronchoscopy)",
      "Suspected endobronchial lesion / foreign body",
      "Persistent collapse, atelectasis, or lobar obstruction",
      "Pre-operative staging of lung cancer"],
     ["Flexible bronchoscopy: diagnosis, BAL, biopsy, suction",
      "Rigid bronchoscopy: foreign body removal, massive haemoptysis, stenting",
      "Endobronchial valve placement for air leak / emphysema",
      "Endobronchial ultrasound (EBUS) for mediastinal lymph node sampling"]),

    (23, "Flail Chest / Stove-In Chest",
     ["Flail chest with respiratory failure (PaO2 <60 mmHg)",
      "Significant pulmonary contusion underlying flail segment",
      "Refractory respiratory failure despite analgesia"],
     ["Adequate analgesia: epidural / intercostal nerve blocks (first priority)",
      "IPPV / mechanical ventilation for respiratory failure",
      "Surgical rib fixation (ORIF) for refractory cases or planned thoracotomy",
      "Monitor for pneumothorax, haemothorax"]),

    (24, "Lung Abscess",
     ["Failure of antibiotic therapy after 6 weeks",
      "Abscess >6 cm or rapidly enlarging",
      "Underlying bronchial obstruction (drain endobronchial cause)",
      "Rupture into pleural space (pyopneumothorax)"],
     ["IV antibiotics 4-6 weeks: penicillin/amoxicillin + metronidazole",
      "Postural drainage + chest physiotherapy",
      "CT-guided percutaneous drainage for peripheral large abscess",
      "Lobectomy/pneumonectomy for chronic abscess not responding to treatment"]),

    (25, "Intercostal Tube Drainage (ICD)",
     ["Pneumothorax >2 cm or tension pneumothorax",
      "Haemothorax, empyema, malignant effusion",
      "Post-operative pleural collections"],
     ["Site: 5th ICS, anterior axillary line (safe triangle) for fluid",
      "2nd ICS midclavicular line for pneumothorax (or same safe triangle)",
     "Blunt dissection above upper border of rib (avoid neurovascular bundle below)",
      "Underwater seal drainage; remove when <100 mL/day + lung fully expanded"]),

    (26, "ARDS",
     ["PaO2/FiO2 <300 mmHg with bilateral infiltrates (Berlin criteria)",
      "Refractory hypoxaemia despite standard ventilation",
      "Severe ARDS (PaO2/FiO2 <100): consider ECMO"],
     ["Lung-protective ventilation: Vt 6 mL/kg IBW, Pplat <30 cmH2O",
      "Prone positioning >16 hrs/day for moderate-severe ARDS",
      "PEEP titration to improve oxygenation",
      "Conservative fluid strategy after resuscitation",
      "ECMO for refractory cases in specialized centres"]),

    (27, "Pulmonary Embolism",
     ["Confirmed PE on CTPA with haemodynamic instability (massive PE)",
      "Sub-massive PE with RV dysfunction and contraindication to thrombolysis",
      "Chronic thromboembolic pulmonary hypertension (CTEPH)"],
     ["Massive PE: Systemic thrombolysis (alteplase 100 mg IV) if no CI",
      "Anticoagulation: LMWH/DOAC for 3-6 months minimum",
      "Catheter-directed thrombolysis for sub-massive PE",
      "Surgical embolectomy if thrombolysis contraindicated/failed",
      "Pulmonary endarterectomy for CTEPH"]),

    (28, "Diaphragmatic Hernia",
     ["Congenital (Bochdalek): neonatal respiratory distress",
      "Traumatic diaphragmatic rupture (blunt or penetrating)",
      "Symptomatic hiatus hernia with complications (Barrett's, stricture, volvulus)"],
     ["Congenital: Delayed repair after lung maturation; patch repair",
      "Traumatic: Urgent surgical repair via laparotomy or VATS",
      "Hiatus: Laparoscopic Nissen fundoplication (sliding); repair for paraesophageal",
      "Reduce herniated contents; close defect ± mesh reinforcement"]),

    (29, "Cardiac Tamponade",
     ["Haemodynamic compromise (Beck's triad: hypotension + raised JVP + muffled HS)",
      "Pulsus paradoxus >10 mmHg",
      "Traumatic haemopericardium"],
     ["Emergency pericardiocentesis (subxiphoid approach, echo-guided)",
      "Surgical pericardial window for recurrent or loculated effusion",
      "Emergency thoracotomy / sternotomy for traumatic tamponade",
      "Treat underlying cause (malignancy → pericardial drain, chemotherapy)"]),

    (30, "Pancoast Tumor (Superior Sulcus)",
     ["Resectable Pancoast/superior sulcus tumor (T3/T4 N0-N1)",
      "Pain control requiring surgical intervention",
      "Diagnostic doubt (tissue biopsy needed)"],
     ["Concurrent chemoradiation (cisplatin + etoposide + radiotherapy) followed by surgery",
      "Surgical resection: en bloc resection of lung + chest wall + ribs ± vertebrae",
      "Palliative RT for pain if unresectable",
      "Horner's syndrome indicates stellate ganglion involvement"]),
]

for t in topics_thorax:
    story.append(topic_card(*t))

# ══════════════════════════════════════════════════════════════════════════════
# SECTION 5 — RENAL & UROLOGICAL
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("🔴  SECTION 5: RENAL & UROLOGICAL SURGERY", C_HEADER))
story.append(Spacer(1, 6))

topics_renal = [
    (31, "Haematuria (Frank)",
     ["All adults with unexplained frank haematuria (urgent cystoscopy)",
      "Recurrent microscopic haematuria >3 RBC/HPF",
      "Haematuria with obstructive symptoms"],
     ["CT urogram (gold standard for upper tract evaluation)",
      "Flexible cystoscopy (mandatory for all adults - rule out bladder Ca.)",
      "Urine cytology for transitional cell carcinoma",
      "Treat underlying cause: stone (ESWL/URS), tumor (surgery), infection (antibiotics)"]),

    (32, "Horseshoe Kidney",
     ["Recurrent UTIs due to stasis",
      "PUJ obstruction with hydronephrosis",
      "Stone formation in horseshoe kidney"],
     ["Conservative if asymptomatic",
      "Pyeloplasty for PUJ obstruction",
      "PCNL/ESWL for stones (modified approach due to anatomy)",
      "Antibiotics for recurrent UTI"]),

    (33, "PCKD (Polycystic Kidney Disease)",
     ["Infected cysts not responding to antibiotics",
      "Cyst haemorrhage causing severe pain",
      "End-stage renal failure"],
     ["Aggressive BP control (ACE inhibitors/ARBs - reduce progression)",
      "Tolvaptan (vasopressin antagonist) - slows cyst growth in ADPKD",
      "Cyst aspiration/sclerotherapy for infected or haemorrhagic cysts",
      "Renal replacement therapy / kidney transplant for ESRD",
      "Screen family members; manage intracranial aneurysms (berry aneurysms)"]),

    (34, "Renal Carbuncle",
     ["Renal cortical abscess >3 cm",
      "Failed antibiotic therapy (no improvement in 48 hrs)",
      "Abscess extending to perinephric space"],
     ["IV antibiotics: anti-staphylococcal (flucloxacillin/vancomycin for MRSA)",
      "CT-guided percutaneous drainage for abscess >3 cm",
      "Open surgical drainage rarely needed",
      "Treat predisposing conditions (DM control, remove infected lines)"]),

    (35, "Renal TB",
     ["Confirmed renal TB (positive AFB culture/PCR)",
      "Stricture causing hydronephrosis",
      "Non-functioning kidney (autonephrectomy)"],
     ["ATT regimen: HRZE × 2 months → HR × 4 months (total 6 months)",
      "Ureteric stricture: regular JJ stenting during treatment",
      "Nephroureterectomy for non-functioning TB kidney with symptoms",
      "Balloon dilatation / endoureterotomy for ureteric strictures post-ATT"]),

    (36, "Hydronephrosis",
     ["PUJ obstruction with symptoms (pain, recurrent UTI, stone, deteriorating function)",
      "Function <40% on MAG3 renogram in obstructed kidney",
      "Bilateral hydronephrosis causing renal failure"],
     ["PUJ obstruction: Laparoscopic/robotic pyeloplasty (Anderson-Hynes - gold standard)",
      "Stone causing obstruction: URS/PCNL/ESWL",
      "BPH causing bilateral hydronephrosis: TURP / catheterization",
      "Ureteric stent (JJ stent) as bridge to definitive surgery",
      "Nephrectomy for non-functioning hydronephrotic kidney"]),

    (37, "Pyonephrosis",
     ["All cases require urgent intervention (sepsis risk)",
      "Fever not settling on antibiotics",
      "Infected obstructed kidney"],
     ["Emergency percutaneous nephrostomy (USG-guided) - first line",
      "IV antibiotics (broad spectrum: piperacillin-tazobactam + gentamicin)",
      "JJ stent insertion if anatomy favourable",
      "Nephrectomy once stable if kidney is non-functional",
      "Identify and treat underlying obstruction (stone, stricture)"]),

    (38, "Perinephric Abscess",
     ["All confirmed perinephric abscesses require drainage",
      "Failed antibiotic therapy",
      "Abscess extending to flank or psoas"],
     ["CT-guided percutaneous drainage + IV antibiotics (first line)",
      "Broad-spectrum antibiotics: E. coli/Proteus coverage (+ antistaphylococcal)",
      "Open surgical drainage if percutaneous fails or multiloculated",
      "Identify and treat source (pyonephrosis, stone, fistula from bowel)"]),

    (39, "Renal Calculus",
     ["Renal colic with obstruction or infection (urological emergency)",
      "Stone >10 mm (unlikely to pass spontaneously)",
      "Bilateral stones or stone in solitary kidney"],
     ["Analgesia: diclofenac 75 mg IM / IV (first choice)",
      "<5 mm: watchful waiting + alpha-blockers (tamsulosin) for passage",
      "5-10 mm: Medical expulsive therapy or ESWL",
      "10-20 mm renal stone: ESWL or URS",
      ">20 mm or staghorn: PCNL (percutaneous nephrolithotomy)",
      "Emergency JJ stent/nephrostomy if infected obstructing stone"]),

    (40, "Wilms Tumor (Nephroblastoma)",
     ["All Wilms tumors regardless of size (curative intent)",
      "Bilateral Wilms tumor (stage V)",
      "Rupture, hemorrhage into tumor"],
     ["Unilateral: Radical nephroureterectomy + regional lymphadenectomy",
      "Bilateral: Pre-op chemotherapy (actinomycin D + vincristine) → nephron-sparing surgery",
      "Post-op chemotherapy: vincristine + actinomycin D (stages I-II)",
      "Add doxorubicin + RT for stages III-IV",
      "Prognosis excellent: >85% overall survival"]),

    (41, "Renal Cell Carcinoma (Grawitz Tumor)",
     ["Localized RCC (T1-T3): nephrectomy intent",
      "Solitary metastasis (lung, brain): resection + targeted therapy",
      "Symptomatic tumor (haematuria, pain, paraneoplastic)"],
     ["T1a (<4 cm): Partial nephrectomy (preferred; preserves function)",
      "T1b-T2: Radical nephrectomy (open or laparoscopic)",
      "T3-T4 / IVC thrombus: Open radical nephrectomy ± IVC thrombectomy",
      "Metastatic: Sunitinib or pazopanib (1st line targeted therapy)",
      "Immunotherapy: nivolumab + ipilimumab for metastatic disease"]),

    (42, "Hydroureter",
     ["Ureteric obstruction causing hydroureter + hydronephrosis",
      "Ureteric stricture post-radiation or surgery",
      "Extrinsic ureteric compression by tumor"],
     ["JJ stent insertion for acute obstruction",
      "Balloon dilatation + stenting for benign strictures",
      "Ureteric reimplantation (Boari flap / psoas hitch) for lower ureteric strictures",
      "Ileal ureteric substitution for long segment loss",
      "Palliative nephrostomy for malignant ureteric obstruction"]),
]

for t in topics_renal:
    story.append(topic_card(*t))

# ══════════════════════════════════════════════════════════════════════════════
# SUMMARY TABLE
# ══════════════════════════════════════════════════════════════════════════════
story.append(PageBreak())
story.append(section_banner("📋  SUMMARY: SURGICAL PROCEDURES AT A GLANCE", C_ACCENT))
story.append(Spacer(1, 8))

summary_data = [
    ["Condition", "Key Surgical Procedure", "Section"],
    ["Amoebic Liver Abscess", "Aspiration if no response to metronidazole", "Hepatobiliary"],
    ["Pyogenic Liver Abscess", "Percutaneous / open drainage + IV antibiotics", "Hepatobiliary"],
    ["Hydatid Cyst", "PAIR procedure / pericystectomy + albendazole", "Hepatobiliary"],
    ["Cholecystitis", "Laparoscopic cholecystectomy (early, <72 hrs)", "Biliary"],
    ["CBD Stones", "ERCP + sphincterotomy + stone extraction", "Biliary"],
    ["Ca. Gallbladder", "Extended cholecystectomy + lymphadenectomy", "Biliary"],
    ["Obstructive Jaundice", "ERCP stenting / Whipple's (Ca. pancreas)", "Biliary"],
    ["Splenomegaly / Hypersplenism", "Splenectomy (after vaccinations)", "Spleen"],
    ["Splenic Artery Aneurysm", "Endovascular embolization / stenting", "Spleen"],
    ["Acute Pancreatitis", "Step-up: drain → necrosectomy → surgery", "Pancreas"],
    ["Chronic Pancreatitis", "Puestow procedure / Whipple's", "Pancreas"],
    ["Ca. Pancreas", "Whipple's (pancreaticoduodenectomy)", "Pancreas"],
    ["Pancreatic Pseudocyst", "Endoscopic cystogastrostomy", "Pancreas"],
    ["Pneumothorax", "ICD at 5th ICS AAL / VATS for recurrence", "Thorax"],
    ["Hemothorax", "ICD (large-bore) / thoracotomy if massive", "Thorax"],
    ["Lung Abscess", "IV antibiotics 4-6 wks / CT-guided drainage", "Thorax"],
    ["ARDS", "Lung-protective ventilation + prone positioning", "Thorax"],
    ["Pulmonary Embolism", "Anticoagulation / thrombolysis / embolectomy", "Thorax"],
    ["Diaphragmatic Hernia", "Surgical repair (laparoscopic / open)", "Thorax"],
    ["Cardiac Tamponade", "Emergency pericardiocentesis / window", "Thorax"],
    ["Pancoast Tumor", "Chemoradiation → en-bloc resection", "Thorax"],
    ["Haematuria", "Cystoscopy + CT urogram + treat cause", "Renal"],
    ["Hydronephrosis", "Anderson-Hynes pyeloplasty / JJ stent", "Renal"],
    ["Pyonephrosis", "Emergency percutaneous nephrostomy", "Renal"],
    ["Perinephric Abscess", "CT-guided percutaneous drainage", "Renal"],
    ["Renal Calculus", "ESWL / URS / PCNL depending on size", "Renal"],
    ["Wilms Tumor", "Nephrectomy + vincristine + actinomycin D", "Renal"],
    ["Renal Cell Carcinoma", "Partial/radical nephrectomy / sunitinib (mets)", "Renal"],
    ["Renal TB", "ATT × 6 months + surgery for complications", "Renal"],
    ["PCKD / ESRD", "Renal transplant / tolvaptan for ADPKD", "Renal"],
]

col_widths = [W*0.40, W*0.42, W*0.18]
tbl = Table(summary_data, colWidths=col_widths, repeatRows=1)

tbl_style = [
    ("BACKGROUND",  (0,0), (-1,0), C_HEADER),
    ("TEXTCOLOR",   (0,0), (-1,0), C_WHITE),
    ("FONTNAME",    (0,0), (-1,0), "Helvetica-Bold"),
    ("FONTSIZE",    (0,0), (-1,0), 9),
    ("FONTSIZE",    (0,1), (-1,-1), 8.5),
    ("FONTNAME",    (0,1), (-1,-1), "Helvetica"),
    ("ROWBACKGROUNDS", (0,1), (-1,-1), [C_WHITE, C_ROW_ALT]),
    ("GRID",        (0,0), (-1,-1), 0.4, C_DIVIDER),
    ("TOPPADDING",  (0,0), (-1,-1), 5),
    ("BOTTOMPADDING",(0,0),(-1,-1), 5),
    ("LEFTPADDING", (0,0), (-1,-1), 6),
    ("RIGHTPADDING",(0,0), (-1,-1), 6),
    ("VALIGN",      (0,0), (-1,-1), "MIDDLE"),
    ("TEXTCOLOR",   (2,1), (2,-1), C_SUBHEAD),
    ("FONTNAME",    (2,1), (2,-1), "Helvetica-Oblique"),
]
tbl.setStyle(TableStyle(tbl_style))
story.append(tbl)

# ── Footer note ────────────────────────────────────────────────────────────────
story.append(Spacer(1, 12))
story.append(HRFlowable(width="100%", thickness=0.5, color=C_DIVIDER))
story.append(Spacer(1, 4))
story.append(Paragraph(
    "References: Sabiston Textbook of Surgery 21e • Bailey & Love's Short Practice of Surgery 28e • "
    "Campbell Walsh Wein Urology • Robbins & Kumar Basic Pathology • Mulholland & Greenfield's Surgery 7e",
    FOOTER_STYLE))
story.append(Paragraph(
    "This document is for educational/revision purposes. Always follow current institutional guidelines.",
    make_style("Disclaimer", fontSize=7, textColor=colors.HexColor("#999999"),
               alignment=TA_CENTER, fontName="Helvetica-Oblique")))

# ── Build ──────────────────────────────────────────────────────────────────────
doc.build(story, canvasmaker=NumberedCanvas)
print(f"PDF created: {OUTPUT}")
Your credits are exhausted. You can purchase a top-up or subscribe to a plan to continue using Orris. If you're already subscribed, your daily credits will reset tomorrow.
This is a shared conversation. Sign in to Orris to start your own chat.