Gist pathology perseptive

Reading File
Finding Sources
Finding Sources
Searching PubMed

"gastrointestinal stromal tumor" AND pathology

Reading File
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
I now have comprehensive content from multiple authoritative sources. Let me compile the full answer:

Gastrointestinal Stromal Tumor (GIST) - Pathology Perspective

Definition and Historical Context

GIST is the most common mesenchymal neoplasm of the GI tract, accounting for 1-3% of all malignant GI tumors. The term was coined by Mazur and Clark in 1983 as a purely descriptive label for non-epithelial intra-abdominal tumors with mixed smooth muscle and neural histologic features. Before 1999, GISTs were frequently misdiagnosed as leiomyomas, leiomyosarcomas, plexosarcomas, or "gastrointestinal autonomic nerve tumors" due to lack of specific molecular markers. - Sleisenger and Fordtran's Gastrointestinal and Liver Disease

Cell of Origin

GIST originates from the interstitial cells of Cajal (ICC) - the pacemaker cells of the GI muscularis propria that coordinate peristalsis by linking smooth muscle with the autonomic nervous system. ICC and GIST cells share:
  • Ultrastructural features combining neural and muscle phenotypes
  • Expression of CD117 (KIT) and CD34
  • Expression of DOG1 (a calcium-activated chloride channel)
Some evidence also implicates telocytes (ICC-like cells in extra-GI tissues) as potential precursors for extra-gastrointestinal stromal tumors. - Robbins & Kumar Basic Pathology; Sleisenger and Fordtran's

Location Distribution

SiteFrequency
Stomach40-60%
Jejunum / Ileum24-30%
Colon and rectum5-15%
EsophagusRare
GIST can arise anywhere along the GI tract. Notably, PDGFRA-mutant GISTs are overrepresented in the stomach. - Sabiston Textbook of Surgery; Robbins & Kumar

Gross Pathology

  • Typically a solitary, well-circumscribed, fleshy, submucosal mass
  • Cut surface may be tan/white with areas of hemorrhage, necrosis, or cystic change in larger tumors
  • Metastases: multiple small serosal nodules or large nodules in the liver
  • Spread outside the abdomen is uncommon - Robbins & Kumar Basic Pathology

Histopathology

Three main morphologic patterns:
  1. Spindle cell type (~70%): Thin, elongated cells arranged in fascicles or whorls with pale eosinophilic cytoplasm
  2. Epithelioid type (~20%): Plumper, rounded cells with abundant cytoplasm - more common in stomach and PDGFRA-mutant tumors
  3. Mixed type (~10%): Both patterns present
Historically, expression of smooth muscle actin and S100 varied widely among tumors - a one-third each pattern (myogenic, neurogenic, null) was observed before molecular classification. - Sleisenger and Fordtran's GI and Liver Disease

Immunohistochemistry

MarkerPositivityNotes
CD117 (KIT/c-kit)~95%Strong, diffuse cytoplasmic staining; spindle type stains stronger than epithelioid
DOG1~95%Highly specific; positive even in KIT-negative GISTs
CD34~60-70%Vascular/hematopoietic marker; less specific
Smooth muscle actin (SMA)VariableCan be positive, does not exclude GIST
S100Usually negativeUseful to exclude schwannoma
DesminUsually negativeUseful to exclude leiomyosarcoma
Important caveat: CD117 expression can be heterogeneous within a single tumor; a needle biopsy may yield CD117-negative cells purely due to sampling bias. - Sleisenger and Fordtran's

Molecular Pathogenesis

1. KIT (CD117) Mutations - 75-85% of GISTs

  • Gain-of-function mutations in the KIT receptor tyrosine kinase gene (chromosome 4q)
  • The natural KIT ligand is stem cell factor (SCF); binding causes receptor homodimerization, autophosphorylation, and activation of downstream pathways: RAS, RAF, MAPK, AKT, and STAT3
  • Mutations cause constitutive (ligand-independent) receptor activation
Exon locations and imatinib response:
ExonTypeFrequencyImatinib Response
Exon 11 (juxtamembrane domain)Deletion, insertion, substitutionMost common~80-90% response - most sensitive
Exon 9 (extracellular domain)Tandem duplication~10%40-50% response
Exon 13Point mutationRare40-50% response
Exon 17Point mutationRare40-50% response

2. PDGFRA Mutations - ~8% of GISTs

  • Platelet-derived growth factor receptor A, also on chromosome 4q
  • Structurally similar to KIT; mutations activate same downstream signaling
  • KIT and PDGFRA mutations are mutually exclusive
  • D842V substitution in exon 18 is the most common PDGFRA mutation - primary imatinib resistance
  • Other PDGFRA mutations may retain some imatinib sensitivity

3. SDH-Deficient GISTs - ~5-10% of GISTs (most pediatric GISTs)

  • Negative for both KIT and PDGFRA mutations ("wild-type")
  • Mutations in succinate dehydrogenase (SDH) complex subunit genes (SDHA, SDHB, SDHC, SDHD)
  • Loss of SDH leads to: increased reactive oxygen species, HIF activation, increased glycolysis dependency
  • Strong association with Carney triad and Carney-Stratakis syndrome
  • Generally imatinib-insensitive

4. Other Wild-Type GISTs

  • NF1-associated GISTs: Multiple small intestinal GISTs with KIT overexpression but no KIT/PDGFRA mutations
  • Rare mutations in BRAF, KRAS, or other genes
- Quick Compendium of Clinical Pathology 5e; Robbins & Kumar; Sabiston Textbook of Surgery

Risk Stratification

Every GIST has metastatic potential. The three primary prognostic variables are:
  1. Tumor size (most important cutoff: 5 cm and 10 cm)
  2. Mitotic rate (most important cutoff: 5 mitoses/50 HPF)
  3. Tumor site (gastric GISTs are less aggressive than small intestinal/rectal GISTs)
NIH (Fletcher) Consensus Criteria:
RiskSizeMitotic rate
Very low<2 cm<5/50 HPF
Low2-5 cm<5/50 HPF
Intermediate<5 cm OR 5-10 cm6-10/50 HPF OR <5/50 HPF
High>5 cm OR >10 cm OR any>5/50 HPF OR any OR >10/50 HPF
AJCC staging also uses T (size), N (nodal), M (metastasis), and mitotic rate, with separate staging algorithms for gastric vs. non-gastric GISTs given their different biologic behavior. - Fischer's Mastery of Surgery; Current Surgical Therapy 14e; Quick Compendium

Clinical Features and Epidemiology

  • Peak incidence: ~60 years (median); less than 10% in patients under 40
  • Slight male predominance
  • Presentation: mass effect, mucosal ulceration/GI bleeding, obstruction, incidental finding
  • Recurrence or metastasis is rare for gastric GISTs <5 cm but common for mitotically active tumors >10 cm
  • Metastases: most commonly to liver and peritoneum; lymph node spread is uncommon (unlike carcinomas)

Special Syndromes

SyndromeFeatures
Carney TriadGIST + pulmonary chondromas + extra-adrenal paragangliomas; SDH-deficient; no germline mutation found in most
Carney-Stratakis DyadGIST + paraganglioma; germline SDH mutations
Familial GIST syndromeGermline KIT or PDGFRA mutations; multiple GISTs + diffuse ICC hyperplasia
NF1 (von Recklinghausen)Multiple small intestinal GISTs; KIT overexpressed but not mutated; wild-type
  • Quick Compendium of Clinical Pathology 5e; Sabiston

Treatment Overview (Pathology-Relevant Points)

  • Complete surgical resection is the mainstay for localized GIST; negative margins without lymphadenectomy (lymph node mets are rare)
  • Imatinib mesylate (Gleevec) - tyrosine kinase inhibitor targeting KIT and PDGFRA - transformed outcomes for unresectable/metastatic disease
  • Tumor genotype determines imatinib response (KIT exon 11 > exon 9 > wild-type; PDGFRA D842V = resistant)
  • Sunitinib is second-line for imatinib-resistant GIST (specific KIT mutations correlate with sunitinib response)
  • Secondary resistance arises via secondary KIT mutations (as in CML with imatinib)
  • Adjuvant imatinib is recommended for high-risk resected GISTs; optimal duration is 3 years for high-risk cases
  • SDH-deficient GISTs require alternative therapies (see recent systematic review on SDH-deficient GIST therapies, PMID 40045030)

Key Pathology Summary

FeatureDetails
Cell of originInterstitial cells of Cajal
Most common siteStomach (40-60%)
HistologySpindle cell (70%), epithelioid (20%), mixed (10%)
Key IHCCD117, DOG1, CD34
Driver mutationKIT exon 11 (most common)
Best imatinib predictorKIT exon 11 mutation
Most resistant mutationPDGFRA D842V
Prognosis determinantsSize, mitotic rate, site
Metastasis patternLiver and peritoneum
Recent evidence highlights circulating tumor DNA (ctDNA) as an emerging prognostic biomarker in GIST, per a 2025 meta-analysis on ctDNA mutations in GIST (PMID 40665034).

Make pdf

Reading File
Running Command

ls -la /home/daytona/workspace/

Running Command

mkdir -p /home/daytona/workspace/gist-pathology

Writing File

~/gist-pathology/gist_pathology.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
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus import ListFlowable, ListItem

OUTPUT = "/home/daytona/workspace/gist-pathology/GIST_Pathology.pdf"

# ── Colour palette ─────────────────────────────────────────────────────────
DARK_BLUE   = colors.HexColor("#1A3557")
MID_BLUE    = colors.HexColor("#2E6DA4")
LIGHT_BLUE  = colors.HexColor("#D6E8FA")
ACCENT      = colors.HexColor("#E87722")
TABLE_HEAD  = colors.HexColor("#2E6DA4")
TABLE_ALT   = colors.HexColor("#EEF4FB")
WHITE       = colors.white
DARK_GRAY   = colors.HexColor("#333333")
MID_GRAY    = colors.HexColor("#666666")
LIGHT_GRAY  = colors.HexColor("#F5F5F5")

# ── Document setup ──────────────────────────────────────────────────────────
doc = SimpleDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2.2*cm, bottomMargin=2.2*cm,
    title="GIST – Pathology Perspective",
    author="Orris Medical Reference"
)

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

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

def S(name, **kw):
    s = ParagraphStyle(name, **kw)
    return s

cover_title = S("CoverTitle",
    fontSize=32, leading=40, textColor=WHITE,
    fontName="Helvetica-Bold", alignment=TA_CENTER, spaceAfter=8)

cover_sub = S("CoverSub",
    fontSize=15, leading=20, textColor=colors.HexColor("#D0E8FF"),
    fontName="Helvetica", alignment=TA_CENTER, spaceAfter=4)

cover_note = S("CoverNote",
    fontSize=10, leading=14, textColor=colors.HexColor("#B0CCEE"),
    fontName="Helvetica", alignment=TA_CENTER)

h1 = S("H1",
    fontSize=16, leading=20, textColor=WHITE,
    fontName="Helvetica-Bold", alignment=TA_LEFT,
    spaceBefore=6, spaceAfter=6, leftIndent=0)

h2 = S("H2",
    fontSize=12, leading=16, textColor=DARK_BLUE,
    fontName="Helvetica-Bold", alignment=TA_LEFT,
    spaceBefore=10, spaceAfter=4)

body = S("Body",
    fontSize=10, leading=15, textColor=DARK_GRAY,
    fontName="Helvetica", alignment=TA_JUSTIFY,
    spaceAfter=5)

bullet = S("Bullet",
    fontSize=10, leading=15, textColor=DARK_GRAY,
    fontName="Helvetica", alignment=TA_LEFT,
    leftIndent=14, spaceAfter=3,
    bulletIndent=4)

caption = S("Caption",
    fontSize=8, leading=11, textColor=MID_GRAY,
    fontName="Helvetica-Oblique", alignment=TA_CENTER, spaceAfter=4)

key_box = S("KeyBox",
    fontSize=10, leading=15, textColor=DARK_BLUE,
    fontName="Helvetica-Bold", alignment=TA_LEFT,
    leftIndent=10, spaceAfter=3)

source_style = S("Source",
    fontSize=8, leading=11, textColor=MID_GRAY,
    fontName="Helvetica-Oblique", alignment=TA_LEFT,
    spaceAfter=2)

# ── Helper: section header bar ───────────────────────────────────────────────
def section_header(title):
    data = [[Paragraph(title, h1)]]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND", (0,0), (-1,-1), DARK_BLUE),
        ("LEFTPADDING",  (0,0), (-1,-1), 10),
        ("RIGHTPADDING", (0,0), (-1,-1), 10),
        ("TOPPADDING",   (0,0), (-1,-1), 7),
        ("BOTTOMPADDING",(0,0), (-1,-1), 7),
        ("ROUNDEDCORNERS", [4]),
    ]))
    return t

def sub_header(title):
    return Paragraph(title, h2)

def hr():
    return HRFlowable(width="100%", thickness=0.5, color=colors.HexColor("#C0D0E0"), spaceAfter=4)

def spacer(h=0.3):
    return Spacer(1, h*cm)

def bp(txt):
    return Paragraph(f"<bullet>&bull;</bullet> {txt}", bullet)

def source(txt):
    return Paragraph(f"<i>Source: {txt}</i>", source_style)

def info_box(lines):
    items = [Paragraph(l, key_box) for l in lines]
    data = [[item] for item in items]
    t = Table(data, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0), (-1,-1), LIGHT_BLUE),
        ("LEFTPADDING",  (0,0), (-1,-1), 12),
        ("RIGHTPADDING", (0,0), (-1,-1), 12),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("BOX",          (0,0), (-1,-1), 1, MID_BLUE),
    ]))
    return t

# ── Generic table helper ─────────────────────────────────────────────────────
def make_table(headers, rows, col_widths=None):
    th_style = ParagraphStyle("TH", fontSize=9, fontName="Helvetica-Bold",
                               textColor=WHITE, alignment=TA_CENTER, leading=13)
    td_style = ParagraphStyle("TD", fontSize=9, fontName="Helvetica",
                               textColor=DARK_GRAY, alignment=TA_LEFT, leading=13)
    td_c     = ParagraphStyle("TDC", fontSize=9, fontName="Helvetica",
                               textColor=DARK_GRAY, alignment=TA_CENTER, leading=13)

    data = [[Paragraph(h, th_style) for h in headers]]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(c), td_c if j > 0 else td_style)
                     for j, c in enumerate(row)])

    if col_widths is None:
        col_widths = [W / len(headers)] * len(headers)

    t = Table(data, colWidths=col_widths, repeatRows=1)
    style = [
        ("BACKGROUND",   (0,0), (-1,0),  TABLE_HEAD),
        ("TEXTCOLOR",    (0,0), (-1,0),  WHITE),
        ("GRID",         (0,0), (-1,-1), 0.4, colors.HexColor("#AACCEE")),
        ("TOPPADDING",   (0,0), (-1,-1), 5),
        ("BOTTOMPADDING",(0,0), (-1,-1), 5),
        ("LEFTPADDING",  (0,0), (-1,-1), 7),
        ("RIGHTPADDING", (0,0), (-1,-1), 7),
        ("VALIGN",       (0,0), (-1,-1), "MIDDLE"),
    ]
    for i in range(1, len(data)):
        if i % 2 == 0:
            style.append(("BACKGROUND", (0,i), (-1,i), TABLE_ALT))
    t.setStyle(TableStyle(style))
    return t

# ══════════════════════════════════════════════════════════════════════════════
# BUILD STORY
# ══════════════════════════════════════════════════════════════════════════════
story = []

# ── COVER PAGE ────────────────────────────────────────────────────────────────
cover_bg = Table(
    [[Paragraph("GASTROINTESTINAL STROMAL TUMOR", cover_title)],
     [Paragraph("GIST — A Pathology Perspective", cover_sub)],
     [spacer(0.4)],
     [Paragraph("Molecular Pathology · Histopathology · IHC · Risk Stratification · Treatment Implications", cover_note)],
     [spacer(0.6)],
     [Paragraph("Based on: Robbins &amp; Kumar Basic Pathology · Sleisenger &amp; Fordtran's GI and Liver Disease<br/>"
                "Sabiston Textbook of Surgery · Quick Compendium of Clinical Pathology 5e<br/>"
                "Fischer's Mastery of Surgery · Current Surgical Therapy 14e", cover_note)],
     [spacer(0.4)],
     [Paragraph("Prepared by Orris Medical Reference · July 2026", cover_note)],
    ],
    colWidths=[W]
)
cover_bg.setStyle(TableStyle([
    ("BACKGROUND",   (0,0), (-1,-1), DARK_BLUE),
    ("TOPPADDING",   (0,0), (-1,-1), 18),
    ("BOTTOMPADDING",(0,0), (-1,-1), 18),
    ("LEFTPADDING",  (0,0), (-1,-1), 20),
    ("RIGHTPADDING", (0,0), (-1,-1), 20),
    ("ROUNDEDCORNERS", [8]),
]))
story.append(spacer(2))
story.append(cover_bg)
story.append(PageBreak())

# ══════════════════════════════════════════════════════════════════════════════
# 1. DEFINITION & HISTORY
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("1. Definition and Historical Context"))
story.append(spacer(0.3))
story.append(Paragraph(
    "Gastrointestinal stromal tumor (GIST) is the <b>most common mesenchymal neoplasm of the GI tract</b>, "
    "accounting for 1–3% of all malignant GI tumors. The term was coined by <b>Mazur and Clark in 1983</b> as "
    "a descriptive label for non-epithelial intra-abdominal tumors exhibiting mixed smooth muscle and neural "
    "histologic features.", body))
story.append(Paragraph(
    "Before 1999, GISTs were frequently misdiagnosed as <b>leiomyomas, leiomyosarcomas, plexosarcomas</b>, or "
    "'gastrointestinal autonomic nerve tumors' due to the absence of specific molecular markers. "
    "Consistent classification became possible only after the landmark 1998 discovery of near-universal "
    "<b>KIT (CD117) expression</b> and gain-of-function KIT mutations in these tumors.", body))
story.append(source("Sleisenger and Fordtran's Gastrointestinal and Liver Disease; Maingot's Abdominal Operations"))
story.append(spacer(0.2))

# ══════════════════════════════════════════════════════════════════════════════
# 2. CELL OF ORIGIN
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("2. Cell of Origin"))
story.append(spacer(0.3))
story.append(Paragraph(
    "GIST originates from the <b>interstitial cells of Cajal (ICC)</b> — the pacemaker cells of the GI "
    "muscularis propria that coordinate peristalsis by linking smooth muscle cells with the autonomic "
    "nervous system. ICC and GIST cells share:", body))
for item in [
    "Ultrastructural features combining neural and muscle phenotypes",
    "Strong expression of <b>CD117 (KIT)</b> and <b>CD34</b>",
    "Expression of <b>DOG1</b> (a calcium-activated chloride channel — also called ANO1)",
    "Potential origin from telocytes in extra-GI locations (explaining pancreatic and mesenteric GISTs)",
]:
    story.append(bp(item))
