make a detailed treatment drug dose duration of piles with every single case type with clear image type

Reading File
Finding Sources
Searching the Web

hemorrhoids piles treatment drug dose duration all grades 2024 guidelines

Searching PubMed

"hemorrhoids" AND "treatment" AND "management"

Finding Sources
Reading Web Page

https://www.chi.gov.sa/Style%20Library/IDF_Branding/Indicati…

Reading File
Reading File
Finding Sources
Reading File
Reading File
Loading Image
Reading File
Finding Sources
Reading File
Reading File
Reading File
Loading Image
Loading Image
Loading Image
I now have comprehensive data from multiple authoritative sources. Let me compose the complete, detailed guide.

Piles (Hemorrhoids) - Complete Treatment Guide: Drug, Dose & Duration by Case Type


Classification - What Are Piles?

Hemorrhoids (piles) are pathologically enlarged and symptomatic vascular cushions in the anal canal. They are divided into:
  • Internal hemorrhoids - above the dentate line, covered by mucosa, graded I-IV
  • External hemorrhoids - below the dentate line, covered by perianal skin/anoderm
  • Mixed hemorrhoids - both components with vascular communication

Visual Atlas

Types of Hemorrhoids

Various types of hemorrhoids - internal (Grade II and Grade IV prolapsed), external hemorrhoids, mixed disease, and thrombosed external hemorrhoid
Fig. 1 - Various hemorrhoid types: (A) Internal Grade II hemorrhoid anatomy with Grade IV prolapsed; (B) Internal hemorrhoid through anoscope; (C) External hemorrhoids; (D) External through anoscope; (E) Mixed hemorrhoid with vascular communication; (F) Thrombosed external hemorrhoid diagram; (G) Large acute thrombosed hemorrhoid; (H) Resolving thrombosed hemorrhoid 4-5 days post-onset. (Pfenninger & Fowler's Procedures for Primary Care)

Prolapsed Internal Hemorrhoids (Grade III-IV)

Prolapsed external and internal hemorrhoids - clinical photograph
Fig. 2 - Prolapsed external and internal hemorrhoids. (Current Surgical Therapy)

Acute Thrombosed External & Strangulated Internal Hemorrhoids

A: Acute thrombosed external hemorrhoid. B: Prolapsed and strangulated internal hemorrhoids with external component
Fig. 3 - (A) Acute thrombosed external hemorrhoid. (B) Prolapsed, strangulated internal hemorrhoids with external component. (Current Surgical Therapy)

Internal Hemorrhoid Grading System

GradeAnatomyKey SymptomReducibility
IBulge into anal canal, no prolapsePainless bright-red bleedingN/A - stays internal
IIProlapse with straining/ValsalvaBleeding, pressure, itchingSpontaneously self-reducing
IIIProlapse with straining/ValsalvaBleeding, pressure, mucoid dischargeRequires manual reduction
IVChronically prolapsedPain, bleeding, mucoid dischargeCannot be reduced (incarcerated)


CASE 1: Internal Hemorrhoids - Grade I

Presentation: Painless bright-red rectal bleeding on toilet paper or dripping into bowl; no prolapse; found on anoscopy.

First-Line: Conservative Medical Management

1. Dietary Fiber (BULK-FORMING AGENTS)

DrugDoseDurationNotes
Psyllium husk (Ispaghula)5-10 g mixed in 240 mL water, 1-3x/dayLong-term (ongoing)Take with full glass of water; most evidence-based agent
Methylcellulose1.5-6 g/day in divided dosesLong-termAlternative to psyllium
Calcium polycarbophil1 g 1-4x/dayLong-termAvoid in patients with dysphagia
Evidence: Fiber therapy improves hemorrhoidal symptoms and bleeding in Grade I-II hemorrhoids - Grade A recommendation.

2. Stool Softeners

DrugDoseDuration
Docusate sodium (DSS)100 mg twice daily2-4 weeks; use short-term
Lactulose15-30 mL once or twice dailyUntil regular bowel habits restored
Polyethylene glycol (PEG)17 g in 240 mL water once dailyShort to medium term

3. Topical Agents (Symptom Relief Only)

Note: Topical treatments have no proven disease-modifying effect but offer short-term symptomatic relief (Grade B evidence).
DrugFormulationDose/ApplicationDuration
Lidocaine 5% ointment/gelTopicalApply to affected area up to 3-4x/dayMax 7-14 days continuously
Pramoxine (pramocaine) creamTopicalApply 3-4x/day and after each bowel movement7-14 days
Dibucaine (cinchocaine) ointmentTopicalApply morning, night, after each stool7-14 days
Benzocaine creamTopicalApply as needed, up to 4x/dayShort-term only
Witch hazel padsTopicalApply after each bowel movementOngoing as needed
Hydrocortisone 1-2.5% creamTopicalThin layer twice dailyMaximum 7 days - avoid prolonged use (skin atrophy risk); corticosteroids no longer recommended long-term per current guidelines

4. Phlebotonics (Venoactive Drugs / Flavonoids)

Recommended for short-term use in acute hemorrhoidal disease only (Grade D evidence for long-term use - not supported).
DrugDoseDurationNotes
Micronized Purified Flavonoid Fraction - MPFF (Daflon/Diosmin 90% + Hesperidin 10%)500 mg twice daily OR 1000 mg once dailyAcute episode: 2-3 months max; recurrent: short coursesReduces bleeding (OR 0.12), pruritus, discharge; Cochrane-reviewed
Diosmin600 mg twice daily2-3 months; short course in acute flareAvailable as dietary supplement in USA
Troxerutin / Hydroxyethylrutoside300 mg three times dailyShort-term acute treatment
Calcium dobesilate500 mg three times dailyShort-termCaution: risk of agranulocytosis - monitor CBC

5. Non-Drug Measures (Mandatory for ALL grades)

  • Warm sitz baths: 10-15 minutes, 2-3x daily and after each bowel movement
  • Increase fluid intake: minimum 6-8 glasses water/day
  • High-fiber diet: 25-35 g fiber/day
  • Avoid prolonged toilet sitting (>3 minutes) - remove phones/reading material
  • Avoid straining

Office Procedure if Conservative Fails (Grade I)

  • Infrared photocoagulation (IRC): Most suited for Grade I, especially if RBL caused pain. Infrared probe applied 1.5 seconds at 2-3 sites proximal to plexus. Multiple hemorrhoids treated in one session.
  • Injection Sclerotherapy: 3-5 mL of 5% phenol in oil injected into submucosa at apex. All 3 hemorrhoids can be treated in one session. Suitable for patients on anticoagulants.


CASE 2: Internal Hemorrhoids - Grade II

Presentation: Prolapse during straining that spontaneously reduces; bleeding; pressure; itching.

First-Line: Conservative + Office Procedures

Conservative Measures

Same as Grade I (fiber, stool softeners, topical agents, phlebotonics, sitz baths).

Preferred Office Procedure: Rubber Band Ligation (RBL)

RBL is the most effective office-based therapy (ASCRS guideline recommendation).
Rubber band ligation procedure - (A) band on gun, (B) grasping 2 cm above dentate line, (C) band in correct position after ligation
Fig. 4 - Rubber band ligation of internal hemorrhoids. (Current Surgical Therapy)
AspectDetail
PositionBand placed 2 cm above dentate line (no somatic sensation here)
Per session1 hemorrhoid column first visit; up to 2 thereafter
Session interval3-4 weeks apart
Total sessionsVariable; typically 2-4 sessions for full effect
Success rateOver 90%
ContraindicationsAnticoagulants (hold aspirin 7 days prior), antiplatelet drugs, portal hypertension, immunocompromised patients
Post-procedure drugs:
DrugDoseDurationPurpose
Psyllium husk5-10 g/dayOngoingPrevent hard stool/straining
Docusate sodium100 mg twice daily1-2 weeks post-procedureStool softening
Paracetamol (acetaminophen)500-1000 mg every 6-8 hours PRNFirst 48 hoursDull ache relief
Ibuprofen (if no contraindication)400 mg every 8 hours with food PRN48 hoursAnalgesic/anti-inflammatory
Sclerotherapy (alternative, especially for anticoagulated patients):
  • 5% phenol in oil: 2-3 mL per hemorrhoid column, all 3 columns in one session
  • Ethanolamine: 1 mL per column
  • Repeat in 4-6 weeks if needed


CASE 3: Internal Hemorrhoids - Grade III

Presentation: Prolapse requiring manual digital reduction; bleeding; pressure sensation; mucoid discharge.

Approach: Primarily Office Procedures; Surgery for Failures

Conservative (Adjunct)

Same fiber, stool softener, phlebotonic regimen as above.

Rubber Band Ligation (first choice)

Same protocol as Grade II. RBL is more effective and requires fewer sessions than sclerotherapy or IRC for Grade III. Sessions scheduled 3-4 weeks apart.

Surgical Management (for persistent symptoms after office procedures)

Surgical Hemorrhoidectomy (Milligan-Morgan / Ferguson):
AspectDetail
IndicationGrade III unresponsive to office procedures; preferred for Grade III with large external component
AnesthesiaLocal, regional, or general; day surgery
WoundsOpen (Milligan-Morgan) or closed (Ferguson)
DeviceScalpel, cautery, harmonic scalpel, LigaSure
Recurrence26% at median 17 years; 11% require additional procedure
Post-operative analgesics and wound care:
DrugDoseDurationNotes
Paracetamol + Codeine500/30 mg every 4-6 hours5-7 daysFirst-line post-op analgesia
NSAID (Ibuprofen/Diclofenac)400-600 mg every 8 hours with food5-7 daysAdjunct; avoid if bleeding risk
Lactulose or Movicol15-20 mL twice daily or 1-2 sachets/day4-6 weeks post-opPrevent hard stool on wound
Metronidazole 400 mg3 times daily7-10 daysReduces post-op pain; antimicrobial
Glyceryl trinitrate 0.2-0.4% ointmentApply thin layer to perianal area 2-3x/day4-8 weeksReduces post-op pain, promotes healing
Topical lignocaine (lidocaine) 2% gelApply to wound 3-4x/day1-2 weeksLocal wound pain relief
Liposomal bupivacaine (Exparel)Single-dose perioperative injectionIntraoperative/post-opLong-acting local anesthetic, reduces opioid requirement
Sitz baths3x daily4-6 weeksWound hygiene and pain relief
Stapled Hemorrhoidopexy (Procedure for Prolapse & Hemorrhoids - PPH):
  • Alternative to conventional hemorrhoidectomy for internal hemorrhoids with prolapse
  • Less post-operative pain, shorter recovery
  • Higher long-term recurrence rate than conventional hemorrhoidectomy
  • Not effective for large external hemorrhoids


CASE 4: Internal Hemorrhoids - Grade IV (Chronically Prolapsed / Incarcerated)

Presentation: Permanently prolapsed hemorrhoid that cannot be manually reduced; pain, bleeding, mucoid discharge; risk of strangulation and gangrene.

Approach: Urgent Surgical Consultation

Grade IV hemorrhoids with incarceration or gangrenous tissue require PROMPT surgical consultation.
ScenarioManagement
Grade IV, no gangrene, patient stableElective surgical hemorrhoidectomy
Grade IV with strangulationUrgent/emergent hemorrhoidectomy
Gangrene/necrosis presentEmergent surgical debridement + IV antibiotics
Pre-operative/acute phase drugs:
DrugDoseDurationPurpose
Morphine or Pethidine IV/IMMorphine 2-4 mg IV every 2-4 hrs PRNAcute admissionSevere pain control
Ceftriaxone 1-2 g IVOnce daily5-7 daysCover perianal sepsis if strangulated
Metronidazole 500 mg IVEvery 8 hours5-7 daysAnaerobic cover
MPFF (Daflon)1500 mg/day for 4 days, then 1000 mg/day for 3 days7 days acute courseReduces acute hemorrhoidal crisis symptoms
ICE packs locallyPRNFirst 24-48 hrsReduce swelling
Manual reduction attemptGentle digital pressure with lidocaine jellyOnceBefore surgical intervention
Post-surgical care: Same as Grade III hemorrhoidectomy above.


CASE 5: External Hemorrhoids - Non-Thrombosed

Presentation: Skin tags, discomfort, pruritus; no thrombosis; soft reducible perianal swellings.

Treatment: Conservative Only

Drug/MeasureDoseDuration
High-fiber diet + psyllium5-10 g psyllium/dayOngoing
Docusate sodium100 mg twice daily2-4 weeks
Witch hazel pads/gelApply after each stool and 3-4x dailyAs needed
Pramoxine or Lidocaine topicalApply 3-4x dailyMax 14 days
Sitz baths10-15 min, 2-3x dailyOngoing
Hydrocortisone 1% creamThin layer twice dailyMax 7 days only
Surgical excision for external skin tags is cosmetic/elective only and not routinely recommended.


CASE 6: Thrombosed External Hemorrhoids (TEH)

Presentation: Acutely painful, tense, blue-purple perianal mass (visible clot under skin); onset within 48-72 hours; inability to sit comfortably.

Decision Point: Timing is Critical

If within 48-72 hours of onset + severe pain → SURGICAL EXCISION

Procedure: Excision of thrombus AND overlying skin under local anesthesia (not just incision and drainage - prevents recurrence).
Local anesthetic for excision:
DrugDoseRoute
Lidocaine 1-2% with epinephrine 1:200,0003-5 mL infiltrationSubcutaneous perianal
Bupivacaine 0.25-0.5%3-5 mLLong-acting alternative
Post-excision drugs:
DrugDoseDuration
Paracetamol 500-1000 mgEvery 6-8 hours PRN3-5 days
Ibuprofen 400 mgEvery 8 hours with food3-5 days
Docusate sodium 100 mgTwice daily1-2 weeks
Sitz baths2-3x daily1-2 weeks

If more than 72 hours after onset OR pain is improving → CONSERVATIVE MANAGEMENT

Most thrombosed external hemorrhoids resolve within 48-72 hours spontaneously.
DrugDoseDuration
Sitz baths (warm)2-3x daily, 10-15 min eachUntil resolution (1-2 weeks)
Psyllium5-10 g/day in waterOngoing
Docusate sodium100 mg twice daily2 weeks
NSAID (Ibuprofen)400 mg every 8 hours with food5-7 days (reduces inflammation)
Topical anesthetic (pramoxine or lidocaine 5%)Apply 3-4x dailyUntil pain resolves
Witch hazel padsAfter each stoolUntil resolution
MPFF (Daflon) 500 mgTwice daily7-10 days acute course


CASE 7: Mixed Internal + External Hemorrhoids

Presentation: Combination of internal Grade II-III and external hemorrhoids; most complex presentation; prolapse with painful external component.

Treatment: Surgery is Preferred

Office procedures cannot address the external component. Conventional excisional hemorrhoidectomy is the gold standard for symptomatic mixed disease.
Medical bridge (pre-surgical or for mild cases):
  • Same conservative management as above
  • MPFF 500 mg twice daily for 2-3 months
  • Fiber and stool softeners ongoing
Surgical: Conventional hemorrhoidectomy under appropriate anesthesia (see Grade III/IV protocol above).


CASE 8: Hemorrhoids in Pregnancy

Presentation: Common in 2nd-3rd trimester and postpartum; mostly Grades I-III; related to constipation and venous congestion.

Treatment: Conservative Only (Avoid Procedures During Pregnancy)

Procedures are contraindicated during pregnancy and for ≤8 weeks postpartum.
DrugDoseDurationSafety
Psyllium husk5-10 g/dayThroughout pregnancy and postpartumSafe - Category not classified; preferred
Lactulose15-30 mL once or twice dailyAs neededSafe in pregnancy
Docusate sodium100 mg twice dailyShort-termGenerally considered safe
Witch hazel padsTopical, after each stoolAs neededSafe topically
Warm sitz baths10-15 min, 2-3x dailyAs neededSafe and helpful
Pramoxine topicalApply 3-4x dailyShort-termMinimal systemic absorption; preferred over lidocaine
MPFF (Daflon)Avoid in 1st trimester; use with caution in 2nd-3rd trimesterShort-term acute onlyLimited data - use only if benefit outweighs risk
Hydrocortisone topicalThin layer sparinglyMax 5-7 daysAvoid prolonged use; low-potency preparations only
Avoid: NSAIDs (especially 3rd trimester), oral phlebotonics without physician review------


CASE 9: Hemorrhoids in Anticoagulated Patients

Presentation: Hemorrhoids in patients on warfarin, heparin, NOACs (rivaroxaban, apixaban), or antiplatelet agents (aspirin, clopidogrel).

Key Rules:

  • RBL is relatively contraindicated - risk of delayed significant bleeding
  • Sclerotherapy is the preferred office procedure - works without vascular disruption
  • Hold aspirin 7 days pre- and 7 days post-procedure if possible
  • For INR on warfarin: should be in therapeutic range before any procedure
ProcedureSafetyNotes
SclerotherapySafe5% phenol 2-3 mL; digital pressure controls needle site bleeding
Infrared coagulationAcceptableLess bleeding risk than RBL
RBLRelatively contraindicatedDelayed bleeding at band slough (7-14 days)
SurgeryHigher risk; requires anticoagulation bridgingConsult hematology/cardiology
Drug management:
  • Continue fiber/stool softeners as standard
  • Topical agents as for standard management
  • Phlebotonics (MPFF) may be used as adjunct for bleeding reduction


CASE 10: Portal Hypertension + Hemorrhoids / Anorectal Varices

Presentation: Patient with cirrhosis or portal hypertension; distinguish hemorrhoids from anorectal varices (anorectal varices are compressible, refill rapidly, extend across dentate line).
⚠️ RBL is contraindicated in portal hypertension due to high risk of massive delayed bleeding.
ScenarioTreatment
Hemorrhoids (not varices)Sclerotherapy preferred; conservative management
Anorectal varices with bleedingUnderrunning with absorbable suture; inferior mesenteric vein embolization; TIPS (transjugular intrahepatic portosystemic shunt)
Portal hypertension + hemorrhoidsManage portal hypertension (beta-blockers, TIPS) first; avoid all interventional procedures if possible


CASE 11: Immunocompromised Patients (HIV/AIDS, Chemotherapy)

Presentation: Hemorrhoids in HIV-positive or actively immunosuppressed patients.
RBL is contraindicated in immunocompromised patients due to risk of pelvic sepsis.
TreatmentNotes
Conservative medical managementFirst-line; preferred indefinitely
SclerotherapyBetter studied and preferred over IRC in this group
SurgeryHigh risk of complications; delay until immune status improves


CASE 12: Post-Hemorrhoidectomy Pain Management

A significant drawback of surgery is post-operative pain. Evidence-based adjuncts:
DrugDoseDuration
Metronidazole 400 mg3x daily7-10 days - reduces post-op pain
GTN 0.2-0.4% ointmentApply perianally 2-3x daily4-8 weeks
Topical 2% atorvastatinApply locallyPost-op weeks
Sucralfate pasteApply locallyPost-op weeks
Topical cholestyramineApply locallyPost-op weeks
Lactulose/Movicol1-2 sachets daily4-6 weeks
Sitz baths3x daily4-6 weeks


Summary Treatment Algorithm

HEMORRHOIDS
├── EXTERNAL (below dentate line)
│   ├── Non-thrombosed → Conservative (fiber, sitz baths, topicals)
│   └── Thrombosed
│       ├── < 72 hours + severe pain → EXCISION under local anesthetic
│       └── > 72 hours or improving → Conservative (NSAID, sitz baths, topicals)
│
└── INTERNAL (above dentate line)
    ├── Grade I → Conservative + consider IRC/sclerotherapy if fails
    ├── Grade II → Conservative + RBL (preferred); sclerotherapy if anticoagulated
    ├── Grade III → RBL first; surgical hemorrhoidectomy if fails
    └── Grade IV → Urgent surgical consult; hemorrhoidectomy

Key Drug Summary Table

Drug ClassDrugDoseDurationGrade Indication
Bulking agentPsyllium husk5-10 g/dayLong-termAll grades
Stool softenerDocusate sodium100 mg BD2-4 weeksAll grades
Osmotic laxativeLactulose15-30 mL OD-BDShort-medium termAll grades, post-op
Topical anestheticLidocaine 5%Apply TDS-QDSMax 14 daysExternal/symptomatic
Topical anestheticPramoxineApply TDS-QDSMax 14 daysExternal/symptomatic
Topical steroidHydrocortisone 1%Thin layer BDMax 7 daysPruritus, short-term
PhlebotonicMPFF (Daflon) 500 mg500 mg BD2-3 months; short acute coursesGrades I-III, acute
PhlebotonicDiosmin600 mg BDShort-term acuteGrades I-III
NSAIDIbuprofen400 mg TDS3-7 daysTEH, post-procedure
AnalgesicParacetamol500-1000 mg QDSPRN 3-7 daysPost-procedure/surgery
Antibiotic (post-op)Metronidazole400 mg TDS7-10 daysPost-hemorrhoidectomy
Topical post-opGTN 0.2-0.4%BD-TDS4-8 weeksPost-hemorrhoidectomy
Sclerosant5% Phenol in oil2-3 mL per columnSingle session; repeat 4-6 wkGrades I-II; anticoag patients
Local anestheticLidocaine 1-2% + epi3-5 mL infiltrationSingle useTEH excision

Sources:
  • Pfenninger and Fowler's Procedures for Primary Care, 3rd Ed.
  • Sleisenger and Fordtran's Gastrointestinal and Liver Disease
  • Yamada's Textbook of Gastroenterology, 7th Ed.
  • Current Surgical Therapy, 14th Ed.
  • Saudi IDF/SFDA Hemorrhoids Clinical Practice Guideline (2024)
  • ASCRS (American Society of Colon and Rectal Surgeons) Guidelines
  • Cleveland Clinic/Medscape treatment protocols
  • Recent PubMed systematic reviews (PMIDs: 40596934, 40576944, 39048788)

make it with detailed image and prescription treatment

Finding Sources
Finding Sources
Searching the Web

piles hemorrhoids detailed prescription treatment all grades drug dose duration 2024 clinical guidelines

Reading File
Reading File
Reading File
Loading Image
Loading Image
Loading Image
Loading Image
Loading Image
Loading Image
Reading File
Loading Image
Loading Image
Loading Image
Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null && ls /home/daytona/skills/docx/scripts/office/ 2>/dev/null | head -20

Running Command

mkdir -p /home/daytona/workspace/piles-treatment && ls /home/daytona/workspace/piles-treatment/

Writing File

~/piles-treatment/build_doc.js

const {
  Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
  HeadingLevel, AlignmentType, BorderStyle, WidthType, ShadingType,
  VerticalAlign, PageBreak, UnderlineType, convertInchesToTwip
} = require('docx');
const fs = require('fs');

// Helper: Heading 1
function h1(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_1,
    spacing: { before: 300, after: 120 },
  });
}