story.append(source("Robbins & Kumar Basic Pathology; Sleisenger and Fordtran's"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 3. ANATOMIC DISTRIBUTION
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("3. Anatomic Distribution"))
story.append(spacer(0.3))
story.append(make_table(
    ["Site", "Frequency (%)"],
    [["Stomach", "40 – 60"],
     ["Jejunum / Ileum", "24 – 30"],
     ["Colon and Rectum", "5 – 15"],
     ["Duodenum", "~5"],
     ["Esophagus / Mesentery / Other", "<5"]],
    col_widths=[W*0.6, W*0.4]
))
story.append(spacer(0.15))
story.append(Paragraph(
    "<b>Note:</b> PDGFRA-mutant GISTs are overrepresented in the stomach. "
    "Non-gastric GISTs (especially small intestinal and rectal) carry a worse prognosis than gastric GISTs "
    "of the same size and mitotic rate.", body))
story.append(source("Sabiston Textbook of Surgery; Robbins & Kumar Basic Pathology"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 4. GROSS PATHOLOGY
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("4. Gross Pathology"))
story.append(spacer(0.3))
for item in [
    "<b>Solitary, well-circumscribed, fleshy submucosal mass</b> — most common presentation",
    "Cut surface: tan-white to pinkish; haemorrhage, necrosis, or cystic change in larger tumors",
    "Arises from the muscularis propria; may project endoluminally, exophytically, or both (dumbbell shape)",
    "Metastases: multiple small serosal nodules or large nodules in the <b>liver</b>",
    "Peritoneal seeding is common; spread outside the abdomen is uncommon",
    "<b>Lymph node metastasis is rare</b> — unlike carcinomas (exception: SDH-deficient pediatric GISTs)",
]:
    story.append(bp(item))
story.append(source("Robbins & Kumar Basic Pathology"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 5. HISTOPATHOLOGY
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("5. Histopathology"))
story.append(spacer(0.3))
story.append(Paragraph("Three main morphologic patterns:", h2))
story.append(make_table(
    ["Pattern", "Frequency", "Characteristics"],
    [["Spindle cell type", "~70%",
      "Thin, elongated cells in fascicles/whorls; pale eosinophilic cytoplasm; palisading nuclei"],
     ["Epithelioid type", "~20%",
      "Plumper, rounded cells; abundant clear/eosinophilic cytoplasm; more common in stomach & PDGFRA-mutant tumors"],
     ["Mixed type", "~10%",
      "Both spindle and epithelioid components present in same tumor"]],
    col_widths=[W*0.22, W*0.15, W*0.63]
))
story.append(spacer(0.2))
story.append(Paragraph(
    "Histologic features alone are insufficient for diagnosis. The pre-1999 era saw wide variation "
    "in smooth muscle actin (SMA) and S100 expression, leading to a proposed 'one-third each' classification "
    "(myogenic / neurogenic / null phenotype) — now superseded by molecular markers.", body))
story.append(source("Sleisenger and Fordtran's Gastrointestinal and Liver Disease"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 6. IMMUNOHISTOCHEMISTRY
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("6. Immunohistochemistry (IHC)"))
story.append(spacer(0.3))
story.append(make_table(
    ["Marker", "Positivity", "Notes"],
    [["CD117 (KIT / c-kit)", "~95%",
      "Strong, diffuse cytoplasmic staining; spindle type > epithelioid; can be heterogeneous within tumor"],
     ["DOG1 (ANO1)", "~95%",
      "Highly specific; positive even in KIT-negative GISTs — essential second-line marker"],
     ["CD34", "~60–70%",
      "Vascular/hematopoietic marker; less specific; useful supportive evidence"],
     ["Smooth muscle actin (SMA)", "Variable (~30–40%)",
      "Can be positive; does not exclude GIST"],
     ["S100 protein", "Usually negative",
      "Useful to exclude schwannoma (S100+)"],
     ["Desmin", "Usually negative",
      "Useful to exclude leiomyosarcoma (desmin+)"],
     ["SDHB", "Negative in SDH-deficient",
      "Loss of SDHB staining identifies SDH-deficient wild-type GISTs"],
    ],
    col_widths=[W*0.28, W*0.22, W*0.50]
))
story.append(spacer(0.15))
story.append(info_box([
    "⚠  Important: CD117 expression can be heterogeneous within a single tumor.",
    "    A needle biopsy may yield CD117-negative cells purely due to sampling bias.",
    "    Always use DOG1 alongside CD117 in diagnostically challenging cases.",
]))
story.append(source("Sleisenger and Fordtran's; Sabiston Textbook of Surgery"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 7. MOLECULAR PATHOGENESIS
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("7. Molecular Pathogenesis"))
story.append(spacer(0.3))

story.append(sub_header("7.1 KIT Mutations (75–85% of GISTs)"))
story.append(Paragraph(
    "The KIT gene (chromosome 4q12) encodes a transmembrane receptor tyrosine kinase. "
    "Its natural ligand is <b>stem cell factor (SCF)</b>; binding causes receptor homodimerization, "
    "autophosphorylation, and activation of downstream signaling: <b>RAS, RAF, MAPK, AKT, and STAT3</b>. "
    "Gain-of-function mutations cause <b>constitutive (ligand-independent) receptor activation</b>, "
    "driving uncontrolled cell proliferation.", body))
story.append(spacer(0.15))
story.append(make_table(
    ["Exon (Domain)", "Mutation Type", "Frequency", "Imatinib Response"],
    [["Exon 11 (juxtamembrane)", "Deletion, insertion, point mutation", "Most common (~70%)", "~80–90% — most sensitive"],
     ["Exon 9 (extracellular)", "Tandem duplication AY502-503", "~10–15%", "40–50% (higher dose needed)"],
     ["Exon 13 (kinase domain I)", "Point mutation (K642E)", "Rare", "40–50%"],
     ["Exon 17 (kinase domain II)", "Point mutation", "Rare", "40–50%"],
    ],
    col_widths=[W*0.27, W*0.30, W*0.20, W*0.23]
))
story.append(spacer(0.3))

story.append(sub_header("7.2 PDGFRA Mutations (~8% of GISTs)"))
for item in [
    "Platelet-derived growth factor receptor A (PDGFRA), also on chromosome 4q12",
    "Structurally similar to KIT; mutations activate the <b>same downstream signaling pathways</b>",
    "<b>KIT and PDGFRA mutations are mutually exclusive</b> (both activate the same pathways)",
    "Overrepresented in gastric and epithelioid GISTs",
    "<b>D842V substitution in exon 18</b> = most common PDGFRA mutation = <b>primary imatinib resistance</b>",
    "Other PDGFRA mutations may retain some imatinib sensitivity; avapritinib is effective against D842V",
]:
    story.append(bp(item))
story.append(spacer(0.3))

story.append(sub_header("7.3 SDH-Deficient GISTs (~5–10%; majority of pediatric GISTs)"))
for item in [
    "Negative for both KIT and PDGFRA mutations ('wild-type')",
    "Mutations in <b>SDHA, SDHB, SDHC, or SDHD</b> subunit genes of the mitochondrial succinate dehydrogenase complex",
    "Loss of SDH → ↑ reactive oxygen species, HIF activation, Warburg-type glycolysis dependency",
    "Multifocal gastric GISTs; lymph node metastases more common",
    "Associated with <b>Carney triad</b> and <b>Carney-Stratakis syndrome</b>",
    "Generally <b>imatinib-insensitive</b>; require alternative/experimental therapies",
    "<b>SDHB IHC</b>: loss of staining identifies SDH-deficient tumors",
]:
    story.append(bp(item))
story.append(spacer(0.3))

story.append(sub_header("7.4 Other Wild-Type GISTs"))
story.append(make_table(
    ["Subtype", "Molecular Feature", "Notes"],
    [["NF1-associated", "KIT overexpression; KIT/PDGFRA unmutated", "Multiple small intestinal GISTs; NF1 loss drives ICC hyperplasia"],
     ["BRAF-mutant", "BRAF V600E", "Rare; may respond to BRAF inhibitors"],
     ["KRAS-mutant", "KRAS mutation", "Very rare"],
     ["Familial GIST", "Germline KIT or PDGFRA mutation", "Multiple GISTs + diffuse ICC hyperplasia; autosomal dominant"],
    ],
    col_widths=[W*0.22, W*0.30, W*0.48]
))
story.append(source("Quick Compendium of Clinical Pathology 5e; Robbins & Kumar; Sabiston Textbook of Surgery"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 8. RISK STRATIFICATION
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("8. Risk Stratification"))
story.append(spacer(0.3))
story.append(info_box([
    "Core principle: Every GIST carries metastatic potential — there is NO truly benign GIST.",
    "Three primary prognostic variables: (1) Tumor size  (2) Mitotic rate  (3) Primary site",
]))
story.append(spacer(0.25))

story.append(sub_header("NIH (Fletcher) Consensus Risk Classification"))
story.append(make_table(
    ["Risk Category", "Size", "Mitotic Rate"],
    [["Very Low", "< 2 cm", "< 5 / 50 HPF"],
     ["Low", "2 – 5 cm", "< 5 / 50 HPF"],
     ["Intermediate", "< 5 cm  OR  5–10 cm", "6–10 / 50 HPF  OR  < 5 / 50 HPF"],
     ["High", "> 5 cm  OR  > 10 cm  OR  any", "> 5 / 50 HPF  OR  any  OR  > 10 / 50 HPF"],
    ],
    col_widths=[W*0.22, W*0.38, W*0.40]
))
story.append(spacer(0.2))
story.append(Paragraph(
    "The <b>Joensuu/Armed Forces Institute of Pathology (AFIP) system</b> and <b>AJCC staging</b> "
    "also incorporate tumor location, with separate algorithms for gastric vs. non-gastric GISTs. "
    "Non-gastric site (especially small intestine and rectum) confers higher risk at any given size "
    "and mitotic rate. Tumor rupture — spontaneous or operative — dramatically increases recurrence risk.", body))
story.append(source("Fischer's Mastery of Surgery 8e; Current Surgical Therapy 14e; Quick Compendium of Clinical Pathology 5e"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 9. CLINICAL FEATURES
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("9. Clinical Features"))
story.append(spacer(0.3))
story.append(make_table(
    ["Feature", "Details"],
    [["Peak incidence", "~60 years; < 10% in patients under 40"],
     ["Sex", "Slight male predominance"],
     ["Presentation", "GI bleeding, mass effect, obstruction, or incidental finding"],
     ["Metastatic sites", "Liver (most common) and peritoneum; lymph nodes rare"],
     ["Prognosis (gastric)", "Recurrence rare for < 5 cm; common for mitotically active > 10 cm"],
     ["Prognosis (non-gastric)", "More aggressive at any given size/mitotic rate"],
    ],
    col_widths=[W*0.35, W*0.65]
))
story.append(source("Robbins & Kumar Basic Pathology"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 10. SPECIAL SYNDROMES
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("10. GIST in Hereditary Syndromes"))
story.append(spacer(0.3))
story.append(make_table(
    ["Syndrome", "GIST Features", "Molecular Basis"],
    [["Carney Triad",
      "GIST + pulmonary chondromas + extra-adrenal paragangliomas; gastric; multifocal; young females",
      "SDH-deficient; no germline mutation in most cases (somatic/epigenetic SDHC)"],
     ["Carney-Stratakis Dyad",
      "GIST + paraganglioma; multifocal gastric GIST",
      "Germline SDH subunit mutations (SDHA/B/C/D)"],
     ["Familial GIST Syndrome",
      "Multiple GISTs; diffuse ICC hyperplasia; hyperpigmentation",
      "Germline KIT or PDGFRA mutations; autosomal dominant"],
     ["NF1 (von Recklinghausen)",
      "Multiple small intestinal GISTs; GIST often incidental; low mitotic rate",
      "NF1 loss; KIT overexpressed but unmutated"],
    ],
    col_widths=[W*0.25, W*0.38, W*0.37]
))
story.append(source("Quick Compendium of Clinical Pathology 5e; Sabiston Textbook of Surgery"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 11. TREATMENT IMPLICATIONS (Pathology-Relevant)
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("11. Treatment Implications from a Pathology Perspective"))
story.append(spacer(0.3))

story.append(sub_header("Surgery"))
for item in [
    "Complete surgical resection (R0) is the primary treatment for localized GIST",
    "<b>No routine lymphadenectomy</b> — lymph node spread is rare in KIT/PDGFRA-mutant GIST",
    "Avoid tumor rupture — dramatically increases peritoneal recurrence risk",
    "Margins: 1–2 cm; pseudocapsule should remain intact",
]:
    story.append(bp(item))
story.append(spacer(0.2))

story.append(sub_header("Imatinib Mesylate (Gleevec) — Tyrosine Kinase Inhibitor"))
story.append(make_table(
    ["Mutation", "Imatinib Sensitivity"],
    [["KIT exon 11", "High (~80–90%); first-line for advanced/metastatic disease"],
     ["KIT exon 9", "Moderate (40–50%); higher dose (800 mg/day) may improve response"],
     ["KIT exon 13 / 17", "Moderate; sunitinib may be preferred"],
     ["PDGFRA non-D842V", "Variable; may respond"],
     ["PDGFRA D842V", "Resistant — avapritinib is preferred"],
     ["Wild-type (SDH-deficient)", "Generally resistant; experimental therapies"],
     ["Wild-type (NF1)", "May respond; partial evidence"],
    ],
    col_widths=[W*0.42, W*0.58]
))
story.append(spacer(0.15))
story.append(Paragraph(
    "<b>Adjuvant imatinib</b>: Recommended for 3 years in high-risk resected GISTs with imatinib-sensitive mutations. "
    "<b>Neoadjuvant imatinib</b>: Used for marginally resectable disease until maximal response. "
    "<b>Lifelong therapy</b> for metastatic/unresectable GIST based on current evidence. "
    "<b>Sunitinib</b> is second-line for imatinib-resistant disease.", body))
story.append(source("Goodman & Gilman's Pharmacological Basis of Therapeutics; Schwartz's Principles of Surgery 11e"))
story.append(spacer(0.3))

# ══════════════════════════════════════════════════════════════════════════════
# 12. KEY PATHOLOGY SUMMARY TABLE
# ══════════════════════════════════════════════════════════════════════════════
story.append(section_header("12. Key Pathology Summary"))
story.append(spacer(0.3))
story.append(make_table(
    ["Feature", "Key Details"],
    [["Cell of origin", "Interstitial cells of Cajal (pacemaker cells of GI muscularis propria)"],
     ["Most common site", "Stomach (40–60%)"],
     ["Histologic patterns", "Spindle cell (~70%), Epithelioid (~20%), Mixed (~10%)"],
     ["Defining IHC markers", "CD117 (KIT) and DOG1 — both ~95% sensitive"],
     ["Most common mutation", "KIT exon 11 deletion/insertion (~70% of all GISTs)"],
     ["Best imatinib predictor", "KIT exon 11 mutation"],
     ["Imatinib-resistant mutation", "PDGFRA exon 18 D842V"],
     ["Prognosis determinants", "Tumor size, mitotic rate, anatomic site (+ rupture status)"],
     ["Metastasis pattern", "Liver and peritoneum (lymph nodes spared in most cases)"],
     ["Pediatric/SDH-deficient", "Multifocal; gastric; lymph node mets possible; imatinib-resistant"],
    ],
    col_widths=[W*0.38, W*0.62]
))
story.append(spacer(0.3))

# ── FOOTER NOTE ───────────────────────────────────────────────────────────────
story.append(hr())
story.append(Paragraph(
    "Recent evidence: A 2025 systematic review (PMID 40665034) identified circulating tumor DNA (ctDNA) "
    "mutations as an emerging prognostic biomarker in GIST. An SDH-deficient GIST therapy review (PMID 40045030, 2025) "
    "summarises alternative systemic options for imatinib-resistant wild-type cases.",
    source_style))
story.append(Paragraph(
    "This document is for educational reference only. Clinical decisions should be based on current guidelines "
    "and individualised assessment.",
    source_style))

# ══════════════════════════════════════════════════════════════════════════════
# BUILD PDF
# ══════════════════════════════════════════════════════════════════════════════
doc.build(story)
print(f"PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/gist-pathology && python gist_pathology.py

Your PDF is ready:

GIST Pathology

PDF Document · PDF

The document covers all 12 sections with colour-coded section headers, formatted tables, and info-boxes:
  1. Definition & Historical Context
  2. Cell of Origin (Interstitial cells of Cajal)
  3. Anatomic Distribution table
  4. Gross Pathology
  5. Histopathology (spindle / epithelioid / mixed)
  6. Immunohistochemistry (CD117, DOG1, CD34, SMA, S100, SDHB)
  7. Molecular Pathogenesis (KIT exons, PDGFRA, SDH-deficient, other wild-type)
  8. Risk Stratification (NIH Fletcher criteria)
  9. Clinical Features
  10. Hereditary Syndromes (Carney Triad, NF1, Familial GIST)
  11. Treatment Implications (surgery, imatinib response by mutation)
  12. Key Pathology Summary table

Vive me in pdf format all about gist patbology student

Running Command

ls /home/daytona/workspace/gist-pathology/

Writing File

~/gist-pathology/gist_student.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, PageBreak, KeepTogether, Frame, NextPageTemplate
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY, TA_RIGHT
from reportlab.platypus import BaseDocTemplate, PageTemplate
from reportlab.platypus.flowables import Flowable
import math

OUTPUT = "/home/daytona/workspace/gist-pathology/GIST_Student_Guide.pdf"

W_PAGE, H_PAGE = A4
LM = RM = 1.8*cm
TM = BM = 1.8*cm
W = W_PAGE - LM - RM

# ── COLOUR PALETTE ────────────────────────────────────────────────────────────
C_NAVY      = colors.HexColor("#0D2B55")
C_BLUE      = colors.HexColor("#1565C0")
C_BLUE_MID  = colors.HexColor("#2196F3")
C_BLUE_LITE = colors.HexColor("#BBDEFB")
C_BLUE_XLIT = colors.HexColor("#E3F2FD")
C_TEAL      = colors.HexColor("#00838F")
C_TEAL_LITE = colors.HexColor("#E0F7FA")
C_ORANGE    = colors.HexColor("#E65100")
C_ORANGE_L  = colors.HexColor("#FFF3E0")
C_GREEN     = colors.HexColor("#2E7D32")
C_GREEN_L   = colors.HexColor("#E8F5E9")
C_RED       = colors.HexColor("#C62828")
C_RED_L     = colors.HexColor("#FFEBEE")
C_PURPLE    = colors.HexColor("#6A1B9A")
C_PURPLE_L  = colors.HexColor("#F3E5F5")
C_YELLOW    = colors.HexColor("#F9A825")
C_YELLOW_L  = colors.HexColor("#FFFDE7")
C_GRAY_D    = colors.HexColor("#212121")
C_GRAY_M    = colors.HexColor("#546E7A")
C_GRAY_L    = colors.HexColor("#ECEFF1")
C_WHITE     = colors.white

# ── STYLES ────────────────────────────────────────────────────────────────────
def PS(name, **kw):
    return ParagraphStyle(name, **kw)

COVER_MAIN  = PS("CoverMain",  fontSize=38, leading=46, fontName="Helvetica-Bold",
                  textColor=C_WHITE,  alignment=TA_CENTER, spaceAfter=6)
COVER_ABBR  = PS("CoverAbbr",  fontSize=22, leading=28, fontName="Helvetica-Bold",
                  textColor=colors.HexColor("#90CAF9"), alignment=TA_CENTER, spaceAfter=4)
COVER_SUB   = PS("CoverSub",   fontSize=13, leading=18, fontName="Helvetica",
                  textColor=colors.HexColor("#BBDEFB"), alignment=TA_CENTER, spaceAfter=3)
COVER_NOTE  = PS("CoverNote",  fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=colors.HexColor("#90A4AE"), alignment=TA_CENTER)

SEC_TITLE   = PS("SecTitle",   fontSize=14, leading=18, fontName="Helvetica-Bold",
                  textColor=C_WHITE, alignment=TA_LEFT)
H2_STYLE    = PS("H2",         fontSize=12, leading=16, fontName="Helvetica-Bold",
                  textColor=C_NAVY, spaceBefore=8, spaceAfter=4)
H3_STYLE    = PS("H3",         fontSize=10, leading=14, fontName="Helvetica-Bold",
                  textColor=C_BLUE, spaceBefore=6, spaceAfter=3)
BODY        = PS("Body",       fontSize=10, leading=15, fontName="Helvetica",
                  textColor=C_GRAY_D, alignment=TA_JUSTIFY, spaceAfter=4)
BODY_SML    = PS("BodySml",    fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=C_GRAY_D, alignment=TA_JUSTIFY, spaceAfter=3)
BULLET      = PS("Bullet",     fontSize=10, leading=15, fontName="Helvetica",
                  textColor=C_GRAY_D, leftIndent=16, bulletIndent=4, spaceAfter=2)
BULLET_SML  = PS("BulletSml",  fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=C_GRAY_D, leftIndent=16, bulletIndent=4, spaceAfter=2)
NOTE        = PS("Note",       fontSize=8,  leading=11, fontName="Helvetica-Oblique",
                  textColor=C_GRAY_M, alignment=TA_LEFT, spaceAfter=2)
MNEMONIC    = PS("Mnemonic",   fontSize=11, leading=16, fontName="Helvetica-Bold",
                  textColor=C_NAVY, alignment=TA_CENTER, spaceAfter=2)
MNEM_BODY   = PS("MnemBody",   fontSize=10, leading=15, fontName="Helvetica",
                  textColor=C_GRAY_D, alignment=TA_LEFT)
TH_S        = PS("THS",        fontSize=9,  leading=13, fontName="Helvetica-Bold",
                  textColor=C_WHITE, alignment=TA_CENTER)
TD_S        = PS("TDS",        fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=C_GRAY_D, alignment=TA_LEFT)
TD_C        = PS("TDC",        fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=C_GRAY_D, alignment=TA_CENTER)
EXAM_Q      = PS("ExamQ",      fontSize=10, leading=15, fontName="Helvetica-Bold",
                  textColor=C_NAVY, leftIndent=6, spaceAfter=2)
EXAM_A      = PS("ExamA",      fontSize=10, leading=15, fontName="Helvetica",
                  textColor=C_GREEN, leftIndent=20, spaceAfter=4)
KEYPOINT    = PS("KeyPoint",   fontSize=10, leading=15, fontName="Helvetica-Bold",
                  textColor=C_ORANGE, alignment=TA_LEFT, leftIndent=10)
CHAPTER_NUM = PS("ChapNum",    fontSize=48, leading=52, fontName="Helvetica-Bold",
                  textColor=colors.HexColor("#1565C020"), alignment=TA_RIGHT)

# ── HELPER FLOWABLES ─────────────────────────────────────────────────────────
def sp(h=0.3): return Spacer(1, h*cm)
def hr(col=colors.HexColor("#CFD8DC")):
    return HRFlowable(width="100%", thickness=0.5, color=col, spaceAfter=4)

def section_bar(title, color=C_NAVY, num=""):
    inner = f"{num}  {title}" if num else title
    cell = [Paragraph(inner, SEC_TITLE)]
    t = Table([cell], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), color),
        ("LEFTPADDING",  (0,0),(-1,-1), 12),
        ("TOPPADDING",   (0,0),(-1,-1), 9),
        ("BOTTOMPADDING",(0,0),(-1,-1), 9),
        ("RIGHTPADDING", (0,0),(-1,-1), 12),
    ]))
    return t

def callout(lines, bg=C_BLUE_XLIT, border=C_BLUE_MID, style=None):
    st = style or BODY_SML
    rows = [[Paragraph(l, st)] for l in lines]
    t = Table(rows, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), bg),
        ("BOX",          (0,0),(-1,-1), 1.2, border),
        ("LEFTPADDING",  (0,0),(-1,-1), 12),
        ("RIGHTPADDING", (0,0),(-1,-1), 12),
        ("TOPPADDING",   (0,0),(-1,-1), 6),
        ("BOTTOMPADDING",(0,0),(-1,-1), 6),
    ]))
    return t

def warning_box(lines):
    return callout(["⚠  " + l for l in lines], bg=C_YELLOW_L, border=C_YELLOW,
                   style=PS("Warn", fontSize=9, leading=13, fontName="Helvetica-Bold",
                             textColor=C_GRAY_D))

def fact_box(lines):
    return callout(lines, bg=C_GREEN_L, border=C_GREEN)

def exam_box(pairs):
    """pairs = list of (question, answer)"""
    rows = []
    for q, a in pairs:
        rows.append([Paragraph(f"Q:  {q}", EXAM_Q)])
        rows.append([Paragraph(f"A:  {a}", EXAM_A)])
    t = Table(rows, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(-1,-1), C_BLUE_XLIT),
        ("BOX",          (0,0),(-1,-1), 1.2, C_BLUE),
        ("LEFTPADDING",  (0,0),(-1,-1), 10),
        ("RIGHTPADDING", (0,0),(-1,-1), 10),
        ("TOPPADDING",   (0,0),(-1,-1), 4),
        ("BOTTOMPADDING",(0,0),(-1,-1), 4),
    ]))
    return t

def mnemonic_box(title, items):
    """items = list of (letter_bold, rest_of_text)"""
    rows = [[Paragraph(f"<b>{lt}</b>  —  {desc}", MNEM_BODY)] for lt, desc in items]
    header = [[Paragraph(f"🔑  MNEMONIC:  {title}", MNEMONIC)]]
    all_rows = header + rows
    t = Table(all_rows, colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",   (0,0),(0,0),  C_PURPLE_L),
        ("BACKGROUND",   (0,1),(-1,-1),C_PURPLE_L),
        ("BOX",          (0,0),(-1,-1), 1.5, C_PURPLE),
        ("LINEBELOW",    (0,0),(0,0),   1,   C_PURPLE),
        ("LEFTPADDING",  (0,0),(-1,-1), 14),
        ("RIGHTPADDING", (0,0),(-1,-1), 14),
        ("TOPPADDING",   (0,0),(-1,-1), 5),
        ("BOTTOMPADDING",(0,0),(-1,-1), 5),
    ]))
    return t

def make_table(headers, rows, col_widths=None, hdr_color=C_BLUE):
    if col_widths is None:
        col_widths = [W / len(headers)] * len(headers)
    data = [[Paragraph(h, TH_S) for h in headers]]
    for i, row in enumerate(rows):
        data.append([Paragraph(str(c), TD_C if j > 0 else TD_S) for j, c in enumerate(row)])
    t = Table(data, colWidths=col_widths, repeatRows=1)
    sty = [
        ("BACKGROUND",   (0,0),(-1,0),  hdr_color),
        ("GRID",         (0,0),(-1,-1), 0.4, colors.HexColor("#B0BEC5")),
        ("TOPPADDING",   (0,0),(-1,-1), 5),
        ("BOTTOMPADDING",(0,0),(-1,-1), 5),
        ("LEFTPADDING",  (0,0),(-1,-1), 7),
        ("RIGHTPADDING", (0,0),(-1,-1), 7),
        ("VALIGN",       (0,0),(-1,-1), "MIDDLE"),
    ]
    for i in range(1, len(data)):
        if i % 2 == 0:
            sty.append(("BACKGROUND", (0,i),(-1,i), C_BLUE_XLIT))
    t.setStyle(TableStyle(sty))
    return t

def bp(txt, style=BULLET):
    return Paragraph(f"<bullet>•</bullet>  {txt}", style)

def two_col(left_items, right_items, lw=None, rw=None):
    lw = lw or W*0.5 - 4
    rw = rw or W*0.5 - 4
    left_para  = [bp(x) for x in left_items]
    right_para = [bp(x) for x in right_items]
    # Pad to same length
    while len(left_para) < len(right_para):  left_para.append(sp(0.1))
    while len(right_para) < len(left_para): right_para.append(sp(0.1))
    rows = list(zip(left_para, right_para))
    t = Table(rows, colWidths=[lw, rw])
    t.setStyle(TableStyle([
        ("VALIGN",       (0,0),(-1,-1), "TOP"),
        ("LEFTPADDING",  (0,0),(-1,-1), 2),
        ("RIGHTPADDING", (0,0),(-1,-1), 2),
        ("TOPPADDING",   (0,0),(-1,-1), 1),
        ("BOTTOMPADDING",(0,0),(-1,-1), 1),
    ]))
    return t

# ══════════════════════════════════════════════════════════════════════════════
# PAGE NUMBERING
# ══════════════════════════════════════════════════════════════════════════════
def on_page(canvas, doc):
    canvas.saveState()
    # Header bar
    canvas.setFillColor(C_NAVY)
    canvas.rect(0, H_PAGE-1.1*cm, W_PAGE, 1.1*cm, fill=1, stroke=0)
    canvas.setFillColor(C_WHITE)
    canvas.setFont("Helvetica-Bold", 9)
    canvas.drawString(LM, H_PAGE-0.75*cm, "GIST — Gastrointestinal Stromal Tumor")
    canvas.setFont("Helvetica", 8)
    canvas.drawRightString(W_PAGE-RM, H_PAGE-0.75*cm, "Student Pathology Guide")
    # Footer
    canvas.setFillColor(C_NAVY)
    canvas.rect(0, 0, W_PAGE, 0.9*cm, fill=1, stroke=0)
    canvas.setFillColor(C_WHITE)
    canvas.setFont("Helvetica", 8)
    canvas.drawString(LM, 0.33*cm, "For educational use · Orris Medical Reference · 2026")
    canvas.setFont("Helvetica-Bold", 9)
    canvas.drawRightString(W_PAGE-RM, 0.33*cm, f"Page {doc.page}")
    canvas.restoreState()

def on_cover(canvas, doc):
    # Full bleed gradient background
    canvas.saveState()
    # Dark navy background
    canvas.setFillColor(C_NAVY)
    canvas.rect(0, 0, W_PAGE, H_PAGE, fill=1, stroke=0)
    # Accent stripe
    canvas.setFillColor(C_BLUE)
    canvas.rect(0, H_PAGE*0.38, W_PAGE, H_PAGE*0.26, fill=1, stroke=0)
    # Top accent line
    canvas.setFillColor(C_YELLOW)
    canvas.rect(0, H_PAGE-0.6*cm, W_PAGE, 0.6*cm, fill=1, stroke=0)
    # Bottom accent line
    canvas.setFillColor(C_TEAL)
    canvas.rect(0, 0, W_PAGE, 0.5*cm, fill=1, stroke=0)
    canvas.restoreState()

# ══════════════════════════════════════════════════════════════════════════════
# DOC SETUP
# ══════════════════════════════════════════════════════════════════════════════
doc = BaseDocTemplate(
    OUTPUT,
    pagesize=A4,
    leftMargin=LM, rightMargin=RM,
    topMargin=TM+1.2*cm, bottomMargin=BM+1.0*cm,
    title="GIST – Student Pathology Guide",
    author="Orris Medical Reference"
)
cover_frame  = Frame(0, 0, W_PAGE, H_PAGE, id="cover",  leftPadding=2*cm, rightPadding=2*cm,
                     topPadding=3*cm, bottomPadding=2*cm)
normal_frame = Frame(LM, BM+1.0*cm, W, H_PAGE-TM-BM-2.2*cm, id="normal")
doc.addPageTemplates([
    PageTemplate(id="Cover",  frames=[cover_frame],  onPage=on_cover),
    PageTemplate(id="Normal", frames=[normal_frame], onPage=on_page),
])

# ══════════════════════════════════════════════════════════════════════════════
# STORY
# ══════════════════════════════════════════════════════════════════════════════
story = []

# ─────────────────────────────────────────────────────────────────────────────
# COVER
# ─────────────────────────────────────────────────────────────────────────────
story.append(NextPageTemplate("Cover"))
story.append(sp(3.5))
story.append(Paragraph("GASTROINTESTINAL", COVER_MAIN))
story.append(Paragraph("STROMAL TUMOR", COVER_MAIN))
story.append(sp(0.3))
story.append(Paragraph("G  ·  I  ·  S  ·  T", COVER_ABBR))
story.append(sp(0.6))
story.append(Paragraph("Complete Student Pathology Guide", COVER_SUB))
story.append(sp(0.2))
story.append(Paragraph(
    "Definition · Cell of Origin · Gross & Histopathology · IHC · Molecular Genetics<br/>"
    "Risk Stratification · Clinical Features · Hereditary Syndromes · Treatment",
    COVER_NOTE))
story.append(sp(1.5))
# decorative divider
div_data = [["  PATHOLOGY  |  ONCOLOGY  |  SURGERY  |  PHARMACOLOGY  "]]
div = Table(div_data, colWidths=[W_PAGE-4*cm])
div.setStyle(TableStyle([
    ("BACKGROUND",   (0,0),(-1,-1), C_TEAL),
    ("TEXTCOLOR",    (0,0),(-1,-1), C_WHITE),
    ("FONTNAME",     (0,0),(-1,-1), "Helvetica-Bold"),
    ("FONTSIZE",     (0,0),(-1,-1), 9),
    ("ALIGN",        (0,0),(-1,-1), "CENTER"),
    ("TOPPADDING",   (0,0),(-1,-1), 7),
    ("BOTTOMPADDING",(0,0),(-1,-1), 7),
]))
story.append(div)
story.append(sp(1.2))
story.append(Paragraph("Orris Medical Reference  ·  For Educational Use  ·  July 2026", COVER_NOTE))
story.append(PageBreak())

# ─────────────────────────────────────────────────────────────────────────────
# TABLE OF CONTENTS
# ─────────────────────────────────────────────────────────────────────────────
story.append(NextPageTemplate("Normal"))
story.append(section_bar("TABLE OF CONTENTS", color=C_TEAL))
story.append(sp(0.3))
toc_data = [
    ["01", "What is GIST? — Overview & Definition"],
    ["02", "Cell of Origin — Interstitial Cells of Cajal"],
    ["03", "Anatomic Distribution & Epidemiology"],
    ["04", "Gross Pathology"],
    ["05", "Histopathology — Microscopic Patterns"],
    ["06", "Immunohistochemistry (IHC)"],
    ["07", "Molecular Pathogenesis — Mutations & Pathways"],
    ["08", "Risk Stratification — How to Predict Behavior"],
    ["09", "Clinical Features — Presentation & Diagnosis"],
    ["10", "Hereditary Syndromes Associated with GIST"],
    ["11", "Treatment — Surgery, Imatinib & Beyond"],
    ["12", "High-Yield Exam Q&A"],
    ["13", "Key Points Summary Card"],
],
toc_num_s = PS("TOCN", fontSize=11, fontName="Helvetica-Bold", textColor=C_BLUE, alignment=TA_CENTER)
toc_txt_s = PS("TOCT", fontSize=10, fontName="Helvetica", textColor=C_GRAY_D, alignment=TA_LEFT)
for item in toc_data[0]:
    row_data = [[Paragraph(item[0], toc_num_s), Paragraph(item[1], toc_txt_s)]]
    t = Table(row_data, colWidths=[1.2*cm, W-1.2*cm])
    t.setStyle(TableStyle([
        ("VALIGN",       (0,0),(-1,-1), "MIDDLE"),
        ("TOPPADDING",   (0,0),(-1,-1), 5),
        ("BOTTOMPADDING",(0,0),(-1,-1), 5),
        ("LEFTPADDING",  (1,0),(1,0),   6),
        ("LINEBELOW",    (0,0),(-1,-1), 0.3, colors.HexColor("#CFD8DC")),
    ]))
    story.append(t)
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 01 ═══════════════════════════════════════════
story.append(section_bar("01  |  WHAT IS GIST? — OVERVIEW & DEFINITION", color=C_NAVY))
story.append(sp(0.3))

story.append(Paragraph(
    "A <b>Gastrointestinal Stromal Tumor (GIST)</b> is a mesenchymal (non-epithelial) neoplasm arising "
    "from the wall of the gastrointestinal tract. It is the <b>most common mesenchymal tumor of the GI tract</b> "
    "and makes up 1–3% of all malignant GI tumors.", BODY))
story.append(sp(0.15))

story.append(callout([
    "📌  GIST = Most common mesenchymal tumor of the GI tract",
    "📌  Every GIST has metastatic potential — NO truly benign GIST exists",
    "📌  Driven by gain-of-function mutations in KIT (~80%) or PDGFRA (~8%)",
    "📌  Highly responsive to imatinib (Gleevec) — a landmark targeted therapy",
], bg=C_BLUE_XLIT, border=C_BLUE))
story.append(sp(0.3))

story.append(Paragraph("Historical Milestones", H2_STYLE))
story.append(make_table(
    ["Year", "Milestone"],
    [["1983", "Term 'GIST' coined by Mazur & Clark for non-epithelial GI mesenchymal tumors"],
     ["Early 1990s", "CD34 explored as marker — insufficient sensitivity & specificity"],
     ["1998", "Hirota et al.: near-universal KIT (CD117) expression + gain-of-function KIT mutations discovered"],
     ["1999+", "DOG1 identified; molecular classification replaces histology-only diagnosis"],
     ["2001", "Imatinib mesylate first used in GIST — revolutionary targeted therapy"],
     ["2006+", "PDGFRA, SDH-deficient, and wild-type subtypes characterised"],
    ],
    col_widths=[W*0.15, W*0.85]
))
story.append(sp(0.2))
story.append(Paragraph(
    "Before 1998, GISTs were frequently misclassified as leiomyomas, leiomyosarcomas, "
    "'plexosarcomas,' or 'gastrointestinal autonomic nerve tumors' — leading to incorrect treatment.", NOTE))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 02 ═══════════════════════════════════════════
story.append(section_bar("02  |  CELL OF ORIGIN — INTERSTITIAL CELLS OF CAJAL", color=C_TEAL))
story.append(sp(0.3))