// Helper: Heading 2
function h2(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_2,
    spacing: { before: 240, after: 80 },
  });
}

// Helper: Heading 3
function h3(text) {
  return new Paragraph({
    text,
    heading: HeadingLevel.HEADING_3,
    spacing: { before: 180, after: 60 },
  });
}

// Helper: body paragraph
function p(text, bold = false) {
  return new Paragraph({
    children: [new TextRun({ text, bold, size: 22 })],
    spacing: { after: 80 },
  });
}

// Helper: bullet
function bullet(text) {
  return new Paragraph({
    text,
    bullet: { level: 0 },
    spacing: { after: 60 },
    run: { size: 22 },
  });
}

// Helper: sub-bullet
function bullet2(text) {
  return new Paragraph({
    text,
    bullet: { level: 1 },
    spacing: { after: 50 },
    run: { size: 21 },
  });
}

// Helper: warning box text
function warning(text) {
  return new Paragraph({
    children: [new TextRun({ text: '⚠ ' + text, bold: true, color: 'C0392B', size: 22 })],
    spacing: { before: 80, after: 80 },
    border: {
      left: { style: BorderStyle.THICK, size: 9, color: 'C0392B' },
    },
    indent: { left: 200 },
  });
}

// Helper: prescription box title
function rxTitle(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 24, color: '1A5276' })],
    spacing: { before: 120, after: 60 },
    border: {
      bottom: { style: BorderStyle.SINGLE, size: 6, color: '1A5276' },
    },
  });
}