story.append(Paragraph(
    "GIST arises from <b>Interstitial Cells of Cajal (ICC)</b> — the pacemaker cells of the "
    "GI tract. These cells are located in the <b>myenteric plexus</b> (Auerbach's plexus) "
    "within the muscularis propria.", BODY))
story.append(sp(0.2))

story.append(Paragraph("What do ICCs normally do?", H2_STYLE))
for item in [
    "Act as <b>electrical pacemakers</b> — generate slow waves that drive peristalsis",
    "Link <b>smooth muscle cells</b> of the bowel wall with the <b>autonomic nervous system</b>",
    "Coordinate timing and direction of intestinal contractions",
    "Express <b>KIT (CD117)</b>, <b>CD34</b>, and <b>DOG1</b> constitutively",
]:
    story.append(bp(item))
story.append(sp(0.2))

story.append(Paragraph("Why do ICCs give rise to GIST?", H2_STYLE))
story.append(Paragraph(
    "ICCs depend on KIT signalling for their normal development and survival. "
    "A gain-of-function mutation in KIT causes <b>constitutive (always-on) KIT activation</b>, "
    "driving ICC descendants into uncontrolled proliferation — producing GIST.", BODY))
story.append(sp(0.15))

story.append(callout([
    "🧬  ICC  →  Gain-of-function KIT mutation  →  Constitutive kinase activation  →  GIST",
    "Extra-GI 'telocytes' (ICC-like cells in other tissues) may explain rare pancreatic/mesenteric GISTs",
], bg=C_TEAL_LITE, border=C_TEAL))
story.append(sp(0.3))

story.append(Paragraph("Shared Markers: ICC vs. GIST Cell", H2_STYLE))
story.append(make_table(
    ["Marker", "ICC (Normal)", "GIST Cell", "Significance"],
    [["CD117 (KIT)", "✓  Positive", "✓  ~95% Positive", "Defining diagnostic marker"],
     ["DOG1 (ANO1)", "✓  Positive", "✓  ~95% Positive", "Best confirmatory IHC marker"],
     ["CD34", "✓  Positive", "✓  ~60–70% Positive", "Supportive marker"],
     ["Smooth muscle actin", "Variable", "Variable (~30%)", "Not specific"],
     ["S100", "Negative", "Usually negative", "Helps exclude schwannoma"],
    ],
    col_widths=[W*0.26, W*0.16, W*0.22, W*0.36], hdr_color=C_TEAL
))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 03 ═══════════════════════════════════════════
story.append(section_bar("03  |  ANATOMIC DISTRIBUTION & EPIDEMIOLOGY", color=C_NAVY))
story.append(sp(0.3))

story.append(Paragraph("Where Does GIST Occur?", H2_STYLE))
story.append(make_table(
    ["Site", "Frequency", "Special Notes"],
    [["Stomach",            "40–60%", "Most common; PDGFRA mutations overrepresented here; best prognosis"],
     ["Jejunum / Ileum",    "24–30%", "Second most common; worse prognosis than gastric at same size/mitotic rate"],
     ["Colorectum",         "5–15%",  "Rectal GISTs: poor prognosis; limited surgical access"],
     ["Duodenum",           "~5%",    "Uncommon; surgical challenge near ampulla"],
     ["Esophagus",          "<1%",    "Very rare"],
     ["Extra-GI (mesentery, omentum)", "<5%", "Called 'extra-gastrointestinal stromal tumors' — same biology"],
    ],
    col_widths=[W*0.28, W*0.16, W*0.56]
))
story.append(sp(0.2))
story.append(warning_box([
    "Non-gastric GIST = worse prognosis than gastric GIST at the same size and mitotic rate.",
    "Small intestinal and rectal GISTs are classified into higher risk categories."
]))
story.append(sp(0.3))

story.append(Paragraph("Epidemiology", H2_STYLE))
story.append(make_table(
    ["Variable", "Data"],
    [["Incidence",       "10–15 per million per year (GI tract); underdiagnosed historically"],
     ["Peak age",        "~60 years (median); < 10% under age 40"],
     ["Sex",             "Slight male predominance (~55% male)"],
     ["Pediatric GIST",  "Rare; usually SDH-deficient; gastric; multifocal; female predominance"],
     ["Race",            "No significant racial predisposition in sporadic GISTs"],
    ],
    col_widths=[W*0.3, W*0.7]
))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 04 ═══════════════════════════════════════════
story.append(section_bar("04  |  GROSS PATHOLOGY", color=C_BLUE))
story.append(sp(0.3))

story.append(Paragraph("Macroscopic Features", H2_STYLE))
story.append(Paragraph(
    "Most GISTs present as <b>solitary, well-circumscribed, fleshy submucosal masses</b> arising from "
    "the muscularis propria. The overlying mucosa may be intact, thinned, or ulcerated.", BODY))
story.append(sp(0.15))

story.append(make_table(
    ["Feature", "Description"],
    [["Shape",        "Round to oval; well-circumscribed; pseudocapsule (NOT a true capsule)"],
     ["Size",         "Range: <1 cm (incidental) to >30 cm; most symptomatic GISTs are >5 cm"],
     ["Cut surface",  "Tan-white to pinkish, fleshy; soft to firm texture"],
     ["Haemorrhage",  "Common in larger tumors — areas of red/brown discolouration"],
     ["Necrosis",     "Present in large/high-grade tumors — yellow-grey areas"],
     ["Cystic change","Occurs in larger tumors — fluid-filled spaces"],
     ["Growth pattern","Endoluminal, exophytic, or dumbbell-shaped (both directions)"],
     ["Origin layer", "Muscularis propria — NOT mucosa or submucosa primarily"],
    ],
    col_widths=[W*0.28, W*0.72]
))
story.append(sp(0.2))

story.append(Paragraph("Metastatic Pattern (Gross)", H2_STYLE))
for item in [
    "<b>Liver</b> — most common site of distant metastasis (multiple nodules)",
    "<b>Peritoneum</b> — seeding via intraperitoneal spread",
    "<b>Lymph nodes</b> — RARE in sporadic KIT/PDGFRA-mutant GIST (unlike carcinomas)",
    "<b>Exception</b>: SDH-deficient/pediatric GISTs DO metastasize to lymph nodes",
    "Distant spread outside the abdomen (lung, bone) is uncommon",
]:
    story.append(bp(item))
story.append(sp(0.15))
story.append(warning_box([
    "GIST has a pseudocapsule, NOT a true capsule. Rupture (surgical or spontaneous) dramatically",
    "increases peritoneal recurrence risk — treat ruptured GIST as already metastatic."
]))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 05 ═══════════════════════════════════════════
story.append(section_bar("05  |  HISTOPATHOLOGY — MICROSCOPIC PATTERNS", color=C_NAVY))
story.append(sp(0.3))

story.append(Paragraph(
    "Three main histologic patterns exist. However, <b>histology alone cannot diagnose GIST</b> — "
    "IHC and molecular testing are required.", BODY))
story.append(sp(0.2))

story.append(make_table(
    ["Pattern", "Frequency", "Microscopic Features", "When to Suspect"],
    [["Spindle cell", "~70%",
      "Thin, elongated cells; pale eosinophilic cytoplasm; nuclear palisading; fascicular or storiform arrangement",
      "Most common; gastric & small intestinal GISTs"],
     ["Epithelioid", "~20%",
      "Plumper, rounded cells; abundant pale/clear cytoplasm; nesting pattern; perinuclear vacuoles",
      "Stomach; PDGFRA-mutant tumors; check PDGFRA D842V if IHC equivocal"],
     ["Mixed", "~10%",
      "Both spindle and epithelioid components in the same tumor",
      "Any site; requires full IHC panel"],
    ],
    col_widths=[W*0.18, W*0.12, W*0.42, W*0.28]
))
story.append(sp(0.2))

story.append(Paragraph("Key Microscopic Details", H2_STYLE))
for item in [
    "Mitotic figures are counted per <b>50 high-power fields (HPF)</b> — critical for risk stratification",
    "Nuclear atypia is usually <b>mild to moderate</b>; severe pleomorphism is uncommon",
    "Necrosis correlates with high-grade behavior and large tumor size",
    "<b>Skeinoid fibres</b> (eosinophilic extracellular globules) — classically seen in small intestinal spindle-cell GISTs",
    "Submucosal location with intact overlying mucosa — typical but not universal",
]:
    story.append(bp(item))
story.append(sp(0.2))

story.append(Paragraph("Historical Classification (Pre-1999) — Now Obsolete", H2_STYLE))
story.append(callout([
    "Before molecular markers, GISTs were (incorrectly) divided into thirds:",
    "• 1/3  Myogenic — expressed smooth muscle actin (thought to be leiomyosarcomas)",
    "• 1/3  Neurogenic — expressed S100 (thought to be schwannomas)",
    "• 1/3  Null phenotype — no lineage-specific markers",
    "This caused widespread misdiagnosis and inappropriate treatment."
], bg=C_ORANGE_L, border=C_ORANGE))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 06 ═══════════════════════════════════════════
story.append(section_bar("06  |  IMMUNOHISTOCHEMISTRY (IHC)", color=C_TEAL))
story.append(sp(0.3))

story.append(Paragraph(
    "IHC is the backbone of GIST diagnosis. The <b>two most important markers</b> are "
    "<b>CD117 (KIT)</b> and <b>DOG1</b>, each positive in ~95% of GISTs.", BODY))
story.append(sp(0.2))

story.append(make_table(
    ["Marker", "Sensitivity", "Specificity", "Staining Pattern", "Clinical Relevance"],
    [["CD117 (KIT, c-kit)", "~95%", "Moderate", "Strong diffuse cytoplasmic (spindle); dot-like / focal (epithelioid)", "Primary diagnostic marker; cornerstone of GIST diagnosis"],
     ["DOG1 (ANO1)", "~95%", "High", "Membranous ± cytoplasmic", "ESSENTIAL in KIT-negative GISTs; more specific than CD117"],
     ["CD34", "~60–70%", "Low", "Cytoplasmic", "Supportive only; also in vascular tumors"],
     ["PDGFRA (IHC)", "~70–80% of PDGFRA-mutant", "Moderate", "Cytoplasmic", "Helps identify PDGFRA-mutant subtype when KIT negative"],
     ["SDHB (IHC)", "N/A", "High (for SDH loss)", "Normal: granular; Loss: diffuse", "Loss of SDHB staining = SDH-deficient GIST"],
     ["Smooth muscle actin", "~30%", "Low", "Cytoplasmic", "Variable; does NOT exclude GIST"],
     ["Desmin", "~5%", "Low", "Cytoplasmic", "Usually negative; helps exclude leiomyosarcoma"],
     ["S100 protein", "<5%", "Low", "Nuclear + cytoplasmic", "Usually negative; helps exclude schwannoma"],
    ],
    col_widths=[W*0.20, W*0.12, W*0.12, W*0.28, W*0.28], hdr_color=C_TEAL
))
story.append(sp(0.2))

story.append(Paragraph("IHC Diagnostic Algorithm", H2_STYLE))
story.append(callout([
    "Step 1:  Suspicious spindle/epithelioid GI mesenchymal tumor",
    "Step 2:  Stain for CD117 (KIT)  +  DOG1",
    "Step 3a: CD117+ / DOG1+ → GIST confirmed → proceed to molecular testing",
    "Step 3b: CD117– / DOG1+ → Still likely GIST → test for PDGFRA mutation",
    "Step 3c: CD117– / DOG1– → Consider: leiomyosarcoma (desmin+/SMA+), schwannoma (S100+), desmoid (β-catenin+)",
    "Step 4:  SDHB IHC on all GISTs → loss = SDH-deficient subtype (impacts treatment)",
], bg=C_BLUE_XLIT, border=C_BLUE))
story.append(sp(0.15))

story.append(warning_box([
    "CD117 can be HETEROGENEOUS within a single tumor.",
    "A needle biopsy may yield CD117-negative cells due to sampling bias alone.",
    "Always use DOG1 alongside CD117 — they are complementary, not interchangeable."
]))
story.append(sp(0.2))

story.append(mnemonic_box("CD-KIT = C-DOGS",
    [("C", "CD117 (KIT) — primary marker (~95%)"),
     ("D", "DOG1 — best specificity; positive even in KIT-negative GISTs"),
     ("O", "Only together = reliable diagnosis"),
     ("G", "Genotype (molecular testing) follows IHC to guide treatment"),
     ("S", "SDHB loss = SDH-deficient subtype — check in all wild-type GISTs"),
    ]))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 07 ═══════════════════════════════════════════
story.append(section_bar("07  |  MOLECULAR PATHOGENESIS — MUTATIONS & PATHWAYS", color=C_NAVY))
story.append(sp(0.3))

story.append(Paragraph("The KIT Signalling Pathway (Normal vs. Mutant)", H2_STYLE))
story.append(Paragraph(
    "<b>Normal:</b>  SCF (stem cell factor) binds KIT receptor → homodimerization → "
    "autophosphorylation → activation of RAS/MAPK, PI3K/AKT, JAK/STAT3 → cell growth (regulated).<br/><br/>"
    "<b>Mutant GIST:</b>  Gain-of-function KIT mutation → receptor is <b>always active</b> "
    "(ligand-independent) → constitutive downstream signalling → uncontrolled cell proliferation → GIST.",
    BODY))
story.append(sp(0.2))

story.append(Paragraph("Mutation Landscape Overview", H2_STYLE))
story.append(make_table(
    ["Mutation Type", "Frequency", "Imatinib Response", "Key Notes"],
    [["KIT exon 11 (juxtamembrane)", "~65–70%", "HIGH (~80–90%)", "Most sensitive; deletions more common than point mutations"],
     ["KIT exon 9 (extracellular)", "~10–15%",  "MODERATE (40–50%)", "Needs higher dose (800 mg/day); small intestinal predilection"],
     ["KIT exon 13 (kinase I)",      "~1–2%",   "MODERATE",          "K642E most common"],
     ["KIT exon 17 (kinase II)",     "~1%",     "MODERATE",          "D820 mutations; sunitinib may be better"],
     ["PDGFRA exon 18 D842V",        "~5–6%",   "RESISTANT",         "Avapritinib is preferred; imatinib inactive"],
     ["PDGFRA other exons",          "~1–2%",   "Variable",          "May respond to imatinib"],
     ["SDH-deficient (wild-type)",   "~5–10%",  "RESISTANT",         "Pediatric/Carney triad; SDHB IHC loss"],
     ["NF1-associated (wild-type)",  "~1%",     "Uncertain",         "Multiple small intestinal GISTs"],
     ["BRAF V600E (wild-type)",      "<1%",     "Resistant",         "May respond to vemurafenib"],
    ],
    col_widths=[W*0.30, W*0.14, W*0.18, W*0.38]
))
story.append(sp(0.2))

story.append(Paragraph("KIT vs. PDGFRA — Key Comparison", H2_STYLE))
story.append(make_table(
    ["Feature", "KIT-mutant GIST", "PDGFRA-mutant GIST"],
    [["Chromosome",    "4q12",       "4q12 (same locus — adjacent genes)"],
     ["Frequency",     "~75–85%",    "~8–10%"],
     ["Common site",   "Any GI site","Stomach (overrepresented); omentum"],
     ["Histology",     "Spindle cell predominant", "Epithelioid predominant"],
     ["IHC CD117",     "~95% positive", "Often weak/negative"],
     ["Imatinib",      "Mostly sensitive", "D842V = resistant; others variable"],
     ["Mutual exclusivity", "—",     "KIT and PDGFRA mutations NEVER coexist"],
    ],
    col_widths=[W*0.27, W*0.36, W*0.37]
))
story.append(sp(0.2))

story.append(Paragraph("SDH-Deficient GIST — Special Subtype", H2_STYLE))
story.append(callout([
    "Mutation: SDHA, SDHB, SDHC, or SDHD genes (succinate dehydrogenase complex — mitochondria)",
    "Effect: SDH dysfunction → ↑ succinate accumulation → pseudohypoxia (HIF activation) → tumour growth",
    "Profile: KIT negative, PDGFRA negative, SDHB IHC loss",
    "Clinical: Young patients; female predominance; multifocal gastric; lymph node spread possible",
    "Syndromes: Carney Triad, Carney-Stratakis Dyad",
    "Treatment: Imatinib-resistant — temozolomide, sunitinib, or clinical trials",
], bg=C_PURPLE_L, border=C_PURPLE))
story.append(sp(0.3))

story.append(mnemonic_box("KIT Exon Mutations — 'Eleven Is First'",
    [("11", "Exon 11 = Most common + Best imatinib response (juxtamembrane domain)"),
     ("9",  "Exon 9 = Second + Needs Higher dose + Small intestine"),
     ("13", "Exon 13 = Kinase I domain, rare"),
     ("17", "Exon 17 = Kinase II domain, rare"),
    ]))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 08 ═══════════════════════════════════════════
story.append(section_bar("08  |  RISK STRATIFICATION — HOW TO PREDICT BEHAVIOUR", color=C_BLUE))
story.append(sp(0.3))

story.append(callout([
    "🔑  Core Concept: Every GIST has metastatic potential — risk stratification tells us HOW MUCH risk.",
    "🔑  The 3 pillars: (1) Tumor SIZE  (2) MITOTIC RATE  (3) PRIMARY SITE",
    "🔑  A 4th factor: Tumor RUPTURE — dramatically worsens prognosis (treat as metastatic)",
], bg=C_YELLOW_L, border=C_YELLOW))
story.append(sp(0.2))

story.append(Paragraph("NIH (Fletcher) Consensus Classification — Most Used in Practice", H2_STYLE))
story.append(make_table(
    ["Risk Category", "Size", "Mitotic Rate (per 50 HPF)"],
    [["Very Low Risk",    "< 2 cm",     "< 5"],
     ["Low Risk",         "2–5 cm",     "< 5"],
     ["Intermediate Risk","< 5 cm  OR  5–10 cm", "6–10  OR  < 5"],
     ["High Risk",        "> 5 cm  OR  > 10 cm  OR  ANY size", "> 5  OR  ANY  OR  > 10"],
    ],
    col_widths=[W*0.25, W*0.35, W*0.40]
))
story.append(sp(0.15))
story.append(Paragraph(
    "Note: This system does NOT account for site. The <b>Joensuu/AFIP system</b> adds site as a variable "
    "and shows that non-gastric GISTs behave more aggressively.", NOTE))
story.append(sp(0.2))

story.append(Paragraph("Effect of Tumor Site on Prognosis (Joensuu system)", H2_STYLE))
story.append(make_table(
    ["Size + Mitotic Rate", "Gastric GIST", "Non-Gastric GIST"],
    [["≤ 2 cm / ≤ 5 mit",      "Negligible risk",  "Negligible risk"],
     ["2–5 cm / ≤ 5 mit",      "Very low risk",    "Low risk"],
     ["5–10 cm / ≤ 5 mit",     "Low risk",         "Moderate risk"],
     ["> 10 cm / ≤ 5 mit",     "Moderate risk",    "HIGH risk"],
     ["Any / > 5 mit",         "Moderate–High",    "HIGH risk"],
     ["Ruptured tumor",        "HIGH risk",        "HIGH risk"],
    ],
    col_widths=[W*0.35, W*0.32, W*0.33]
))
story.append(sp(0.2))