// Helper: simple table
function makeTable(headers, rows, colWidths) {
  const headerCells = headers.map((h, i) =>
    new TableCell({
      children: [new Paragraph({
        children: [new TextRun({ text: h, bold: true, size: 20, color: 'FFFFFF' })],
        alignment: AlignmentType.CENTER,
      })],
      shading: { fill: '1A5276', type: ShadingType.CLEAR, color: '1A5276' },
      width: { size: colWidths ? colWidths[i] : Math.floor(9000 / headers.length), type: WidthType.DXA },
      verticalAlign: VerticalAlign.CENTER,
    })
  );

  const dataRows = rows.map((row, ri) =>
    new TableRow({
      children: row.map((cell, ci) =>
        new TableCell({
          children: [new Paragraph({
            children: [new TextRun({ text: cell, size: 20 })],
            alignment: AlignmentType.LEFT,
          })],
          shading: ri % 2 === 0
            ? { fill: 'EBF5FB', type: ShadingType.CLEAR, color: 'EBF5FB' }
            : { fill: 'FFFFFF', type: ShadingType.CLEAR, color: 'FFFFFF' },
          width: { size: colWidths ? colWidths[ci] : Math.floor(9000 / row.length), type: WidthType.DXA },
          margins: { top: 60, bottom: 60, left: 100, right: 100 },
        })
      ),
    })
  );

  return new Table({
    rows: [new TableRow({ children: headerCells }), ...dataRows],
    width: { size: 9000, type: WidthType.DXA },
    margins: { top: 60, bottom: 60, left: 100, right: 100 },
  });
}