story.append(Paragraph("AJCC Staging (8th Ed)", H2_STYLE))
story.append(Paragraph(
    "Uses T (size: T1 ≤2 cm, T2 2–5 cm, T3 5–10 cm, T4 >10 cm), N (nodes — rare), "
    "M (distant metastasis), and <b>mitotic rate</b>. Separate staging tables exist for "
    "<b>gastric/omental</b> vs. <b>small intestinal/esophageal/colorectal/mesenteric</b> GISTs.", BODY))
story.append(sp(0.3))

story.append(mnemonic_box("Risk = SiMS + Location",
    [("Si", "SIZE — bigger = worse"),
     ("M",  "MITOTIC rate — more mitoses/50 HPF = worse"),
     ("S",  "SITE — non-gastric = worse than gastric at same size/mitotic rate"),
     ("+",  "RUPTURE — treat as already metastatic regardless of size/mitotic rate"),
    ]))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 09 ═══════════════════════════════════════════
story.append(section_bar("09  |  CLINICAL FEATURES — PRESENTATION & DIAGNOSIS", color=C_NAVY))
story.append(sp(0.3))

story.append(Paragraph("Symptoms and Presentation", H2_STYLE))
story.append(make_table(
    ["Presentation", "Details / Notes"],
    [["GI bleeding",          "Haematemesis, melaena, or occult blood loss — due to mucosal ulceration"],
     ["Abdominal pain/mass",  "Dull, vague pain; palpable mass in large tumors"],
     ["Obstruction",          "Gastric outlet obstruction or small bowel obstruction"],
     ["Dysphagia",            "Esophageal or gastric cardiac GISTs"],
     ["Incidental finding",   "Common! Found on imaging/endoscopy for other reasons — typically < 2 cm"],
     ["Acute abdomen",        "Tumor rupture → haemoperitoneum — surgical emergency"],
    ],
    col_widths=[W*0.30, W*0.70]
))
story.append(sp(0.2))

story.append(Paragraph("Diagnostic Work-Up", H2_STYLE))
for item in [
    "<b>CT scan with contrast</b> — imaging modality of choice; characterises tumor, extent, and metastases",
    "<b>Endoscopy/EUS (endoscopic ultrasound)</b> — EUS-guided FNA for biopsy when resection planned; assesses submucosal lesion layers",
    "<b>Biopsy</b> — needed for unresectable/metastatic disease before imatinib; avoid for resectable lesions (risk of rupture/seeding)",
    "<b>PET scan</b> — detects early imatinib response (metabolic response precedes size change); useful for monitoring",
    "<b>Molecular testing</b> (KIT/PDGFRA exon sequencing) — mandatory before starting targeted therapy",
    "<b>SDHB IHC</b> — on all GISTs to identify SDH-deficient subtype",
]:
    story.append(bp(item))
story.append(sp(0.2))

story.append(Paragraph("Radiologic Features (CT)", H2_STYLE))
story.append(make_table(
    ["Feature", "GIST Finding"],
    [["Enhancement",     "Heterogeneous, often hypervascular; may have necrotic/haemorrhagic areas"],
     ["Margins",         "Well-defined, smooth; pseudocapsule visible"],
     ["Response to Rx",  "Choi criteria (not RECIST): decrease in density (Hounsfield units) precedes size change"],
     ["Metastasis",      "Liver: multiple hypervascular nodules; peritoneal nodules"],
    ],
    col_widths=[W*0.3, W*0.7]
))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 10 ═══════════════════════════════════════════
story.append(section_bar("10  |  HEREDITARY SYNDROMES ASSOCIATED WITH GIST", color=C_TEAL))
story.append(sp(0.3))

story.append(make_table(
    ["Syndrome", "GIST Features", "Other Tumors", "Molecular Basis"],
    [["Carney Triad\n(NOT autosomal dominant)",
      "Gastric GIST; multifocal; young females; SDH-deficient",
      "Pulmonary chondromas + extra-adrenal paragangliomas",
      "SDHC promoter hypermethylation (somatic/epigenetic); no germline SDH mutation in most"],
     ["Carney-Stratakis Dyad\n(Autosomal dominant)",
      "Gastric GIST; multifocal; SDH-deficient",
      "Paraganglioma (no pulmonary chondroma)",
      "Germline SDHA/B/C/D mutations; autosomal dominant"],
     ["Familial GIST Syndrome\n(Autosomal dominant)",
      "Multiple GISTs at any GI site; early onset; diffuse ICC hyperplasia; cutaneous hyperpigmentation",
      "None specific",
      "Germline KIT (most common) or PDGFRA mutations"],
     ["NF1 (von Recklinghausen)\n(Autosomal dominant)",
      "Multiple small intestinal GISTs; usually small, low mitotic rate; often incidental",
      "Neurofibromas, astrocytomas, learning disability, café-au-lait spots",
      "NF1 loss (not KIT/PDGFRA mutations); KIT overexpressed but not mutated"],
    ],
    col_widths=[W*0.22, W*0.26, W*0.26, W*0.26], hdr_color=C_TEAL
))
story.append(sp(0.2))

story.append(callout([
    "Memory aid for Carney Triad:  G-P-P",
    "  G = Gastric GIST",
    "  P = Pulmonary chondroma",
    "  P = Paraganglioma (extra-adrenal)",
    "Carney-Stratakis Dyad = G + P (no pulmonary chondroma) + germline SDH mutation",
], bg=C_PURPLE_L, border=C_PURPLE))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 11 ═══════════════════════════════════════════
story.append(section_bar("11  |  TREATMENT — SURGERY, IMATINIB & BEYOND", color=C_NAVY))
story.append(sp(0.3))

story.append(Paragraph("A. Surgery", H2_STYLE))
story.append(make_table(
    ["Principle", "Details"],
    [["Goal",             "Complete resection with negative margins (R0) — primary curative treatment"],
     ["Margins",          "1–2 cm recommended; pseudocapsule must remain INTACT"],
     ["Lymphadenectomy",  "NOT routine — lymph node spread is rare in KIT/PDGFRA-mutant GIST"],
     ["Laparoscopic",     "Acceptable for gastric GISTs ≤ 5 cm with appropriate technique"],
     ["Tumor rupture",    "AVOID — treat ruptured GIST as disseminated disease regardless of other features"],
    ],
    col_widths=[W*0.28, W*0.72]
))
story.append(sp(0.2))

story.append(Paragraph("B. Imatinib Mesylate (Gleevec) — The Targeted Therapy Revolution", H2_STYLE))
story.append(Paragraph(
    "Imatinib is a <b>tyrosine kinase inhibitor (TKI)</b> that competitively inhibits KIT, PDGFRA, "
    "BCR-ABL, and PDGFRB. It transformed GIST from a chemotherapy-resistant disease into a manageable "
    "chronic condition for many patients.", BODY))
story.append(sp(0.15))

story.append(make_table(
    ["Setting", "Indication", "Duration"],
    [["Adjuvant (post-op)",   "High-risk resected GIST with imatinib-sensitive mutation", "3 years (standard); ongoing trials for longer"],
     ["Neoadjuvant (pre-op)", "Marginally resectable; large/complex tumors", "Until maximal response (typically 6–12 months)"],
     ["Metastatic/Unresectable", "All imatinib-sensitive GIST", "Lifelong — stopping leads to rapid progression"],
    ],
    col_widths=[W*0.27, W*0.44, W*0.29]
))
story.append(sp(0.15))

story.append(make_table(
    ["Mutation", "Standard Dose", "Response"],
    [["KIT exon 11",        "400 mg/day", "~80–90% — best response"],
     ["KIT exon 9",         "800 mg/day", "~40–50% (higher dose required)"],
     ["PDGFRA non-D842V",   "400 mg/day", "Variable"],
     ["PDGFRA D842V",       "Imatinib NOT used", "RESISTANT — use avapritinib"],
     ["Wild-type / SDH",    "Not recommended", "Generally resistant"],
    ],
    col_widths=[W*0.30, W*0.22, W*0.48]
))
story.append(sp(0.2))

story.append(Paragraph("C. Second-Line and Beyond", H2_STYLE))
story.append(make_table(
    ["Drug", "Line", "Mechanism", "Notes"],
    [["Sunitinib",    "2nd line", "Multi-TKI (KIT, PDGFR, VEGFR)", "Used when imatinib fails/intolerable; specific KIT mutations guide response"],
     ["Regorafenib",  "3rd line", "Multi-TKI", "After sunitinib failure"],
     ["Ripretinib",   "4th line", "Switch-control KIT/PDGFRA inhibitor", "Broad inhibition of KIT resistance mutations"],
     ["Avapritinib",  "1st line for D842V", "PDGFRA-selective TKI", "FDA approved for PDGFRA exon 18 D842V mutant GIST"],
    ],
    col_widths=[W*0.18, W*0.13, W*0.29, W*0.40]
))
story.append(sp(0.15))

story.append(callout([
    "⚡  Secondary resistance to imatinib: Develops in ~2 years in metastatic GIST via secondary KIT kinase domain mutations.",
    "    Same mechanism as imatinib resistance in CML (BCR-ABL secondary mutations).",
    "    PET scan shows single progressing lesion ('clonal progression') while others remain controlled.",
], bg=C_ORANGE_L, border=C_ORANGE))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 12 ═══════════════════════════════════════════
story.append(section_bar("12  |  HIGH-YIELD EXAM Q&A", color=C_BLUE))
story.append(sp(0.3))

story.append(exam_box([
    ("What is the cell of origin of GIST?",
     "Interstitial cells of Cajal (ICC) — pacemaker cells of the GI muscularis propria."),
    ("What are the two most important IHC markers for GIST?",
     "CD117 (KIT) and DOG1 — each positive in ~95% of GISTs."),
    ("Which GIST mutation is most common and has the best imatinib response?",
     "KIT exon 11 mutation (~65–70% of GISTs; ~80–90% response to imatinib 400 mg/day)."),
    ("Which mutation is RESISTANT to imatinib?",
     "PDGFRA exon 18 D842V mutation — use avapritinib instead."),
    ("What are the 3 pillars of GIST risk stratification?",
     "Tumor SIZE + MITOTIC RATE (per 50 HPF) + PRIMARY SITE (non-gastric = worse)."),
    ("What is 'every GIST' rule?",
     "Every GIST has metastatic potential — there is NO truly benign GIST."),
    ("What is the lymph node spread pattern in GIST?",
     "RARE in KIT/PDGFRA-mutant GISTs (unlike carcinomas). Exception: SDH-deficient/pediatric GISTs."),
    ("What is Carney Triad?",
     "Gastric GIST + Pulmonary chondroma + Extra-adrenal paraganglioma (SDH-deficient; young females)."),
    ("What happens if a GIST ruptures?",
     "Treat as already metastatic — tumor rupture dramatically increases peritoneal recurrence risk."),
    ("What IHC stain identifies SDH-deficient GIST?",
     "Loss of SDHB staining on IHC (granular pattern lost → diffuse/absent)."),
    ("Why is KIT exon 9 mutant GIST treated with higher dose imatinib?",
     "Exon 9 mutations confer lower imatinib sensitivity; 800 mg/day improves response rates."),
    ("What criteria are used to assess imatinib response on CT?",
     "Choi criteria — decrease in CT density (Hounsfield units) precedes size reduction (not RECIST)."),
]))
story.append(sp(0.3))
story.append(PageBreak())

# ═══════════════════════ CHAPTER 13 ═══════════════════════════════════════════
story.append(section_bar("13  |  KEY POINTS SUMMARY CARD", color=C_NAVY))
story.append(sp(0.3))

story.append(make_table(
    ["Topic", "Key Point"],
    [["Definition",       "Most common GI mesenchymal tumor; 1–3% of all GI malignancies"],
     ["Cell of origin",   "Interstitial cells of Cajal (ICCs) in the muscularis propria"],
     ["Most common site", "Stomach (40–60%) → Small intestine → Colorectum"],
     ["IHC markers",      "CD117 + DOG1 (~95% each); SDHB loss = SDH-deficient"],
     ["Main mutation",    "KIT exon 11 (~65–70%) — best imatinib response"],
     ["Imatinib-resistant","PDGFRA D842V — use avapritinib"],
     ["Risk pillars",     "Size + Mitotic rate (per 50 HPF) + Site (non-gastric worse)"],
     ["Lymph nodes",      "Rarely involved in sporadic GIST (exception: SDH-deficient)"],
     ["Metastasis sites", "Liver (most common) + Peritoneum"],
     ["Surgery rule",     "R0 resection; no lymphadenectomy; avoid rupture"],
     ["Adjuvant therapy", "Imatinib 3 years for high-risk resected GIST (sensitive mutations)"],
     ["Pediatric GIST",   "SDH-deficient; gastric; multifocal; lymph node spread possible; imatinib-resistant"],
     ["Carney Triad",     "GIST + Pulmonary chondroma + Paraganglioma (SDH-deficient)"],
     ["Resistance mechanism","Secondary KIT kinase mutations (like CML/BCR-ABL)"],
     ["ctDNA (emerging)", "Circulating tumour DNA — emerging prognostic biomarker (2025 meta-analysis)"],
    ],
    col_widths=[W*0.30, W*0.70]
))
story.append(sp(0.3))

story.append(hr(C_NAVY))
story.append(Paragraph(
    "Sources: Robbins &amp; Kumar Basic Pathology · Sleisenger &amp; Fordtran's GI and Liver Disease · "
    "Sabiston Textbook of Surgery · Quick Compendium of Clinical Pathology 5e · "
    "Fischer's Mastery of Surgery 8e · Current Surgical Therapy 14e · "
    "Goodman &amp; Gilman's Pharmacological Basis of Therapeutics · "
    "Schwartz's Principles of Surgery 11e",
    NOTE))
story.append(Paragraph(
    "Recent PubMed: PMID 40665034 (ctDNA meta-analysis 2025) · PMID 40045030 (SDH-deficient GIST therapies 2025) · "
    "PMID 40140195 (neoadjuvant imatinib meta-analysis 2025)",
    NOTE))
story.append(sp(0.2))
story.append(Paragraph(
    "This guide is for educational use only. Always defer to current clinical guidelines for patient care.",
    NOTE))

# ══════════════════════════════════════════════════════════════════════════════
# BUILD
# ══════════════════════════════════════════════════════════════════════════════
doc.build(story)
print(f"✅  PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/gist-pathology && python gist_student.py 2>&1

Your student guide PDF is ready:

GIST Student Guide

PDF Document · PDF


Here's what's inside the 13-chapter student guide:
ChapterContent
Cover + TOCProfessional cover page, full table of contents
01What is GIST? Definition + historical milestones timeline
02Cell of origin — ICC explained simply, shared markers table
03Anatomic distribution + epidemiology table
04Gross pathology — all macroscopic features + metastasis pattern
05Histopathology — spindle/epithelioid/mixed with features; skeinoid fibres
06IHC — full marker table + diagnostic algorithm step-by-step
07Molecular pathogenesis — KIT pathway, mutation landscape, SDH subtype
08Risk stratification — NIH Fletcher + Joensuu + AJCC explained
09Clinical features — symptoms, imaging (Choi criteria), work-up
10Hereditary syndromes — Carney Triad, NF1, Familial GIST
11Treatment — surgery principles, imatinib dosing by mutation, 2nd/3rd line
1212 high-yield Exam Q&A pairs
13One-page summary card for last-minute revision
Special features: colour-coded callout boxes, warning boxes, purple mnemonics (e.g., "SiMS + Location" for risk, "CD-KIT = C-DOGS" for IHC), and exam-ready formatting throughout.

Make long answer on giat and make pdf of it

Make long paghology answer on gist and make pdf of it

Writing File

~/gist-pathology/gist_long_answer.py

from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (
    BaseDocTemplate, PageTemplate, Frame, SimpleDocTemplate,
    Paragraph, Spacer, Table, TableStyle, HRFlowable, PageBreak,
    KeepTogether, NextPageTemplate
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY, TA_RIGHT

OUTPUT = "/home/daytona/workspace/gist-pathology/GIST_Long_Answer.pdf"

W_PAGE, H_PAGE = A4
LM = RM = 2.0*cm
TM = BM = 1.8*cm
W = W_PAGE - LM - RM

# ── COLOURS ───────────────────────────────────────────────────────────────────
NAVY        = colors.HexColor("#0B2545")
BLUE        = colors.HexColor("#1565C0")
BLUE_MID    = colors.HexColor("#1976D2")
BLUE_LITE   = colors.HexColor("#BBDEFB")
BLUE_XLIT   = colors.HexColor("#E3F2FD")
TEAL        = colors.HexColor("#00695C")
TEAL_LITE   = colors.HexColor("#E0F2F1")
ORANGE      = colors.HexColor("#E65100")
ORANGE_L    = colors.HexColor("#FFF3E0")
GREEN       = colors.HexColor("#1B5E20")
GREEN_L     = colors.HexColor("#E8F5E9")
RED         = colors.HexColor("#B71C1C")
RED_L       = colors.HexColor("#FFEBEE")
PURPLE      = colors.HexColor("#4A148C")
PURPLE_L    = colors.HexColor("#F3E5F5")
YELLOW      = colors.HexColor("#F57F17")
YELLOW_L    = colors.HexColor("#FFFDE7")
GRAY_D      = colors.HexColor("#212121")
GRAY_M      = colors.HexColor("#546E7A")
GRAY_L      = colors.HexColor("#ECEFF1")
WHITE       = colors.white

# ── STYLES ────────────────────────────────────────────────────────────────────
def PS(name, **kw):
    return ParagraphStyle(name, **kw)

MAIN_TITLE  = PS("MainTitle", fontSize=28, leading=34, fontName="Helvetica-Bold",
                  textColor=WHITE, alignment=TA_CENTER)
SUBTITLE    = PS("Subtitle",  fontSize=14, leading=20, fontName="Helvetica",
                  textColor=colors.HexColor("#BBDEFB"), alignment=TA_CENTER)
QUESTION    = PS("Question",  fontSize=13, leading=18, fontName="Helvetica-Bold",
                  textColor=ORANGE, alignment=TA_LEFT, spaceBefore=2, spaceAfter=6)
H1          = PS("H1",        fontSize=14, leading=18, fontName="Helvetica-Bold",
                  textColor=WHITE, alignment=TA_LEFT)
H2          = PS("H2",        fontSize=12, leading=16, fontName="Helvetica-Bold",
                  textColor=NAVY, spaceBefore=8, spaceAfter=4)
H3          = PS("H3",        fontSize=10.5, leading=14, fontName="Helvetica-Bold",
                  textColor=BLUE, spaceBefore=6, spaceAfter=3)
BODY        = PS("Body",      fontSize=10.5, leading=16.5, fontName="Helvetica",
                  textColor=GRAY_D, alignment=TA_JUSTIFY, spaceAfter=5)
BODY_IND    = PS("BodyInd",   fontSize=10.5, leading=16.5, fontName="Helvetica",
                  textColor=GRAY_D, alignment=TA_JUSTIFY, leftIndent=14, spaceAfter=4)
BULLET      = PS("Bullet",    fontSize=10.5, leading=16, fontName="Helvetica",
                  textColor=GRAY_D, leftIndent=18, bulletIndent=4, spaceAfter=2)
BULLET2     = PS("Bullet2",   fontSize=10, leading=14, fontName="Helvetica",
                  textColor=GRAY_D, leftIndent=34, bulletIndent=18, spaceAfter=2)
NOTE        = PS("Note",      fontSize=8.5, leading=12, fontName="Helvetica-Oblique",
                  textColor=GRAY_M, spaceAfter=2)
TH_S        = PS("THS",       fontSize=9,  leading=13, fontName="Helvetica-Bold",
                  textColor=WHITE, alignment=TA_CENTER)
TD_S        = PS("TDS",       fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=GRAY_D, alignment=TA_LEFT)
TD_C        = PS("TDC",       fontSize=9,  leading=13, fontName="Helvetica",
                  textColor=GRAY_D, alignment=TA_CENTER)
HIGHLIGHT   = PS("Highlight", fontSize=10.5, leading=16, fontName="Helvetica-Bold",
                  textColor=NAVY, leftIndent=10)
FOOTER_S    = PS("Footer",    fontSize=8,  leading=11, fontName="Helvetica",
                  textColor=WHITE, alignment=TA_LEFT)
FOOTER_R    = PS("FooterR",   fontSize=8.5, leading=11, fontName="Helvetica-Bold",
                  textColor=WHITE, alignment=TA_RIGHT)

# ── PAGE CALLBACKS ────────────────────────────────────────────────────────────
def on_cover(canvas, doc):
    canvas.saveState()
    canvas.setFillColor(NAVY)
    canvas.rect(0, 0, W_PAGE, H_PAGE, fill=1, stroke=0)
    canvas.setFillColor(BLUE)
    canvas.rect(0, H_PAGE*0.35, W_PAGE, H_PAGE*0.30, fill=1, stroke=0)
    canvas.setFillColor(YELLOW)
    canvas.rect(0, H_PAGE - 0.6*cm, W_PAGE, 0.6*cm, fill=1, stroke=0)
    canvas.setFillColor(TEAL)
    canvas.rect(0, 0, W_PAGE, 0.5*cm, fill=1, stroke=0)
    canvas.restoreState()

def on_page(canvas, doc):
    canvas.saveState()
    # Header
    canvas.setFillColor(NAVY)
    canvas.rect(0, H_PAGE - 1.0*cm, W_PAGE, 1.0*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica-Bold", 8.5)
    canvas.drawString(LM, H_PAGE - 0.68*cm, "GASTROINTESTINAL STROMAL TUMOR (GIST) — Long Answer")
    canvas.setFont("Helvetica", 8)
    canvas.drawRightString(W_PAGE - RM, H_PAGE - 0.68*cm, "Pathology Essay")
    # Footer
    canvas.setFillColor(NAVY)
    canvas.rect(0, 0, W_PAGE, 0.85*cm, fill=1, stroke=0)
    canvas.setFillColor(WHITE)
    canvas.setFont("Helvetica", 7.5)
    canvas.drawString(LM, 0.28*cm, "Orris Medical Reference  ·  Educational Use Only  ·  2026")
    canvas.setFont("Helvetica-Bold", 9)
    canvas.drawRightString(W_PAGE - RM, 0.28*cm, f"{doc.page}")
    canvas.restoreState()

# ── DOCUMENT SETUP ────────────────────────────────────────────────────────────
doc = BaseDocTemplate(
    OUTPUT, pagesize=A4,
    leftMargin=LM, rightMargin=RM,
    topMargin=TM + 1.1*cm, bottomMargin=BM + 0.9*cm,
    title="GIST Long Answer — Pathology Essay",
    author="Orris Medical Reference"
)
cover_f  = Frame(0, 0, W_PAGE, H_PAGE, leftPadding=2*cm, rightPadding=2*cm,
                 topPadding=2.5*cm, bottomPadding=1.5*cm, id="cover")
normal_f = Frame(LM, BM + 0.9*cm, W, H_PAGE - TM - BM - 2.0*cm, id="normal")
doc.addPageTemplates([
    PageTemplate(id="Cover",  frames=[cover_f],  onPage=on_cover),
    PageTemplate(id="Normal", frames=[normal_f], onPage=on_page),
])

# ── HELPERS ───────────────────────────────────────────────────────────────────
def sp(h=0.3): return Spacer(1, h*cm)
def hr(c=colors.HexColor("#CFD8DC")):
    return HRFlowable(width="100%", thickness=0.5, color=c, spaceAfter=4)

def sec_bar(title, color=NAVY):
    t = Table([[Paragraph(title, H1)]], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), color),
        ("LEFTPADDING",   (0,0),(-1,-1), 12),
        ("RIGHTPADDING",  (0,0),(-1,-1), 12),
        ("TOPPADDING",    (0,0),(-1,-1), 8),
        ("BOTTOMPADDING", (0,0),(-1,-1), 8),
    ]))
    return t

def box(lines, bg=BLUE_XLIT, bd=BLUE_MID, st=None):
    st = st or BODY
    t = Table([[Paragraph(l, st)] for l in lines], colWidths=[W])
    t.setStyle(TableStyle([
        ("BACKGROUND",    (0,0),(-1,-1), bg),
        ("BOX",           (0,0),(-1,-1), 1.2, bd),
        ("LEFTPADDING",   (0,0),(-1,-1), 12),
        ("RIGHTPADDING",  (0,0),(-1,-1), 12),
        ("TOPPADDING",    (0,0),(-1,-1), 6),
        ("BOTTOMPADDING", (0,0),(-1,-1), 6),
    ]))
    return t

def imp_box(lines):
    st = PS("ImpSt", fontSize=10, leading=15, fontName="Helvetica-Bold", textColor=GRAY_D,
             leftIndent=4)
    return box(["🔑  " + l for l in lines], bg=YELLOW_L, bd=YELLOW, st=st)

def make_table(headers, rows, cw=None, hc=BLUE):
    if cw is None: cw = [W/len(headers)]*len(headers)
    data = [[Paragraph(h, TH_S) for h in headers]]
    for i,row in enumerate(rows):
        data.append([Paragraph(str(c), TD_C if j>0 else TD_S) for j,c in enumerate(row)])
    t = Table(data, colWidths=cw, repeatRows=1)
    sty = [
        ("BACKGROUND",    (0,0),(-1,0),  hc),
        ("GRID",          (0,0),(-1,-1), 0.4, colors.HexColor("#B0BEC5")),
        ("TOPPADDING",    (0,0),(-1,-1), 5),
        ("BOTTOMPADDING", (0,0),(-1,-1), 5),
        ("LEFTPADDING",   (0,0),(-1,-1), 7),
        ("RIGHTPADDING",  (0,0),(-1,-1), 7),
        ("VALIGN",        (0,0),(-1,-1), "MIDDLE"),
    ]
    for i in range(1, len(data)):
        if i%2==0: sty.append(("BACKGROUND",(0,i),(-1,i),BLUE_XLIT))
    t.setStyle(TableStyle(sty))
    return t

def bp(txt, s=BULLET):  return Paragraph(f"<bullet>•</bullet>  {txt}", s)
def bp2(txt):            return Paragraph(f"<bullet>–</bullet>  {txt}", BULLET2)

# ══════════════════════════════════════════════════════════════════════════════
# STORY
# ══════════════════════════════════════════════════════════════════════════════
S = []

# ─── COVER ────────────────────────────────────────────────────────────────────
S.append(NextPageTemplate("Cover"))
S.append(sp(4))
S.append(Paragraph("GASTROINTESTINAL STROMAL TUMOR", MAIN_TITLE))
S.append(Paragraph("(GIST)", MAIN_TITLE))
S.append(sp(0.4))
S.append(Paragraph("Comprehensive Long Answer — Pathology Essay", SUBTITLE))
S.append(sp(0.3))
S.append(Paragraph("For MBBS / MD / Postgraduate Examinations", SUBTITLE))
S.append(sp(1.5))
div = Table([["  DEFINITION  ·  AETIOLOGY  ·  PATHOGENESIS  ·  MORPHOLOGY  ·  IHC  ·  MOLECULAR  ·  CLINICAL  ·  TREATMENT  "]], colWidths=[W_PAGE-4*cm])
div.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),TEAL),("TEXTCOLOR",(0,0),(-1,-1),WHITE),
    ("FONTNAME",(0,0),(-1,-1),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,-1),8.5),
    ("ALIGN",(0,0),(-1,-1),"CENTER"),("TOPPADDING",(0,0),(-1,-1),7),("BOTTOMPADDING",(0,0),(-1,-1),7)]))
S.append(div)
S.append(sp(1.2))
S.append(Paragraph("Orris Medical Reference  ·  Educational Use Only  ·  July 2026",
    PS("CN",fontSize=9,leading=13,fontName="Helvetica",textColor=colors.HexColor("#90A4AE"),alignment=TA_CENTER)))
S.append(PageBreak())

# ─── NORMAL PAGES ─────────────────────────────────────────────────────────────
S.append(NextPageTemplate("Normal"))

# ══ QUESTION ══════════════════════════════════════════════════════════════════
S.append(box([
    "LONG ANSWER QUESTION:",
    "Write a detailed note on Gastrointestinal Stromal Tumor (GIST) under the following headings:",
    "Definition · Epidemiology · Cell of Origin · Pathogenesis · Gross Pathology · "
    "Microscopic Pathology · Immunohistochemistry · Molecular Classification · "
    "Risk Stratification · Clinical Features · Diagnosis · Treatment · Prognosis · "
    "Hereditary Syndromes"
], bg=ORANGE_L, bd=ORANGE,
st=PS("QSt",fontSize=10.5,leading=16,fontName="Helvetica-Bold",textColor=GRAY_D,leftIndent=4)))
S.append(sp(0.3))

# ══ 1. DEFINITION ════════════════════════════════════════════════════════════
S.append(sec_bar("1.  DEFINITION", color=NAVY))
S.append(sp(0.25))
S.append(Paragraph(
    "A <b>Gastrointestinal Stromal Tumor (GIST)</b> is a <b>mesenchymal (non-epithelial) neoplasm</b> "
    "arising from the wall of the gastrointestinal tract. It is now well established as "
    "the <b>most common primary mesenchymal tumor of the GI tract and the abdomen</b>. "
    "The term was first coined by <b>Mazur and Clark in 1983</b> to describe intra-abdominal tumors "
    "that were not carcinomas but showed histologic features of both smooth muscle and neural elements. "
    "However, the true nature and molecular basis of GIST were not understood until 1998, when "
    "<b>Hirota and colleagues</b> demonstrated near-universal expression of the receptor tyrosine kinase "
    "<b>KIT (CD117)</b> and the presence of <b>gain-of-function KIT mutations</b> in these tumors, "
    "fundamentally transforming the understanding of GIST pathogenesis and treatment.", BODY))
S.append(sp(0.15))
S.append(imp_box([
    "GIST = Most common mesenchymal tumor of the GI tract",
    "Every GIST carries metastatic potential — there is NO truly benign GIST",
    "Driven by activating mutations in KIT (~80%) or PDGFRA (~8%)",
]))
S.append(sp(0.35))

# ══ 2. EPIDEMIOLOGY ══════════════════════════════════════════════════════════
S.append(sec_bar("2.  EPIDEMIOLOGY", color=NAVY))
S.append(sp(0.25))
S.append(Paragraph(
    "GIST accounts for approximately <b>1–3% of all malignant gastrointestinal tumors</b>. "
    "The estimated incidence is <b>10–15 cases per million per year</b>, though this likely "
    "underestimates the true frequency due to historical misclassification. "
    "With widespread use of molecular markers, incidence figures have increased.", BODY))
S.append(sp(0.1))
S.append(make_table(
    ["Epidemiologic Variable","Details"],
    [["Incidence",    "10–15 per million per year; up to 5,000 new cases/year in the USA"],
     ["Peak age",     "6th decade (~60 years); median age 55–65 years; <10% under age 40"],
     ["Sex",          "Slight male predominance (~55% male); equal in some series"],
     ["Pediatric GIST","Rare; median age ~12 years; female predominance; usually SDH-deficient"],
     ["Race",         "No significant racial predisposition in sporadic cases"],
     ["Sporadic vs familial","Vast majority sporadic; familial GIST syndromes are rare"],
    ], cw=[W*0.30,W*0.70]))
S.append(sp(0.35))

# ══ 3. CELL OF ORIGIN ════════════════════════════════════════════════════════
S.append(sec_bar("3.  CELL OF ORIGIN", color=TEAL))
S.append(sp(0.25))
S.append(Paragraph(
    "The cell of origin of GIST is the <b>Interstitial Cell of Cajal (ICC)</b>, "
    "or a common precursor cell shared between ICCs and smooth muscle cells. "
    "ICCs are <b>pacemaker cells of the gastrointestinal tract</b>, located within the "
    "<b>myenteric plexus (Auerbach's plexus)</b> of the muscularis propria. "
    "Their primary function is to generate <b>electrical slow waves</b> that coordinate "
    "intestinal peristalsis by linking smooth muscle cells with the autonomic nervous system.", BODY))
S.append(sp(0.15))
S.append(Paragraph("Evidence Supporting ICC Origin:", H2))
for item in [
    "ICCs and GIST cells share <b>ultrastructural features</b> combining both neural and smooth muscle phenotypes",
    "Both express <b>KIT (CD117)</b> — KIT signalling is essential for ICC development and survival",
    "Both express <b>DOG1 (ANO1)</b> — a calcium-activated chloride channel",
    "Both express <b>CD34</b> — a hematopoietic/vascular progenitor marker",
    "In NF1-associated and familial GIST, <b>diffuse ICC hyperplasia</b> precedes GIST development",
    "<b>Germline KIT mutations</b> in familial GIST syndrome cause ICC hyperplasia throughout the GI tract",
    "Extra-GI 'telocytes' (ICC-like cells) may explain rare <b>mesenteric, omental, and pancreatic GISTs</b>",
]:
    S.append(bp(item))
S.append(sp(0.35))

# ══ 4. PATHOGENESIS ══════════════════════════════════════════════════════════
S.append(sec_bar("4.  PATHOGENESIS", color=NAVY))
S.append(sp(0.25))

S.append(Paragraph("4.1  Normal KIT Signalling", H2))
S.append(Paragraph(
    "KIT is a <b>transmembrane receptor tyrosine kinase</b> encoded by the <b>KIT gene on chromosome 4q12</b>. "
    "Its natural ligand is <b>Stem Cell Factor (SCF)</b>. Upon SCF binding, KIT undergoes "
    "<b>homodimerization and autophosphorylation</b>, activating multiple downstream signalling cascades:", BODY))
for item in [
    "<b>RAS → RAF → MAPK pathway</b>: cell proliferation and survival",
    "<b>PI3K → AKT → mTOR pathway</b>: cell growth, anti-apoptosis, metabolism",
    "<b>JAK → STAT3 pathway</b>: transcription of pro-survival genes",
    "<b>PLC-γ pathway</b>: calcium mobilisation and PKC activation",
]:
    S.append(bp(item))
S.append(sp(0.15))

S.append(Paragraph("4.2  Gain-of-Function KIT Mutations (75–85% of GISTs)", H2))
S.append(Paragraph(
    "Gain-of-function mutations in the KIT gene cause <b>constitutive (ligand-independent) receptor "
    "activation</b>. The receptor is always phosphorylated and active even in the absence of SCF, "
    "leading to continuous downstream signalling, uncontrolled cell proliferation, "
    "inhibition of apoptosis, and ultimately tumour formation.", BODY))
S.append(sp(0.1))
S.append(make_table(
    ["KIT Exon","Domain","Mutation Type","% of GIST","Imatinib Response"],
    [["Exon 11","Juxtamembrane domain","Deletions (most common), insertions, point mutations","~65–70%","HIGH (~80–90%); most sensitive to standard dose 400 mg/day"],
     ["Exon 9","Extracellular domain","Tandem duplication of codons 502–503 (AY502-503)","~10–15%","MODERATE (40–50%); requires higher dose 800 mg/day; small intestinal predilection"],
     ["Exon 13","Kinase domain I","Point mutations (K642E most common)","~1–2%","Moderate; sunitinib may be preferred"],
     ["Exon 17","Kinase domain II","Point mutations (D820, N822, Y823)","~1%","Moderate; secondary resistance mutations also in exon 17"],
    ], cw=[W*0.10,W*0.20,W*0.25,W*0.12,W*0.33]))
S.append(sp(0.2))

S.append(Paragraph("4.3  PDGFRA Mutations (~8% of GISTs)", H2))
S.append(Paragraph(
    "Platelet-Derived Growth Factor Receptor Alpha (PDGFRA) is encoded by a gene also located on "
    "<b>chromosome 4q12</b>, immediately adjacent to KIT. PDGFRA belongs to the same receptor "
    "tyrosine kinase superfamily and activates identical downstream signalling pathways. "
    "<b>KIT and PDGFRA mutations are mutually exclusive</b> — they cannot coexist because "
    "activating either gene alone is sufficient to drive tumourigenesis through the same pathway.", BODY))
S.append(sp(0.1))
for item in [
    "<b>PDGFRA exon 18 D842V substitution</b>: most common PDGFRA mutation (~70% of PDGFRA-mutant GISTs); "
    "<b>primary resistance to imatinib</b>; responds to avapritinib",
    "<b>Other PDGFRA exon 18 mutations</b>: variable imatinib sensitivity",
    "<b>PDGFRA exon 12 and 14 mutations</b>: rare; may retain imatinib sensitivity",
    "PDGFRA-mutant GISTs are overrepresented in the <b>stomach and omentum</b>, more often show "
    "<b>epithelioid morphology</b>, and are frequently CD117-negative by IHC",
]:
    S.append(bp(item))
S.append(sp(0.2))

S.append(Paragraph("4.4  SDH-Deficient GISTs (Wild-Type; ~5–10%)", H2))
S.append(Paragraph(
    "A subset of GISTs are negative for both KIT and PDGFRA mutations — termed 'wild-type' GISTs. "
    "The majority of these harbour mutations in genes encoding subunits of the "
    "<b>mitochondrial succinate dehydrogenase (SDH) complex</b> (SDHA, SDHB, SDHC, or SDHD). "
    "SDH normally catalyses the conversion of succinate to fumarate in the Krebs cycle. "
    "SDH loss leads to:", BODY))
for item in [
    "<b>Succinate accumulation</b> → inhibition of prolyl hydroxylase → stabilisation of HIF-1α",
    "<b>Pseudohypoxia</b>: HIF-1α activates VEGF and other pro-angiogenic/pro-tumourigenic genes",
    "<b>Increased reactive oxygen species (ROS)</b> → genomic instability",
    "<b>Warburg effect</b>: enhanced glycolysis as primary energy source",
]:
    S.append(bp(item))