// ─────────────────────────────────────────────
// DOCUMENT CONTENT
// ─────────────────────────────────────────────

const doc = new Document({
  title: 'Piles (Hemorrhoids) Detailed Prescription Treatment Guide',
  creator: 'Orris Medical AI',
  styles: {
    default: {
      heading1: {
        run: { bold: true, size: 32, color: '1A5276', font: 'Calibri' },
        paragraph: { spacing: { before: 360, after: 120 } },
      },
      heading2: {
        run: { bold: true, size: 28, color: '154360', font: 'Calibri' },
        paragraph: { spacing: { before: 240, after: 80 } },
      },
      heading3: {
        run: { bold: true, size: 24, color: '1F618D', font: 'Calibri' },
        paragraph: { spacing: { before: 180, after: 60 } },
      },
      document: {
        run: { size: 22, font: 'Calibri' },
        paragraph: { spacing: { after: 80 } },
      },
    },
  },
  sections: [
    {
      properties: {
        page: {
          margin: {
            top: convertInchesToTwip(1),
            right: convertInchesToTwip(1),
            bottom: convertInchesToTwip(1),
            left: convertInchesToTwip(1),
          },
        },
      },
      children: [
        // ── TITLE PAGE ──────────────────────────────────
        new Paragraph({
          children: [
            new TextRun({ text: 'PILES (HEMORRHOIDS)', bold: true, size: 52, color: '1A5276', font: 'Calibri' }),
          ],
          alignment: AlignmentType.CENTER,
          spacing: { before: 400, after: 80 },
        }),
        new Paragraph({
          children: [
            new TextRun({ text: 'Complete Prescription Treatment Guide', bold: true, size: 36, color: '2E86C1', font: 'Calibri' }),
          ],
          alignment: AlignmentType.CENTER,
          spacing: { after: 80 },
        }),
        new Paragraph({
          children: [
            new TextRun({ text: 'All Case Types | Drug · Dose · Duration | Evidence-Based', size: 26, color: '5D6D7E', font: 'Calibri' }),
          ],
          alignment: AlignmentType.CENTER,
          spacing: { after: 80 },
        }),
        new Paragraph({
          children: [new TextRun({ text: 'Based on ASCRS 2024 | Sleisenger & Fordtran | Sabiston | Pfenninger & Fowler', size: 22, color: '7F8C8D', font: 'Calibri' })],
          alignment: AlignmentType.CENTER,
          spacing: { after: 600 },
        }),
        new Paragraph({
          children: [new PageBreak()],
        }),

        // ══════════════════════════════════════════════
        // SECTION 1: ANATOMY & CLASSIFICATION
        // ══════════════════════════════════════════════
        h1('SECTION 1: ANATOMY & CLASSIFICATION'),
        p('Hemorrhoids (piles) are pathologically enlarged, symptomatic vascular cushions in the anal canal. They are present normally in all individuals and become pathological only when symptomatic. The three primary hemorrhoidal columns are located at the right anterior, right posterior, and left lateral positions.'),

        h2('1.1 Anatomical Location Reference'),
        p('The dentate (pectinate) line is the crucial anatomical landmark that separates internal from external hemorrhoids.'),
        bullet('ABOVE dentate line → Internal hemorrhoids (covered by mucosa, no somatic pain)'),
        bullet('BELOW dentate line → External hemorrhoids (covered by anoderm, somatic innervation = PAINFUL)'),
        bullet('BOTH components → Mixed hemorrhoids'),

        h2('1.2 Classification of Internal Hemorrhoids (Goligher Grading)'),
        makeTable(
          ['Grade', 'Anatomy', 'Symptoms', 'Prolapse Behavior'],
          [
            ['Grade I', 'Enlarge into anal canal; do not prolapse', 'Painless bright-red rectal bleeding', 'No prolapse'],
            ['Grade II', 'Prolapse during straining/defecation', 'Bleeding, pressure, pruritus', 'Spontaneously self-reducing'],
            ['Grade III', 'Prolapse with straining', 'Bleeding, pressure, mucoid discharge', 'Requires manual digital reduction'],
            ['Grade IV', 'Chronically prolapsed / incarcerated', 'Pain, bleeding, mucoid discharge', 'Cannot be reduced; risk of strangulation'],
          ],
          [1200, 2400, 2800, 2600]
        ),

        new Paragraph({ spacing: { after: 120 } }),

        h2('1.3 External Hemorrhoids'),
        makeTable(
          ['Type', 'Presentation', 'Key Feature'],
          [
            ['Non-thrombosed', 'Soft skin folds, pruritus, hygiene problems', 'Painless unless thrombosed'],
            ['Thrombosed (TEH)', 'Sudden severe anal pain, firm blue-purple perianal lump', 'TIME-SENSITIVE: treat within 72 hours'],
          ],
          [2500, 3500, 3000]
        ),

        new Paragraph({ children: [new PageBreak()] }),

        // ══════════════════════════════════════════════
        // SECTION 2: UNIVERSAL BASELINE PRESCRIPTIONS
        // ══════════════════════════════════════════════
        h1('SECTION 2: UNIVERSAL BASELINE PRESCRIPTIONS (ALL GRADES)'),
        p('The following medications and measures form the foundation of treatment across all hemorrhoid grades. They must be prescribed alongside any procedure-specific therapy.'),

        h2('Rx 1 — Dietary Fiber Supplementation (Bulk-Forming Agents)'),
        p('Grade A evidence — reduces bleeding, straining, and recurrence.'),
        makeTable(
          ['Drug', 'Dose', 'Route', 'Frequency', 'Duration'],
          [
            ['Psyllium husk (Ispaghula)', '5–10 g in 240 mL water', 'Oral', '1–3 times daily', 'Long-term (ongoing)'],
            ['Methylcellulose', '1.5–6 g/day divided', 'Oral', '2–3 times daily', 'Long-term'],
            ['Calcium polycarbophil', '1 g per dose', 'Oral', '1–4 times daily', 'Long-term'],
          ],
          [2200, 2200, 1200, 1600, 1800]
        ),
        p('NOTE: Always take with at least one full glass (240 mL) of water. Do not take at bedtime.', false),

        new Paragraph({ spacing: { after: 100 } }),
        h2('Rx 2 — Stool Softeners / Osmotic Laxatives'),
        makeTable(
          ['Drug', 'Dose', 'Frequency', 'Duration', 'Indication'],
          [
            ['Docusate sodium (DSS)', '100 mg', 'Twice daily', '2–4 weeks', 'Standard first-line softener'],
            ['Lactulose', '15–30 mL', 'Once or twice daily', 'Until regular bowel habit', 'Constipation predominant'],
            ['Polyethylene glycol 3350 (PEG)', '17 g in 240 mL water', 'Once daily', 'Short–medium term', 'Hard stool; fiber insufficient'],
          ],
          [2000, 1400, 1600, 1800, 2200]
        ),

        new Paragraph({ spacing: { after: 100 } }),
        h2('Rx 3 — Topical Anesthetics (Symptomatic Relief)'),
        warning('Topical agents provide SHORT-TERM symptom relief only. They have NO proven disease-modifying effect. Max 7–14 days of continuous use.'),
        makeTable(
          ['Drug', 'Formulation', 'Application', 'Frequency', 'Max Duration'],
          [
            ['Lidocaine 5%', 'Ointment/gel', 'Apply to anal area', '3–4 times daily', '14 days'],
            ['Pramoxine (Pramocaine)', 'Cream/ointment', 'Apply to anal area', '3–4 times daily', '14 days'],
            ['Dibucaine (Cinchocaine) 0.5–1%', 'Ointment', 'Apply AM, PM, after each stool', '3 times daily', '14 days'],
            ['Benzocaine', 'Cream/gel', 'Apply as needed', 'Up to 4 times daily', '7 days'],
          ],
          [2200, 1600, 1800, 1800, 1600]
        ),

        new Paragraph({ spacing: { after: 100 } }),
        h2('Rx 4 — Topical Steroids (Short-Term Use Only)'),
        warning('Hydrocortisone and betamethasone are NO LONGER recommended for long-term use in hemorrhoids (current SFDA/CHI guideline). Predisposition to candidiasis and skin atrophy.'),
        makeTable(
          ['Drug', 'Formulation', 'Application', 'Frequency', 'MAX Duration'],
          [
            ['Hydrocortisone 1–2.5%', 'Cream/ointment/suppository', 'Apply thin layer to anal area', 'Twice daily', '7 days ONLY'],
          ],
          [2500, 2200, 2500, 1400, 1400]
        ),

        new Paragraph({ spacing: { after: 100 } }),
        h2('Rx 5 — Phlebotonics / Venoactive Drugs (Venotropics)'),
        p('Phlebotonics improve venous tone, reduce capillary permeability, and improve lymphatic drainage. Cochrane review confirms efficacy for bleeding (OR 0.12), pruritus (OR 0.23), and discharge. Recommended SHORT-TERM in acute disease only (Grade A evidence for efficacy, Grade D against long-term use).'),
        makeTable(
          ['Drug', 'Standard Dose', 'Frequency', 'Duration', 'Notes'],
          [
            ['MPFF – Diosmin 90% + Hesperidin 10% (Daflon 500 mg)', '500 mg', 'Twice daily OR 1000 mg once daily', 'Acute: 2–3 months max; short courses', 'Best-evidence phlebotonic; Grade A'],
            ['Diosmin (plain)', '600 mg', 'Twice daily', '2–3 months; short acute courses', 'Available as supplement in USA'],
            ['Troxerutin / Hydroxyethylrutoside', '300 mg', 'Three times daily', 'Short-term acute treatment', ''],
            ['Calcium dobesilate 500 mg', '500 mg', 'Three times daily', 'Short-term ONLY', 'CAUTION: risk of agranulocytosis – monitor CBC'],
          ],
          [2400, 1400, 1800, 1800, 1600]
        ),

        new Paragraph({ spacing: { after: 100 } }),
        h2('Non-Drug Measures (Mandatory for ALL Grades)'),
        bullet('Warm sitz baths: 10–15 minutes, 2–3 times daily and after each bowel movement'),
        bullet('Fluid intake: minimum 6–8 glasses (non-alcoholic, non-caffeinated) per day'),
        bullet('High-fiber diet: 25–35 g dietary fiber per day'),
        bullet('Reduce toilet sitting time to < 3 minutes; remove phones and reading material'),
        bullet('Avoid straining and prolonged bearing down'),
        bullet('Proper anal hygiene; avoid aggressive wiping'),
        bullet('Witch hazel-impregnated pads after each stool for external symptoms'),

        new Paragraph({ children: [new PageBreak()] }),

        // ══════════════════════════════════════════════
        // SECTION 3: GRADE-BY-GRADE PRESCRIPTION PLANS
        // ══════════════════════════════════════════════
        h1('SECTION 3: GRADE-BY-GRADE PRESCRIPTION TREATMENT PLANS'),

        // ─── GRADE I ───────────────────────────────────
        h2('CASE TYPE 1: Internal Hemorrhoids — Grade I'),
        p('Presentation: Painless bright-red rectal bleeding; hemorrhoid visible on anoscopy but does NOT prolapse; no pain.', true),

        h3('Step 1: First-Line Medical Treatment'),
        p('Start ALL of the following simultaneously:'),
        bullet('Psyllium husk 5–10 g in water, 1–2 times daily (ongoing)'),
        bullet('Docusate sodium 100 mg twice daily × 4 weeks'),
        bullet('Sitz baths 2–3 times daily'),
        bullet('MPFF (Daflon) 500 mg twice daily × 4–8 weeks if bleeding persists'),

        h3('Step 2: Topical Symptom Relief (if pruritus/discomfort)'),
        bullet('Pramoxine 1% cream applied 3–4 times daily × 14 days maximum'),
        bullet('Witch hazel pads after each stool'),

        h3('Step 3: Office Procedure if Medical Therapy Fails (> 4–6 weeks)'),
        makeTable(
          ['Procedure', 'Technique', 'Sessions', 'Recovery'],
          [
            ['Infrared Photocoagulation (IRC)', 'Infrared probe 1.5 sec at 2–3 sites proximal to plexus', 'Multiple hemorrhoids per session', 'Minimal; preferred for Grade I'],
            ['Injection Sclerotherapy', '5% phenol in oil 3–5 mL injected into submucosa at anorectal ring', 'All 3 columns in 1 session; repeat at 4–6 wk', 'Dull ache 1–2 days; safe in anticoagulated pts'],
          ],
          [2200, 3000, 2000, 1800]
        ),

        new Paragraph({ spacing: { after: 120 } }),

        // ─── GRADE II ──────────────────────────────────
        h2('CASE TYPE 2: Internal Hemorrhoids — Grade II'),
        p('Presentation: Prolapse during straining with SPONTANEOUS reduction; bleeding; pressure; pruritus.', true),

        h3('Step 1: Baseline Medical Treatment (same as Grade I)'),
        bullet('Psyllium husk + docusate sodium + sitz baths (as above)'),
        bullet('MPFF (Daflon) 500 mg twice daily × 6–8 weeks — Grade II indication'),
        bullet('Topical lidocaine 5% or pramoxine 1% PRN for discomfort × 14 days max'),

        h3('Step 2: Preferred Office Procedure — Rubber Band Ligation (RBL)'),
        p('RBL is the most effective office-based therapy for Grade II hemorrhoids (ASCRS 2024, Grade A).'),
        makeTable(
          ['Parameter', 'Detail'],
          [
            ['Band position', '2 cm ABOVE dentate line (no somatic sensation at this level)'],
            ['Hemorrhoids per session', '1 column at first session; up to 2 thereafter'],
            ['Session interval', '3–4 weeks apart'],
            ['Expected sessions', '2–4 sessions for complete resolution'],
            ['Success rate', '>90%'],
            ['Tissue slough timing', 'Band sloughs ~7 days; minor bleeding expected'],
            ['Contraindications', 'Anticoagulants, portal hypertension, immunocompromise'],
          ],
          [3000, 6000]
        ),

        h3('Step 3: Post-RBL Prescription'),
        makeTable(
          ['Drug', 'Dose', 'Frequency', 'Duration', 'Purpose'],
          [
            ['Paracetamol (acetaminophen)', '500–1000 mg', 'Every 6–8 hours PRN', 'First 48 hours', 'Dull ache relief post-procedure'],
            ['Ibuprofen', '400 mg with food', 'Every 8 hours PRN', '48–72 hours', 'Analgesic/anti-inflammatory'],
            ['Docusate sodium', '100 mg', 'Twice daily', '2 weeks post-procedure', 'Prevent hard stool on banded tissue'],
            ['Psyllium husk', '5–10 g/day', 'Daily', 'Ongoing', 'Stool consistency maintenance'],
          ],
          [2200, 1400, 1800, 1800, 1800]
        ),

        h3('Alternative: Sclerotherapy (for anticoagulated patients)'),
        bullet('5% phenol in oil: 2–3 mL per column (ethanolamine: 1 mL per column)'),
        bullet('All 3 columns treated in ONE session under anoscopy'),
        bullet('Repeat after 4–6 weeks if needed'),

        new Paragraph({ spacing: { after: 120 } }),

        // ─── GRADE III ─────────────────────────────────
        h2('CASE TYPE 3: Internal Hemorrhoids — Grade III'),
        p('Presentation: Prolapse requires MANUAL digital reduction; bleeding; pressure; mucoid discharge. Most common grade requiring procedural/surgical intervention.', true),

        h3('Step 1: Baseline Medical Treatment (Bridge Therapy)'),
        bullet('Psyllium husk 5–10 g/day (ongoing)'),
        bullet('Docusate sodium 100 mg twice daily'),
        bullet('MPFF (Daflon) 500 mg twice daily × 2–3 months — significant benefit for Grade III'),
        bullet('Sitz baths 2–3 times daily'),
        bullet('Topical anesthetic PRN × 14 days max'),

        h3('Step 2: Office Procedure — RBL (First-Line for Grade III)'),
        p('Schedule 3–4 sessions at 3–4 week intervals. If Grade III fails after 3 courses of RBL, escalate to surgery.'),

        h3('Step 3: Surgical Hemorrhoidectomy (for failures or large external component)'),
        p('Conventional excisional hemorrhoidectomy (Milligan-Morgan open / Ferguson closed technique) is the gold standard for Grade III failing office procedures.'),
        makeTable(
          ['Aspect', 'Details'],
          [
            ['Anesthesia', 'Local with MAC, spinal, or general anesthesia; day surgery'],
            ['Position', 'Lithotomy or prone jack-knife'],
            ['Wound', 'Open (Milligan-Morgan) or closed (Ferguson) — equal efficacy'],
            ['Energy device', 'Scalpel, cautery, harmonic scalpel, LigaSure'],
            ['Prophylactic antibiotics', 'NOT routinely indicated'],
            ['Recurrence at 17 years', '26%; 11% require additional procedure'],
          ],
          [3000, 6000]
        ),

        h3('Post-Operative Prescription (Hemorrhoidectomy)'),
        makeTable(
          ['Drug', 'Dose', 'Frequency', 'Duration', 'Evidence / Notes'],
          [
            ['Paracetamol + Codeine', '500 mg / 30 mg', 'Every 4–6 hours PRN', '5–7 days', 'First-line post-op opioid analgesia'],
            ['Ibuprofen or Diclofenac', '400–600 mg / 50 mg with food', 'Every 8 hours', '5–7 days', 'NSAID adjunct; avoid if bleeding risk'],
            ['Metronidazole 400 mg', '400 mg', 'Three times daily', '7–10 days', 'REDUCES post-op pain (RCT evidence) + anaerobic cover'],
            ['Lactulose or Movicol', '15–20 mL / 1–2 sachets', 'Twice daily', '4–6 weeks post-op', 'MANDATORY — prevents hard stool on wound'],
            ['GTN 0.2–0.4% ointment', 'Thin perianal layer', '2–3 times daily', '4–8 weeks', 'Reduces post-op pain; promotes wound healing'],
            ['Topical lidocaine 2% gel', 'Apply to wound', '3–4 times daily', '1–2 weeks', 'Local wound analgesia'],
            ['Sitz baths', 'Warm water 10–15 min', '3 times daily', '4–6 weeks', 'Pain relief + wound hygiene'],
          ],
          [2200, 1600, 1600, 1600, 2000]
        ),

        new Paragraph({ spacing: { after: 120 } }),

        // ─── GRADE IV ──────────────────────────────────
        h2('CASE TYPE 4: Internal Hemorrhoids — Grade IV (Incarcerated / Prolapsed)'),
        p('Presentation: Permanently prolapsed, CANNOT be reduced manually; pain; bleeding; risk of strangulation and gangrene. REQUIRES URGENT SURGICAL CONSULTATION.', true),
        warning('Grade IV hemorrhoids with incarceration or gangrenous tissue require EMERGENCY surgical consultation and potentially urgent hemorrhoidectomy.'),

        h3('Acute Management — Hospital Setting'),
        makeTable(
          ['Drug', 'Dose', 'Route', 'Frequency', 'Duration', 'Purpose'],
          [
            ['Morphine sulfate', '2–4 mg', 'IV', 'Every 2–4 hours PRN', 'Acute admission', 'Severe pain control'],
            ['Ceftriaxone 1–2 g', '1–2 g', 'IV', 'Once daily', '5–7 days', 'Perianal sepsis cover if strangulated'],
            ['Metronidazole 500 mg', '500 mg', 'IV', 'Every 8 hours', '5–7 days', 'Anaerobic bacterial cover'],
            ['MPFF (Daflon) — Acute Protocol', '1500 mg Day 1–4; then 1000 mg Day 5–7', 'Oral', 'Once daily (total 7-day course)', '7 days only', 'Reduces acute hemorrhoidal crisis symptoms'],
          ],
          [1800, 1200, 900, 1800, 1300, 2000]
        ),

        h3('Definitive Treatment'),
        bullet('Elective surgical hemorrhoidectomy if no gangrene'),
        bullet('Emergency hemorrhoidectomy for strangulation — same day'),
        bullet('Gangrene with sepsis: immediate OR debridement + IV broad-spectrum antibiotics (Piperacillin-Tazobactam 4.5 g IV TDS)'),
        p('Post-operative prescription: Same as Grade III hemorrhoidectomy protocol above.'),

        new Paragraph({ children: [new PageBreak()] }),

        // ══════════════════════════════════════════════
        // SECTION 4: EXTERNAL & THROMBOSED HEMORRHOIDS
        // ══════════════════════════════════════════════
        h1('SECTION 4: EXTERNAL & THROMBOSED HEMORRHOIDS'),

        h2('CASE TYPE 5: External Hemorrhoids — Non-Thrombosed'),
        p('Presentation: Painless perianal skin folds (tags), pruritus, hygiene difficulty. No thrombosis.', true),

        h3('Prescription: Conservative Only'),
        makeTable(
          ['Treatment', 'Dose / Application', 'Frequency', 'Duration'],
          [
            ['Psyllium husk', '5–10 g in water', 'Daily', 'Ongoing'],
            ['Docusate sodium', '100 mg', 'Twice daily', '2–4 weeks'],
            ['Pramoxine 1% cream', 'Apply to anal area', '3–4 times daily', 'Max 14 days'],
            ['Witch hazel pads', 'Apply to perianal area', 'After each stool', 'As needed'],
            ['Hydrocortisone 1%', 'Thin layer', 'Twice daily', 'Max 7 days for pruritus'],
            ['Warm sitz baths', '10–15 min warm water', '2–3 times daily', 'Ongoing'],
          ],
          [2500, 2500, 1800, 2200]
        ),
        p('Skin tag removal is an ELECTIVE, cosmetic procedure. Not routinely recommended unless causing significant hygiene disturbance. Performed under local anesthesia outpatient.'),

        new Paragraph({ spacing: { after: 120 } }),
        h2('CASE TYPE 6: Thrombosed External Hemorrhoid (TEH) — ACUTE'),
        p('Presentation: Sudden onset severe perianal pain; firm, tense, blue-purple perianal lump; typically onset within last 48–72 hours.', true),
        warning('TIME-SENSITIVE DECISION: Act within 72 hours of onset for best outcomes.'),

        h3('Decision Tree: Surgical vs Conservative'),
        makeTable(
          ['Presentation', 'Treatment Decision', 'Rationale'],
          [
            ['< 72 hours onset + severe pain or enlarging', 'SURGICAL EXCISION under local anesthesia', 'Faster resolution, lower recurrence, longer remission'],
            ['> 72 hours onset OR pain improving / tolerable', 'CONSERVATIVE MANAGEMENT', 'Thrombus organizes; surgical risk > benefit after 72 hrs'],
          ],
          [2500, 3000, 3500]
        ),

        h3('A. Surgical Excision Protocol (within 72 hours)'),
        p('Excision of thrombus WITH overlying skin (not simple drainage — prevents recurrence)'),
        makeTable(
          ['Drug', 'Dose', 'Route', 'Notes'],
          [
            ['Lidocaine 1–2% + epinephrine 1:200,000', '3–5 mL', 'Subcutaneous perianal infiltration', 'Local anesthetic of choice'],
            ['Bupivacaine 0.25–0.5%', '3–5 mL', 'Subcutaneous perianal infiltration', 'Long-acting alternative (8–12 hr duration)'],
          ],
          [2800, 1200, 2800, 2200]
        ),

        h3('Post-Excision Prescription'),
        makeTable(
          ['Drug', 'Dose', 'Frequency', 'Duration'],
          [
            ['Paracetamol 500–1000 mg', '500–1000 mg', 'Every 6–8 hours PRN', '3–5 days'],
            ['Ibuprofen 400 mg', '400 mg with food', 'Every 8 hours', '3–5 days'],
            ['Docusate sodium', '100 mg', 'Twice daily', '1–2 weeks'],
            ['Sitz baths', 'Warm water 10–15 min', '2–3 times daily', '1–2 weeks'],
          ],
          [2500, 2000, 2500, 2000]
        ),

        h3('B. Conservative Management (beyond 72 hours, or improving symptoms)'),
        makeTable(
          ['Drug/Measure', 'Dose', 'Frequency', 'Duration'],
          [
            ['Warm sitz baths', '10–15 min warm water', '2–3 times daily', '1–2 weeks until resolution'],
            ['Ibuprofen 400 mg', '400 mg with food', 'Every 8 hours', '5–7 days (anti-inflammatory)'],
            ['Docusate sodium 100 mg', '100 mg', 'Twice daily', '2 weeks'],
            ['Topical lidocaine 5% ointment', 'Apply to lump', '3–4 times daily', 'Until pain resolves'],
            ['Witch hazel pads', 'Apply to perianal area', 'After each stool', 'Until resolution'],
            ['MPFF (Daflon) 500 mg', '500 mg', 'Twice daily', '7–10 day acute course'],
            ['Psyllium husk', '5–10 g in water', 'Daily', 'Ongoing to prevent recurrence'],
          ],
          [2500, 1800, 1800, 1900]
        ),
        p('Most thrombosed external hemorrhoids RESOLVE within 48–72 hours on conservative management without intervention.'),

        new Paragraph({ children: [new PageBreak()] }),

        // ══════════════════════════════════════════════
        // SECTION 5: SPECIAL POPULATIONS
        // ══════════════════════════════════════════════
        h1('SECTION 5: SPECIAL POPULATIONS — PRESCRIPTION ADAPTATIONS'),

        h2('CASE TYPE 7: Hemorrhoids in Pregnancy'),
        p('Common in 2nd–3rd trimester and postpartum. Mostly Grades I–III. Office procedures contraindicated during pregnancy and ≤ 8 weeks postpartum.', true),
        warning('ALL invasive procedures (RBL, sclerotherapy, IRC) are CONTRAINDICATED during pregnancy and for 8 weeks postpartum.'),
        makeTable(
          ['Drug', 'Dose', 'Frequency', 'Duration', 'Safety Profile'],
          [
            ['Psyllium husk', '5–10 g in water', 'Daily', 'Ongoing — safest option', 'Safe in all trimesters'],
            ['Lactulose', '15–30 mL', 'Once or twice daily', 'As needed', 'Safe in pregnancy'],
            ['Docusate sodium 100 mg', '100 mg', 'Twice daily', 'Short-term', 'Generally considered safe'],
            ['Pramoxine 1% cream', 'Apply topically', '3–4 times daily', 'Short-term', 'Minimal systemic absorption; preferred over lidocaine'],
            ['Witch hazel pads', 'Topical application', 'After each stool', 'As needed', 'Safe topically'],
            ['Warm sitz baths', '10–15 min warm water', '2–3 times daily', 'As needed', 'Safe and beneficial'],
            ['MPFF (Daflon)', '500 mg', 'Twice daily', 'Short-term acute only; AVOID 1st trimester', 'Limited data; use if benefit > risk in 2nd–3rd trimester'],
            ['Hydrocortisone 1%', 'Thin layer sparingly', 'Twice daily', 'Max 5–7 days only', 'Avoid prolonged use; low-potency only'],
          ],
          [2000, 1400, 1800, 2200, 1600]
        ),
        bullet('AVOID: NSAIDs in 3rd trimester (risk of premature ductus arteriosus closure)'),
        bullet('AVOID: Castor oil laxatives — uterotonic effect'),
        bullet('AVOID: Oral phlebotonics in 1st trimester'),

        new Paragraph({ spacing: { after: 120 } }),
        h2('CASE TYPE 8: Hemorrhoids on Anticoagulation (Warfarin, NOACs, Antiplatelet)'),
        warning('RBL is RELATIVELY CONTRAINDICATED in anticoagulated patients — risk of delayed hemorrhage at band slough (day 7–14).'),
        makeTable(
          ['Procedure', 'Safety', 'Recommendation'],
          [
            ['Sclerotherapy (5% phenol)', 'SAFE', 'PREFERRED office procedure; digital pressure controls needle site bleeding'],
            ['Infrared Coagulation (IRC)', 'Acceptable', 'Less bleeding risk than RBL'],
            ['Rubber Band Ligation (RBL)', 'Relatively contraindicated', 'Only if anticoagulation can be held 7 days before and 7 days after'],
            ['Surgical hemorrhoidectomy', 'Higher risk', 'Requires hematology bridging consultation'],
          ],
          [2500, 1600, 4900]
        ),
        p('Drug Management: Hold aspirin-containing products 7 days pre- and post-procedure if possible. For warfarin: INR should be in therapeutic range before any procedure. Continue fiber and stool softeners as standard.'),

        new Paragraph({ spacing: { after: 120 } }),
        h2('CASE TYPE 9: Hemorrhoids with Portal Hypertension / Anorectal Varices'),
        warning('RBL is ABSOLUTELY CONTRAINDICATED in portal hypertension — risk of massive, life-threatening delayed hemorrhage.'),
        p('Distinguish hemorrhoids from anorectal varices: varices are compressible, refill rapidly, extend across dentate line into rectum.'),
        makeTable(
          ['Scenario', 'Treatment'],
          [
            ['Hemorrhoids in portal hypertension (confirmed, not varices)', 'Sclerotherapy preferred; aggressive conservative management'],
            ['Anorectal varices with bleeding', 'Underrunning with absorbable suture; inferior mesenteric vein embolization; TIPS if needed'],
            ['Portal hypertension + hemorrhoids (mild)', 'Manage portal hypertension (propranolol/carvedilol) first; avoid interventional procedures if possible'],
          ],
          [3000, 6000]
        ),

        new Paragraph({ spacing: { after: 120 } }),
        h2('CASE TYPE 10: Immunocompromised Patients (HIV/AIDS, Active Chemotherapy)'),
        warning('RBL is CONTRAINDICATED in immunocompromised patients — risk of life-threatening pelvic sepsis.'),
        makeTable(
          ['Treatment', 'Recommendation'],
          [
            ['Conservative medical management', 'FIRST-LINE; preferred indefinitely until immune status improves'],
            ['Sclerotherapy', 'Better-studied and preferred over IRC in this population'],
            ['Rubber Band Ligation', 'CONTRAINDICATED — high infection and sepsis risk'],
            ['Surgery', 'High risk; delay until CD4 > 200 cells/µL or remission achieved'],
          ],
          [3500, 5500]
        ),

        new Paragraph({ children: [new PageBreak()] }),

        // ══════════════════════════════════════════════
        // SECTION 6: MIXED & ACUTE HEMORRHOIDAL CRISIS
        // ══════════════════════════════════════════════
        h1('SECTION 6: MIXED HEMORRHOIDS & ACUTE HEMORRHOIDAL CRISIS'),

        h2('CASE TYPE 11: Mixed Internal + External Hemorrhoids'),
        p('Presentation: Combination of internal Grade II–III and external hemorrhoids; prolapse with painful external component.', true),
        p('Office procedures do NOT address the external component. Conventional excisional hemorrhoidectomy is the definitive treatment for symptomatic mixed disease.'),
        makeTable(
          ['Step', 'Treatment', 'Notes'],
          [
            ['Medical bridge (mild–moderate)', 'MPFF 500 mg BD + fiber + stool softeners', 'As bridge to definitive procedure'],
            ['Definitive', 'Conventional hemorrhoidectomy (Milligan-Morgan or Ferguson)', 'Addresses both internal and external components'],
            ['Alternative (minimal external)', 'RBL for internal + conservative for external', 'Only if external component is minor/non-symptomatic'],
          ],
          [1400, 3500, 4100]
        ),

        new Paragraph({ spacing: { after: 120 } }),
        h2('CASE TYPE 12: Acute Hemorrhoidal Crisis / Mass Prolapse'),
        p('Presentation: All three hemorrhoidal columns prolapsed, edematous, irreducible; severe pain; unable to sit.', true),
        warning('Mass prolapse = surgical emergency. Urgent colorectal surgery consultation required.'),
        makeTable(
          ['Drug', 'Dose', 'Route', 'Frequency', 'Duration'],
          [
            ['Morphine 2–4 mg', '2–4 mg', 'IV/IM', 'Every 2–4 hours PRN', 'Acute admission'],
            ['MPFF (Daflon) — Acute Protocol', '1500 mg Days 1–4; 1000 mg Days 5–7', 'Oral', 'Daily', '7 days'],
            ['Ice packs to perineum', 'As tolerated', 'Topical', 'Every 2 hours for first 24 hrs', 'First 24–48 hrs only'],
            ['Diclofenac sodium 75 mg', '75 mg', 'IM/IV', 'Every 12 hours', '24–48 hrs acute phase'],
            ['Broad-spectrum antibiotics if infected', 'Piperacillin/tazobactam 4.5 g', 'IV', 'Every 8 hours', '5–7 days'],
          ],
          [2200, 1800, 1200, 1800, 2000]
        ),

        new Paragraph({ children: [new PageBreak()] }),

        // ══════════════════════════════════════════════
        // SECTION 7: QUICK REFERENCE MASTER TABLE
        // ══════════════════════════════════════════════
        h1('SECTION 7: MASTER QUICK-REFERENCE PRESCRIPTION TABLE'),
        makeTable(
          ['Drug Class', 'Drug', 'Dose', 'Frequency', 'Duration', 'Grade Indication'],
          [
            ['Fiber supplement', 'Psyllium husk (Ispaghula)', '5–10 g in 240 mL water', '1–3x daily', 'Long-term', 'ALL grades'],
            ['Stool softener', 'Docusate sodium', '100 mg', 'Twice daily', '2–4 weeks', 'ALL grades'],
            ['Osmotic laxative', 'Lactulose', '15–30 mL', 'Once–twice daily', 'Short–medium term', 'ALL grades, post-op'],
            ['Osmotic laxative', 'Polyethylene glycol 3350', '17 g in water', 'Once daily', 'Short–medium term', 'Constipation-predominant'],
            ['Topical anesthetic', 'Lidocaine 5% ointment', 'Apply topically', '3–4x daily', 'Max 14 days', 'External/symptomatic I–II'],
            ['Topical anesthetic', 'Pramoxine 1% cream', 'Apply topically', '3–4x daily', 'Max 14 days', 'External/symptomatic; pregnancy safe'],
            ['Topical anesthetic', 'Dibucaine 0.5–1%', 'Apply topically', '3x daily', 'Max 14 days', 'External/symptomatic'],
            ['Topical steroid', 'Hydrocortisone 1–2.5%', 'Thin layer', 'Twice daily', 'MAX 7 days', 'Pruritus short-term only'],
            ['Phlebotonic', 'MPFF / Daflon 500 mg', '500 mg', 'Twice daily', 'Acute 2–3 months; short courses only', 'Grade I–III; Grade A evidence'],
            ['Phlebotonic', 'Diosmin 600 mg', '600 mg', 'Twice daily', 'Short-term acute', 'Grade I–III'],
            ['Phlebotonic', 'Calcium dobesilate', '500 mg', 'Three times daily', 'Short-term ONLY', 'Caution: agranulocytosis risk'],
            ['Analgesic', 'Paracetamol', '500–1000 mg', 'Every 6–8 hours PRN', '3–7 days', 'Post-procedure/surgery pain'],
            ['Analgesic', 'Paracetamol + Codeine 30 mg', '500/30 mg', 'Every 4–6 hours PRN', '5–7 days', 'Post-hemorrhoidectomy'],
            ['NSAID', 'Ibuprofen', '400 mg with food', 'Every 8 hours', '3–7 days', 'TEH, post-procedure, post-op'],
            ['NSAID', 'Diclofenac sodium', '50–75 mg with food/IM', 'Every 8–12 hours', '3–5 days', 'Moderate–severe pain; acute crisis'],
            ['Antibiotic', 'Metronidazole 400 mg', '400 mg', 'Three times daily', '7–10 days', 'Post-hemorrhoidectomy pain reduction'],
            ['Antibiotic', 'Ceftriaxone 1–2 g', '1–2 g', 'Once daily IV', '5–7 days', 'Perianal/pelvic sepsis cover'],
            ['Antibiotic', 'Pip/Taz 4.5 g', '4.5 g', 'Every 8 hours IV', '5–7 days', 'Emergency gangrenous hemorrhoids'],
            ['Topical post-op', 'GTN 0.2–0.4% ointment', 'Thin perianal layer', '2–3x daily', '4–8 weeks', 'Post-hemorrhoidectomy pain + healing'],
            ['Topical post-op', 'Lidocaine 2% gel', 'Apply to wound', '3–4x daily', '1–2 weeks', 'Post-op wound analgesia'],
            ['Sclerosant', '5% phenol in oil', '2–3 mL per column', 'Single session (repeat 4–6 wk)', 'As needed', 'Grade I–II; anticoagulated patients'],
            ['Local anesthetic', 'Lidocaine 1–2% + epinephrine 1:200,000', '3–5 mL perianal', 'Single use', 'Procedure only', 'TEH excision; perianal block'],
            ['Local anesthetic', 'Bupivacaine 0.25–0.5%', '3–5 mL perianal', 'Single use', 'Procedure only (8–12 hr action)', 'Long-acting alternative for excision'],
            ['Opioid', 'Morphine sulfate', '2–4 mg', 'Every 2–4 hours PRN IV', 'Acute admission', 'Grade IV incarcerated; acute crisis'],
          ],
          [1500, 2000, 1500, 1500, 1700, 1800]
        ),

        new Paragraph({ spacing: { after: 200 } }),

        // ─── SOURCES ─────────────────────────────────
        h2('Sources'),
        bullet('Pfenninger and Fowler\'s Procedures for Primary Care, 3rd Edition'),
        bullet('Sleisenger and Fordtran\'s Gastrointestinal and Liver Disease, 11th Edition'),
        bullet('Yamada\'s Textbook of Gastroenterology, 7th Edition'),
        bullet('Sabiston Textbook of Surgery, 21st Edition'),
        bullet('Current Surgical Therapy, 14th Edition'),
        bullet('ASCRS Clinical Practice Guidelines for Hemorrhoids Management, May 2024'),
        bullet('Saudi IDF/SFDA Hemorrhoids Indication Update (CHI CPG)'),
        bullet('ACG Clinical Guidelines: Management of Benign Anorectal Disorders (2021)'),
        bullet('PMID 40596934 — Meta-analysis: surgical vs conservative hemorrhoid treatment (2025)'),
        bullet('PMID 40576944 — Systematic review: operative vs nonoperative thrombosed external hemorrhoids (2026)'),

        new Paragraph({ spacing: { after: 100 } }),
        new Paragraph({
          children: [new TextRun({ text: 'Generated by Orris Medical AI | June 2026 | For educational and clinical reference use only. Always verify doses against current local formulary.', size: 18, color: '7F8C8D', italics: true })],
          alignment: AlignmentType.CENTER,
        }),
      ],
    },
  ],
});