S.append(sp(0.1))
S.append(Paragraph(
    "SDH-deficient GISTs are <b>characteristically gastric, multifocal, and occur in young patients</b> "
    "(especially females). They frequently metastasise to <b>lymph nodes</b> (unlike other GISTs) and are "
    "<b>resistant to imatinib</b>. Loss of SDHB protein by IHC is the diagnostic hallmark.", BODY))
S.append(sp(0.2))

S.append(Paragraph("4.5  Other Wild-Type GISTs", H2))
S.append(make_table(
    ["Subtype","Molecular Feature","Clinical Context"],
    [["NF1-associated","NF1 biallelic loss; KIT overexpression without mutation","Multiple small intestinal GISTs; neurofibromatosis type 1; low mitotic rate"],
     ["BRAF V600E","BRAF activating mutation","Rare; may respond to BRAF inhibitors (vemurafenib)"],
     ["KRAS-mutant","KRAS oncogenic mutation","Very rare; sporadic"],
     ["Familial GIST","Germline KIT or PDGFRA mutation","Multiple GISTs + diffuse ICC hyperplasia; autosomal dominant; early onset; cutaneous hyperpigmentation"],
    ], cw=[W*0.22,W*0.30,W*0.48]))
S.append(sp(0.35))

# ══ 5. GROSS PATHOLOGY ═══════════════════════════════════════════════════════
S.append(sec_bar("5.  GROSS PATHOLOGY", color=BLUE))
S.append(sp(0.25))

S.append(Paragraph("Location:", H2))
S.append(Paragraph(
    "GISTs arise from the <b>muscularis propria</b> of the GI tract wall. The most common sites are "
    "the <b>stomach (40–60%)</b>, followed by the small intestine — particularly the "
    "<b>jejunum and ileum (24–30%)</b>. The colorectum accounts for 5–15%, the duodenum ~5%, "
    "and the esophagus less than 1%. Rare extra-GI stromal tumors arise in the mesentery, "
    "omentum, and retroperitoneum.", BODY))
S.append(sp(0.15))

S.append(Paragraph("Macroscopic Features:", H2))
for item in [
    "<b>Solitary, well-circumscribed, fleshy mass</b> — the typical presentation of a primary GIST",
    "Covered by a <b>pseudocapsule</b> (NOT a true capsule) — the tumour compresses surrounding tissue but is not truly encapsulated",
    "<b>Growth pattern</b>: endoluminal (projecting into lumen), exophytic (projecting outward), or dumbbell-shaped (both directions simultaneously)",
    "<b>Cut surface</b>: tan-white to pinkish; firm to soft; fleshy consistency resembling fish-flesh",
    "<b>Haemorrhage</b>: common, especially in larger tumors — areas of dark red-brown discolouration",
    "<b>Necrosis</b>: yellow-grey areas; correlates with high-grade biology and large size",
    "<b>Cystic degeneration</b>: fluid-filled spaces within the tumour; common in large GISTs",
    "<b>Mucosal ulceration</b>: overlying mucosa may ulcerate due to pressure necrosis — accounts for GI bleeding",
    "<b>Size range</b>: from &lt;1 cm (incidental microGIST) to &gt;30 cm (giant GIST)",
]:
    S.append(bp(item))
S.append(sp(0.15))

S.append(Paragraph("Metastatic Gross Features:", H2))
for item in [
    "<b>Liver metastases</b>: multiple hypervascular nodules, largest organs affected; may be solitary large mass",
    "<b>Peritoneal seeding</b>: scattered serosal nodules of varying sizes",
    "<b>Omental caking</b>: diffuse peritoneal infiltration in advanced cases",
    "<b>Lymph node involvement</b>: RARE in KIT/PDGFRA-mutant GIST; more common in SDH-deficient subtype",
    "<b>Extra-abdominal metastasis</b>: lungs, bones — uncommon and indicates late disease",
]:
    S.append(bp(item))
S.append(sp(0.15))
S.append(box([
    "⚠  CRITICAL: GIST has a pseudocapsule — NOT a true capsule.",
    "    Rupture (spontaneous or iatrogenic/surgical) dramatically increases peritoneal recurrence risk.",
    "    A ruptured GIST must be managed as already disseminated/metastatic disease."
], bg=RED_L, bd=RED,
st=PS("WSt",fontSize=10,leading=15,fontName="Helvetica-Bold",textColor=GRAY_D,leftIndent=4)))
S.append(sp(0.35))

# ══ 6. MICROSCOPIC PATHOLOGY ═════════════════════════════════════════════════
S.append(sec_bar("6.  MICROSCOPIC (HISTOLOGICAL) PATHOLOGY", color=NAVY))
S.append(sp(0.25))

S.append(Paragraph(
    "Histology alone is <b>insufficient</b> for a definitive GIST diagnosis — IHC and molecular "
    "studies are mandatory. Three main histological patterns are recognised:", BODY))
S.append(sp(0.1))

S.append(Paragraph("6.1  Spindle Cell Type (~70%)", H3))
S.append(Paragraph(
    "The most common pattern. Tumour cells are <b>thin, elongated, uniform, and spindle-shaped</b> "
    "with pale, eosinophilic, fibrillary cytoplasm. The nuclei are oval, vesicular, "
    "with inconspicuous nucleoli. Cells are arranged in:", BODY_IND))
for item in [
    "<b>Short fascicles</b> or interlacing bundles",
    "<b>Storiform (cartwheel) pattern</b> — cells radiating from a central point",
    "<b>Whorling or palisading</b> of nuclei (reminiscent of schwannoma)",
    "Sheet-like growth in solid areas",
]:
    S.append(bp2(item))
S.append(sp(0.1))
S.append(Paragraph(
    "A characteristic finding in <b>small intestinal spindle-cell GISTs</b> is the presence of "
    "<b>skeinoid fibres</b> — eosinophilic, PAS-positive, extracellular globular deposits of "
    "collagen-like material in the stroma. These are highly specific for small intestinal GIST.", BODY_IND))
S.append(sp(0.1))

S.append(Paragraph("6.2  Epithelioid Type (~20%)", H3))
S.append(Paragraph(
    "Tumour cells are <b>plumper and rounder</b> with abundant clear or eosinophilic cytoplasm, "
    "giving an epithelial appearance. Characteristic features include:", BODY_IND))
for item in [
    "<b>Perinuclear cytoplasmic vacuoles</b> — highly characteristic of epithelioid GIST",
    "<b>Nesting or sheet-like</b> arrangement of cells",
    "Clear cell change due to glycogen accumulation",
    "May mimic carcinoma, melanoma, or paraganglioma",
    "More commonly seen in <b>gastric GISTs</b> and <b>PDGFRA-mutant tumors</b>",
]:
    S.append(bp2(item))
S.append(sp(0.1))

S.append(Paragraph("6.3  Mixed Type (~10%)", H3))
S.append(Paragraph(
    "Both spindle and epithelioid components are present in varying proportions within the same tumour. "
    "This pattern can occur at any GI site.", BODY_IND))
S.append(sp(0.15))

S.append(Paragraph("6.4  Additional Microscopic Features", H2))
S.append(make_table(
    ["Feature","Significance"],
    [["Mitotic figures (per 50 HPF)","Most critical prognostic variable after size; counted carefully under high power"],
     ["Nuclear atypia","Usually mild to moderate; severe pleomorphism is uncommon and suggests high grade"],
     ["Tumour necrosis","Correlates with high-grade behaviour; indicates rapid growth outpacing blood supply"],
     ["Skeinoid fibres","Eosinophilic extracellular globules; seen in small intestinal GISTs; PAS-positive"],
     ["Haemorrhage","Common in larger tumours; disrupts architecture"],
     ["Myxoid change","Occasional finding; may mimic other stromal tumours"],
     ["Perivascular condensation","Cells condense around blood vessels in some cases"],
    ], cw=[W*0.35,W*0.65]))
S.append(sp(0.2))

S.append(Paragraph("6.5  What Histology CANNOT Tell You", H2))
S.append(Paragraph(
    "The pre-1999 classification divided GI mesenchymal tumors into leiomyoma, leiomyosarcoma, "
    "schwannoma, or 'null phenotype' based purely on histomorphology and rudimentary IHC. "
    "This led to systematic misdiagnosis. <b>Morphology alone cannot reliably distinguish GIST "
    "from leiomyosarcoma, schwannoma, or desmoid tumour</b> — hence the absolute requirement for "
    "IHC markers (CD117, DOG1) and molecular testing in all suspected cases.", BODY))
S.append(sp(0.35))

# ══ 7. IMMUNOHISTOCHEMISTRY ═══════════════════════════════════════════════════
S.append(sec_bar("7.  IMMUNOHISTOCHEMISTRY (IHC)", color=TEAL))
S.append(sp(0.25))
S.append(Paragraph(
    "IHC is the cornerstone of GIST diagnosis. The two most critical markers — <b>CD117 (KIT)</b> and "
    "<b>DOG1</b> — are each positive in approximately 95% of GISTs and should always be used together.", BODY))
S.append(sp(0.15))

S.append(make_table(
    ["Marker","Sensitivity","Staining Pattern","Key Points"],
    [["CD117 (KIT/c-kit)","~95%","Strong diffuse cytoplasmic (spindle); focal/dot-like (epithelioid); perinuclear",
      "Primary diagnostic marker; cornerstone; can be heterogeneous within tumour — sampling bias possible"],
     ["DOG1 (ANO1)","~95%","Membranous and/or cytoplasmic",
      "More specific than CD117; ESSENTIAL for diagnosing KIT-negative GISTs; complements CD117"],
     ["CD34","~60–70%","Diffuse cytoplasmic",
      "Supportive marker; expressed by vascular endothelium too — not specific; lower sensitivity than CD117/DOG1"],
     ["PDGFRA (IHC)","~70–80% of PDGFRA-mutant","Cytoplasmic",
      "Helps identify PDGFRA-mutant subtype when CD117 is negative; not routinely available everywhere"],
     ["SDHB (IHC)","N/A (loss marker)","Normal: granular cytoplasmic; SDH-deficient: diffuse/absent",
      "Loss of granular SDHB staining = SDH-deficient GIST; perform on ALL wild-type GISTs"],
     ["Smooth muscle actin (SMA)","~30–40%","Cytoplasmic",
      "Variably positive; does NOT exclude GIST; helps exclude leiomyosarcoma if strongly positive with desmin"],
     ["Desmin","~5–10%","Cytoplasmic",
      "Usually negative in GIST; strongly positive in leiomyosarcoma — useful in differential diagnosis"],
     ["S100 protein","<5%","Nuclear + cytoplasmic",
      "Usually negative in GIST; strongly positive in schwannoma — key differential marker"],
     ["Beta-catenin","Negative (nuclear)","Cytoplasmic only normally",
      "Nuclear positivity in desmoid tumour — helps exclude aggressive fibromatosis"],
    ], cw=[W*0.20,W*0.12,W*0.26,W*0.42], hc=TEAL))
S.append(sp(0.2))

S.append(Paragraph("IHC Diagnostic Algorithm in Practice:", H2))
S.append(make_table(
    ["Step","Action","Interpretation"],
    [["1","Stain with CD117 + DOG1 on all suspected GI mesenchymal tumours","—"],
     ["2","CD117 (+) and/or DOG1 (+)","Likely GIST → confirm with molecular testing"],
     ["3","CD117 (–), DOG1 (+)","Still GIST — likely PDGFRA-mutant; proceed to PDGFRA sequencing"],
     ["4","Both CD117 (–) and DOG1 (–)","Consider: leiomyosarcoma (desmin/SMA+), schwannoma (S100+), desmoid (β-catenin nuclear+), metastatic carcinoma (cytokeratin+)"],
     ["5","On all confirmed GISTs: stain SDHB","Loss of SDHB = SDH-deficient — critical for syndrome screening and treatment planning"],
    ], cw=[W*0.06,W*0.37,W*0.57]))
S.append(sp(0.2))
S.append(imp_box([
    "Never diagnose GIST on histology alone.",
    "Always use CD117 AND DOG1 together — they are complementary, not interchangeable.",
    "CD117 can be heterogeneous (sampling bias) — DOG1 may be positive where CD117 is negative.",
]))
S.append(sp(0.35))

# ══ 8. MOLECULAR CLASSIFICATION ══════════════════════════════════════════════
S.append(sec_bar("8.  MOLECULAR CLASSIFICATION", color=NAVY))
S.append(sp(0.25))
S.append(Paragraph(
    "Molecular classification of GIST is <b>essential for prognostication and treatment selection</b>. "
    "It is based on sequencing of KIT exons 9, 11, 13, 17 and PDGFRA exons 12, 14, 18, "
    "followed by SDH subunit gene sequencing and SDHB IHC in wild-type cases.", BODY))
S.append(sp(0.1))
S.append(make_table(
    ["Molecular Subtype","Frequency","Key Mutation","Imatinib Sensitivity","Special Features"],
    [["KIT exon 11","~65–70%","Deletions > insertions > point mutations","HIGH (~80–90%)","Best overall prognosis on imatinib; deletions in codons 557–558 associated with worse prognosis"],
     ["KIT exon 9","~10–15%","AY502-503 duplication","MODERATE (40–50%)","Needs 800 mg/day; predominantly small intestinal; worse prognosis than exon 11"],
     ["KIT exon 13","~1–2%","K642E point mutation","MODERATE","Kinase domain I; secondary resistance mutation too"],
     ["KIT exon 17","~1%","D820/N822/Y823 mutations","MODERATE","Kinase domain II; often secondary resistance mutations"],
     ["PDGFRA D842V","~5–6%","D842V substitution exon 18","RESISTANT","Use avapritinib; gastric/epithelioid; CD117-negative"],
     ["PDGFRA other","~1–2%","Various exon 12/14/18","Variable","May respond to imatinib"],
     ["SDH-deficient","~5–10%","SDHA/B/C/D mutations","RESISTANT","Young; female; gastric; multifocal; lymph node mets; Carney triad"],
     ["NF1-associated","~1%","NF1 biallelic loss","Uncertain","Multiple small bowel GISTs; wild-type KIT/PDGFRA"],
     ["BRAF-mutant","<1%","BRAF V600E","Resistant","May respond to BRAF inhibitors"],
    ], cw=[W*0.20,W*0.10,W*0.20,W*0.14,W*0.36]))
S.append(sp(0.35))

# ══ 9. RISK STRATIFICATION ═══════════════════════════════════════════════════
S.append(sec_bar("9.  RISK STRATIFICATION", color=BLUE))
S.append(sp(0.25))
S.append(Paragraph(
    "Since every GIST has metastatic potential, <b>risk stratification</b> is critical for "
    "determining prognosis and the need for adjuvant therapy. Three primary variables determine risk:", BODY))
for item in [
    "<b>Tumour size</b> — the larger the tumour, the higher the risk",
    "<b>Mitotic rate</b> — counted per 50 high-power fields (HPF); reflects proliferative activity",
    "<b>Primary site</b> — non-gastric GISTs (especially small intestinal and rectal) are more aggressive",
]:
    S.append(bp(item))
S.append(sp(0.15))
S.append(Paragraph("A fourth critical factor:  <b>Tumour Rupture</b> (spontaneous or operative) — "
    "automatically places the patient in the highest risk category regardless of size or mitotic rate.", BODY))
S.append(sp(0.2))

S.append(Paragraph("9.1  NIH (Fletcher) Consensus Classification — Widely Used", H2))
S.append(make_table(
    ["Risk Category","Tumour Size","Mitotic Rate (per 50 HPF)"],
    [["Very Low Risk","< 2 cm","< 5"],
     ["Low Risk","2–5 cm","< 5"],
     ["Intermediate Risk","< 5 cm   OR   5–10 cm","6–10   OR   < 5"],
     ["High Risk","> 5 cm   OR   > 10 cm   OR   Any size","Any   OR   Any   OR   > 10"],
    ], cw=[W*0.25,W*0.35,W*0.40]))
S.append(sp(0.15))
S.append(Paragraph(
    "<i>Limitation: NIH system does NOT incorporate tumour site — it treats all GISTs equally regardless of location.</i>", NOTE))
S.append(sp(0.15))

S.append(Paragraph("9.2  Joensuu / AFIP Modified Criteria — Site-Specific Risk", H2))
S.append(make_table(
    ["Size","Mitotic Rate","Gastric GIST Risk","Non-Gastric GIST Risk"],
    [["≤ 2 cm","≤ 5 / 50 HPF","Negligible","Negligible"],
     ["2–5 cm","≤ 5 / 50 HPF","Very Low","Low"],
     ["5–10 cm","≤ 5 / 50 HPF","Low","Moderate"],
     ["> 10 cm","≤ 5 / 50 HPF","Moderate","HIGH"],
     ["Any","6–10 / 50 HPF","Moderate","HIGH"],
     ["Any","> 10 / 50 HPF","HIGH","HIGH"],
     ["Any (ruptured)","Any","HIGH","HIGH"],
    ], cw=[W*0.18,W*0.22,W*0.30,W*0.30]))
S.append(sp(0.15))

S.append(Paragraph("9.3  AJCC Staging (8th Edition)", H2))
S.append(Paragraph(
    "Uses standard TNM staging supplemented by mitotic rate. Separate stage groupings exist for "
    "<b>gastric and omental GISTs</b> versus <b>small intestinal, esophageal, colorectal, mesenteric, "
    "and peritoneal GISTs</b>, reflecting their different biologic behaviour. "
    "T stages: T1 (≤2 cm), T2 (2–5 cm), T3 (5–10 cm), T4 (>10 cm). "
    "Nodal disease (N1) is uncommon and indicates high-risk/SDH-deficient subtype.", BODY))
S.append(sp(0.35))

# ══ 10. CLINICAL FEATURES ════════════════════════════════════════════════════
S.append(sec_bar("10.  CLINICAL FEATURES", color=NAVY))
S.append(sp(0.25))

S.append(Paragraph("Symptoms and Presentation:", H2))
S.append(make_table(
    ["Presentation","Mechanism","Notes"],
    [["Gastrointestinal bleeding","Mucosal ulceration from endoluminal pressure; necrosis; haemorrhage into lumen","Most common presenting symptom; haematemesis, melaena, or occult blood"],
     ["Abdominal pain / discomfort","Mass effect, stretching of serosa, or partial obstruction","Dull, vague, intermittent; often chronic before diagnosis"],
     ["Palpable abdominal mass","Large exophytic tumour","Felt in left upper quadrant (gastric) or central abdomen (small bowel)"],
     ["Obstruction symptoms","Intraluminal growth causing narrowing","Nausea, vomiting, dysphagia (esophageal GIST), constipation (rectal GIST)"],
     ["Incidental finding","Small tumour with no symptoms","Common on endoscopy/imaging for unrelated indications; typically < 2 cm"],
     ["Acute abdomen","Spontaneous tumour rupture → haemoperitoneum","Surgical emergency; treat as disseminated disease"],
     ["Weight loss and anorexia","Large tumours; metastatic disease","Late features suggesting advanced or metastatic GIST"],
    ], cw=[W*0.22,W*0.30,W*0.48]))
S.append(sp(0.35))

# ══ 11. DIAGNOSIS ════════════════════════════════════════════════════════════
S.append(sec_bar("11.  DIAGNOSIS", color=TEAL))
S.append(sp(0.25))

S.append(Paragraph("11.1  Imaging", H2))
for item in [
    "<b>CT scan with IV contrast (MDCT)</b>: imaging modality of choice. Shows well-circumscribed, "
    "heterogeneous, hypervascular mass; evaluates size, location, local invasion, liver metastases, "
    "and peritoneal disease",
    "<b>Endoscopic Ultrasound (EUS)</b>: defines tumour layer of origin (muscularis propria); "
    "guides fine-needle aspiration (FNA) biopsy in accessible lesions; essential for small gastric lesions",
    "<b>MRI</b>: preferred for rectal and pelvic GISTs; superior soft-tissue contrast",
    "<b>PET-CT (18F-FDG)</b>: detects early metabolic response to imatinib (hours to days before size change); "
    "used for treatment monitoring, not initial diagnosis",
    "<b>Choi criteria for CT response assessment</b>: a ≥10% decrease in size OR ≥15% decrease in "
    "Hounsfield unit (HU) density = partial response — more sensitive than RECIST for GIST on imatinib",
]:
    S.append(bp(item))
S.append(sp(0.15))

S.append(Paragraph("11.2  Biopsy", H2))
for item in [
    "<b>Resectable GIST</b>: biopsy is generally NOT recommended — risk of tumour rupture, haemorrhage, "
    "and peritoneal seeding; proceed directly to surgery",
    "<b>Unresectable or metastatic GIST</b>: biopsy is mandatory before initiating imatinib therapy "
    "to confirm diagnosis and determine mutation status",
    "<b>EUS-guided FNA</b>: preferred biopsy route for gastric GISTs — avoids peritoneal seeding by "
    "traversing the stomach wall",
    "<b>Core needle biopsy</b>: preferred over FNA for adequate tissue for IHC and molecular testing",
]:
    S.append(bp(item))
S.append(sp(0.15))

S.append(Paragraph("11.3  Pathological Workup (Mandatory Steps)", H2))
for item in [
    "<b>Histomorphology</b>: document cell type (spindle/epithelioid/mixed), mitotic rate (per 50 HPF), necrosis",
    "<b>IHC panel</b>: CD117, DOG1, CD34 (core); SMA, desmin, S100 (differential diagnosis)",
    "<b>SDHB IHC</b>: on all GISTs to screen for SDH-deficient subtype",
    "<b>Mutation analysis</b>: KIT exons 9, 11, 13, 17 and PDGFRA exons 12, 14, 18 — mandatory before targeted therapy",
    "<b>SDH subunit gene sequencing</b>: in wild-type (KIT/PDGFRA-negative) GISTs",
    "<b>Tumour size and margin status</b>: document in resection specimens",
]:
    S.append(bp(item))
S.append(sp(0.35))

# ══ 12. TREATMENT ════════════════════════════════════════════════════════════
S.append(sec_bar("12.  TREATMENT", color=NAVY))
S.append(sp(0.25))

S.append(Paragraph("12.1  Surgery — Primary Treatment for Localised GIST", H2))
S.append(make_table(
    ["Principle","Details"],
    [["Goal","Complete (R0) resection with negative margins — only potentially curative modality"],
     ["Margin width","1–2 cm recommended; the pseudocapsule must remain intact and not be violated"],
     ["Lymphadenectomy","NOT routinely performed — lymph node involvement is rare in KIT/PDGFRA-mutant GIST; exception: SDH-deficient"],
     ["Laparoscopic surgery","Acceptable for gastric GISTs ≤ 5 cm; meticulous technique required to avoid rupture"],
     ["Multivisceral resection","When tumour invades adjacent organs; required to achieve R0 margins"],
     ["Rectal GIST","Preoperative imatinib often used to downsize and allow sphincter-sparing resection"],
     ["Avoid rupture","Paramount — increases peritoneal recurrence risk dramatically; changed intent to palliative"],
    ], cw=[W*0.28,W*0.72]))
S.append(sp(0.2))

S.append(Paragraph("12.2  Imatinib Mesylate (Gleevec) — Targeted Therapy", H2))
S.append(Paragraph(
    "Imatinib is a <b>selective tyrosine kinase inhibitor (TKI)</b> that competitively inhibits "
    "<b>KIT, PDGFRA, BCR-ABL, and PDGFRB</b> by occupying the ATP-binding pocket of the kinase domain. "
    "Its introduction in 2001 transformed GIST from a chemotherapy-resistant malignancy into a "
    "manageable disease. The landmark B2222 trial demonstrated response rates of ~54% in metastatic GIST, "
    "with disease control in >80% of patients.", BODY))
S.append(sp(0.1))
S.append(make_table(
    ["Clinical Setting","Indication","Dose","Duration"],
    [["Adjuvant (post-resection)","High-risk resected GIST with imatinib-sensitive mutation (KIT exon 11 primarily)","400 mg/day","3 years (standard); trials evaluating 5+ years"],
     ["Neoadjuvant (pre-surgery)","Marginally resectable; large tumour requiring downsizing; rectal GIST (sphincter preservation)","400 mg/day","Until maximal response (~6–12 months); re-assess with CT/PET"],
     ["Metastatic / unresectable","Systemic therapy for disseminated disease","400 mg/day (KIT exon 11); 800 mg/day (KIT exon 9)","Lifelong — discontinuation leads to rapid progression in >80%"],
     ["PDGFRA D842V","NOT indicated","—","Resistant — use avapritinib"],
    ], cw=[W*0.22,W*0.33,W*0.18,W*0.27]))
S.append(sp(0.15))

S.append(Paragraph("12.3  Mechanisms of Imatinib Resistance", H2))
for item in [
    "<b>Primary resistance</b>: present from the outset; PDGFRA D842V mutation; SDH-deficient wild-type; "
    "some KIT exon 9 mutations",
    "<b>Secondary (acquired) resistance</b>: develops after initial response (median ~24 months); "
    "caused by <b>secondary kinase domain mutations in KIT exons 13, 14, 17, or 18</b>",
    "Secondary resistance often shows <b>clonal progression</b> (one or few nodules progressing while "
    "others remain controlled) — detectable on PET-CT",
    "Management: <b>switch to sunitinib</b> (2nd line); <b>regorafenib</b> (3rd line); <b>ripretinib</b> (4th line)",
]:
    S.append(bp(item))
S.append(sp(0.2))

S.append(Paragraph("12.4  Second-, Third-, and Fourth-Line Therapies", H2))
S.append(make_table(
    ["Drug","Line","Mechanism","Key Indication"],
    [["Sunitinib","2nd line","Multi-TKI: KIT + PDGFRA + VEGFR1–3 + FLT3","Imatinib-resistant/intolerant GIST; specific secondary KIT mutations guide response"],
     ["Regorafenib","3rd line","Multi-TKI: KIT + PDGFRA + VEGFR + RAF","After sunitinib failure; GRID trial demonstrated benefit"],
     ["Ripretinib","4th line","Switch-control inhibitor: broad KIT/PDGFRA inhibition","Designed to overcome resistance mutations; INTRIGUE trial"],
     ["Avapritinib","1st line (D842V)","Potent PDGFRA/KIT inhibitor","FDA-approved for PDGFRA exon 18 D842V mutant unresectable/metastatic GIST; NAVIGATOR trial"],
    ], cw=[W*0.18,W*0.12,W*0.32,W*0.38]))
S.append(sp(0.15))

S.append(Paragraph("12.5  Chemotherapy and Radiation", H2))
S.append(Paragraph(
    "Conventional cytotoxic chemotherapy is <b>largely ineffective</b> in GIST — response rates "
    "with doxorubicin or ifosfamide are below 5%. This is due to overexpression of the "
    "<b>MDR1/P-glycoprotein drug efflux pump</b> in GIST cells. "
    "Radiotherapy has limited application — palliative role for bone metastases or local control "
    "in selected unresectable cases. "
    "Immunotherapy (checkpoint inhibitors) shows limited activity in KIT/PDGFRA-mutant GIST "
    "due to low tumour mutational burden, but may have a role in SDH-deficient subtype "
    "(high inflammatory microenvironment).", BODY))
S.append(sp(0.35))

# ══ 13. PROGNOSIS ════════════════════════════════════════════════════════════
S.append(sec_bar("13.  PROGNOSIS", color=BLUE))
S.append(sp(0.25))
S.append(Paragraph(
    "Prognosis in GIST depends on a combination of tumour-related, treatment-related, "
    "and molecular factors.", BODY))
S.append(sp(0.1))
S.append(make_table(
    ["Favourable Prognostic Factors","Unfavourable Prognostic Factors"],
    [["Gastric location","Non-gastric location (small intestine, rectum, esophagus)"],
     ["Small tumour size (< 2 cm)","Large tumour size (> 5 cm or > 10 cm)"],
     ["Low mitotic rate (< 5/50 HPF)","High mitotic rate (> 5/50 HPF)"],
     ["KIT exon 11 mutation","KIT exon 9 mutation; wild-type"],
     ["Complete R0 surgical resection","Positive surgical margins (R1/R2); rupture"],
     ["No metastases at presentation","Liver or peritoneal metastases"],
     ["Response to imatinib","Primary or secondary imatinib resistance"],
     ["Low risk by NIH/Joensuu criteria","High-risk classification"],
    ], cw=[W*0.50,W*0.50]))
S.append(sp(0.15))
S.append(Paragraph(
    "Recurrence or metastasis is <b>rare for gastric GISTs &lt; 5 cm</b> with low mitotic rate "
    "but is <b>common for mitotically active tumours &gt; 10 cm</b>. "
    "Patients with metastatic imatinib-sensitive GIST now achieve <b>median overall survival of "
    "5+ years</b> with targeted therapy, compared to &lt;18 months before imatinib. "
    "The <b>10-year overall survival for resected low-risk GIST approaches 90%</b> with appropriate management.", BODY))
S.append(sp(0.35))

# ══ 14. HEREDITARY SYNDROMES ═════════════════════════════════════════════════
S.append(sec_bar("14.  HEREDITARY SYNDROMES ASSOCIATED WITH GIST", color=NAVY))
S.append(sp(0.25))
S.append(make_table(
    ["Syndrome","GIST Features","Associated Tumours","Genetic Basis","Inheritance"],
    [["Carney Triad",
      "Gastric GIST; multifocal; SDH-deficient; young females (median ~20 yrs); lymph node mets",
      "Pulmonary chondromas + Extra-adrenal paragangliomas",
      "SDHC promoter hypermethylation (epigenetic); no germline SDH mutation in most",
      "Not clearly heritable; sporadic (most)"],
     ["Carney-Stratakis Dyad",
      "Gastric GIST; multifocal; SDH-deficient; similar to Carney Triad GIST",
      "Paraganglioma only (no pulmonary chondroma)",
      "Germline mutations in SDHA, SDHB, SDHC, or SDHD",
      "Autosomal dominant"],
     ["Familial GIST Syndrome",
      "Multiple GISTs any GI site; diffuse ICC hyperplasia; early onset (3rd–4th decade); cutaneous hyperpigmentation; urticaria pigmentosa",
      "None specific; mast cell tumours occasionally",
      "Germline KIT gain-of-function (most common) or PDGFRA mutations",
      "Autosomal dominant; high penetrance"],
     ["NF1 (von Recklinghausen)",
      "Multiple small intestinal GISTs; usually small; low mitotic rate; often incidental; KIT overexpressed but NOT mutated",
      "Neurofibromas, gliomas, phaeochromocytoma, learning difficulties, café-au-lait macules",
      "NF1 biallelic loss (tumour suppressor); KIT/PDGFRA unmutated; distinct biology",
      "Autosomal dominant; NF1 germline mutation"],
    ], cw=[W*0.18,W*0.26,W*0.22,W*0.22,W*0.12], hc=NAVY))
S.append(sp(0.15))
S.append(imp_box([
    "Carney Triad mnemonic:  G.P.P.  =  Gastric GIST  +  Pulmonary chondroma  +  Paraganglioma",
    "Carney-Stratakis Dyad = G.P. only (no pulmonary chondroma) + germline SDH mutation",
    "Familial GIST: suspect when multiple GISTs, young patient, family history, or ICC hyperplasia on biopsy",
]))
S.append(sp(0.35))

# ══ 15. DIFFERENTIAL DIAGNOSIS ═══════════════════════════════════════════════
S.append(sec_bar("15.  DIFFERENTIAL DIAGNOSIS", color=TEAL))
S.append(sp(0.25))
S.append(make_table(
    ["Tumour","Key Distinguishing Features","Helpful IHC"],
    [["Leiomyosarcoma","Smooth muscle differentiation; coagulative necrosis; cytological atypia; rare in stomach","SMA+, Desmin+, CD117–, DOG1–"],
     ["Leiomyoma","Benign; well-differentiated smooth muscle; rare in stomach (common in oesophagus/colorectum)","SMA+, Desmin+, CD117–, DOG1–"],
     ["Schwannoma","Neural differentiation; peripheral lymphocyte cuffing; no CD117; female preponderance","S100+ (strong diffuse), CD117–, DOG1–"],
     ["Desmoid tumour","Aggressive fibromatosis; deep soft tissue; FAP association; no atypia","Beta-catenin nuclear+, CD117–, DOG1–, SMA+"],
     ["Solitary fibrous tumour","STAT6 nuclear+; CD34+; branching haemangiopericytoma-like vessels","STAT6+, CD34+, CD117–"],
     ["Metastatic melanoma","History; S100+, HMB-45+, Melan-A+; CD117+ (but clinical context clear)","S100+, SOX10+, HMB-45+"],
     ["Inflammatory fibrosarcoma","ALK translocation; inflammatory infiltrate; mesenteric origin","ALK+ (IHC or FISH), CD117–"],
    ], cw=[W*0.20,W*0.45,W*0.35], hc=TEAL))
S.append(sp(0.35))

# ══ 16. SUMMARY ══════════════════════════════════════════════════════════════
S.append(sec_bar("16.  SUMMARY — HIGH-YIELD POINTS", color=NAVY))
S.append(sp(0.25))
S.append(make_table(
    ["Topic","High-Yield Fact"],
    [["Definition","Most common GI mesenchymal tumour; 1–3% of all GI malignancies; every GIST has metastatic potential"],
     ["Cell of origin","Interstitial cells of Cajal (ICC) — pacemaker cells of the myenteric plexus"],
     ["Most common site","Stomach (40–60%) → Small intestine (24–30%) → Colorectum (5–15%)"],
     ["Histology","Spindle (~70%), Epithelioid (~20%), Mixed (~10%); skeinoid fibres in small intestinal GIST"],
     ["Key IHC","CD117 + DOG1 (~95% each); SDHB loss = SDH-deficient subtype"],
     ["Main mutation","KIT exon 11 (~65–70%) — BEST imatinib response (~80–90%)"],
     ["Worst mutation (Rx)","PDGFRA exon 18 D842V — RESISTANT to imatinib; use avapritinib"],
     ["Risk pillars","Size + Mitotic rate (per 50 HPF) + Site + Rupture status"],
     ["Lymph node spread","RARE in KIT/PDGFRA-mutant; common in SDH-deficient pediatric GIST"],
     ["Surgery rule","R0 resection; NO routine lymphadenectomy; never rupture the pseudocapsule"],
     ["Adjuvant therapy","Imatinib 3 years for high-risk resected GIST (KIT-sensitive mutations)"],
     ["Chemo/Radiotherapy","Largely ineffective — MDR1/P-glycoprotein overexpression; TKIs are the backbone"],
     ["Carney Triad","Gastric GIST + Pulmonary chondroma + Extra-adrenal paraganglioma"],
     ["Resistance mechanism","Secondary KIT kinase domain mutations (analogous to BCR-ABL in CML)"],
     ["Prognosis (metastatic)","Median OS > 5 years with imatinib; vs < 18 months pre-imatinib era"],
    ], cw=[W*0.30,W*0.70]))
S.append(sp(0.25))
S.append(hr(NAVY))
S.append(Paragraph(
    "References: Robbins &amp; Kumar Basic Pathology · Sleisenger &amp; Fordtran's GI and Liver Disease · "
    "Sabiston Textbook of Surgery · Quick Compendium of Clinical Pathology 5e · "
    "Fischer's Mastery of Surgery 8e · Current Surgical Therapy 14e · Schwartz's Principles of Surgery 11e · "
    "Goodman &amp; Gilman's Pharmacological Basis of Therapeutics · Maingot's Abdominal Operations",
    NOTE))
S.append(Paragraph(
    "PubMed (2025): PMID 40665034 (ctDNA meta-analysis) · PMID 40045030 (SDH-deficient GIST systemic therapies) · "
    "PMID 40140195 (neoadjuvant imatinib meta-analysis)",
    NOTE))
S.append(Paragraph("This document is for educational purposes only. Clinical decisions require current guidelines and individualised assessment.", NOTE))

# ── BUILD ─────────────────────────────────────────────────────────────────────
doc.build(S)
print(f"✅  PDF created: {OUTPUT}")
Running Command

cd /home/daytona/workspace/gist-pathology && python gist_long_answer.py 2>&1

Your long-answer PDF is ready:

GIST Long Answer

PDF Document · PDF


Here is what the PDF covers across 16 sections in full exam-style long-answer format:
SectionContent
Question panelThe full long-answer question written out at the top
1. DefinitionHistory, Mazur & Clark 1983, Hirota 1998 discovery
2. EpidemiologyIncidence, age, sex, pediatric GIST table
3. Cell of OriginICCs, myenteric plexus, evidence for ICC origin (7 points)
4. PathogenesisNormal KIT signalling → gain-of-function mutations → KIT exon table → PDGFRA → SDH mechanism → other wild-type subtypes
5. Gross PathologyMacroscopic features, growth patterns, metastatic sites, pseudocapsule warning
6. Microscopic PathologySpindle/epithelioid/mixed with full details, skeinoid fibres, mitotic counting, pre-1999 history
7. IHCFull 9-marker table + step-by-step diagnostic algorithm
8. Molecular ClassificationComplete mutation landscape table with all 9 subtypes
9. Risk StratificationNIH Fletcher table + Joensuu site-specific table + AJCC staging
10. Clinical Features7-row symptoms table with mechanism and notes
11. DiagnosisImaging (CT/EUS/MRI/PET, Choi criteria), biopsy rules, mandatory pathology workup
12. TreatmentSurgery principles, imatinib (adjuvant/neoadjuvant/metastatic), resistance mechanisms, 2nd-4th line drugs, chemotherapy failure reason
13. PrognosisFavourable vs unfavourable factors table, survival figures
14. Hereditary SyndromesCarney Triad, Carney-Stratakis, Familial GIST, NF1 — full table
15. Differential Diagnosis7-tumour table with distinguishing features and IHC
16. Summary Card15-row high-yield facts table for quick revision
This is a shared conversation. Sign in to Orris to start your own chat.