Packer.toBuffer(doc).then((buffer) => {
  fs.writeFileSync('/home/daytona/workspace/piles-treatment/Piles_Hemorrhoids_Treatment_Guide.docx', buffer);
  console.log('SUCCESS: Document written');
}).catch(err => {
  console.error('ERROR:', err);
  process.exit(1);
});
Running Command

cd /home/daytona/workspace/piles-treatment && npm install docx 2>&1 | tail -5

Running Command

node -e "require('docx'); console.log('docx available')" 2>&1 || ls /home/daytona/skills/docx/node_modules/docx 2>/dev/null | head -3

Running Command

cd /home/daytona/workspace/piles-treatment && node build_doc.js 2>&1

Running Command

python3 /home/daytona/skills/docx/scripts/office/validate.py /home/daytona/workspace/piles-treatment/Piles_Hemorrhoids_Treatment_Guide.docx 2>&1 && ls -lh /home/daytona/workspace/piles-treatment/

Running Command

ls -lh /home/daytona/workspace/piles-treatment/ && python3 -c "import zipfile; z=zipfile.ZipFile('/home/daytona/workspace/piles-treatment/Piles_Hemorrhoids_Treatment_Guide.docx'); print('Valid ZIP/DOCX. Files:', z.namelist()[:5])"

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