// renal.sy -- Nephron physiology, glomerular filtration, tubular transport,
// RAAS, and clinical nephrology as native Scyla.
//
// The kidney is a 1-million-unit parallel processor. Each nephron is an
// independent filtration-reabsorption pipeline. The glomerulus is a
// pressure-driven sieve; the tubule is a segment-specific transporter
// array. RAAS is the feedback controller. Diuretics are targeted
// transporter knockouts. CKD staging is loss-of-throughput monitoring.
//
// Sources:
//   Guyton AC, Hall JE. Textbook of Medical Physiology, 14th ed, 2021.
//   Boron WF, Boulpaep EL. Medical Physiology, 3rd ed, 2017.
//   Brenner BM, Rector FC. The Kidney, 11th ed, 2020.
//   Mount DB. Thick ascending limb of the loop of Henle.
//     Clin J Am Soc Nephrol 9:1974-1986, 2014.
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536

// ═══════════════════════════════════════════════════════
// STRUCTS
// ═══════════════════════════════════════════════════════

struct NephronSegment {
    name: String,
    abbreviation: String,
    epithelium: String,
    permeability_water: String,
    permeability_nacl: String,
    primary_function: String,
    key_transporters: String,
    fraction_na_reabsorbed: Float,
    citation: String,
}

struct RenalTransporter {
    name: String,
    gene: String,
    accession: String,
    segment: String,
    membrane: String,
    ions_moved: String,
    stoichiometry: String,
    energy_source: String,
    inhibitor: String,
    clinical_relevance: String,
    citation: String,
}

struct GlomerularParameter {
    name: String,
    normal_value: Float,
    unit: String,
    direction: String,
    description: String,
    citation: String,
}

struct RAASComponent {
    step_number: Int,
    name: String,
    gene: String,
    accession: String,
    source: String,
    action: String,
    clinical_target: String,
    citation: String,
}

struct Diuretic {
    name: String,
    drug_class: String,
    target_segment: String,
    target_transporter: String,
    mechanism: String,
    side_effects: String,
    clinical_use: String,
    citation: String,
}

struct CKDStage {
    stage_label: String,
    gfr_low: Float,
    gfr_high: Float,
    description: String,
    action: String,
    citation: String,
}

struct AcidBaseProcess {
    name: String,
    segment: String,
    enzyme_or_transporter: String,
    accession: String,
    mechanism: String,
    net_effect: String,
    citation: String,
}

struct ClinicalSyndrome {
    name: String,
    category: String,
    pathophysiology: String,
    key_findings: String,
    proteinuria: String,
    complement: String,
    examples: String,
    citation: String,
}

struct HormonalRegulator {
    name: String,
    source: String,
    trigger: String,
    receptor: String,
    receptor_accession: String,
    renal_effect: String,
    net_result: String,
    citation: String,
}

// ═══════════════════════════════════════════════════════
// HELPER CONSTRUCTORS
// ═══════════════════════════════════════════════════════

fn nseg(n: String, ab: String, ep: String, pw: String, pn: String, pf: String, kt: String, fr: Float, ci: String) -> NephronSegment {
    return NephronSegment { name: n, abbreviation: ab, epithelium: ep, permeability_water: pw, permeability_nacl: pn, primary_function: pf, key_transporters: kt, fraction_na_reabsorbed: fr, citation: ci }
}

fn rtrans(n: String, g: String, ac: String, seg: String, mem: String, im: String, st: String, es: String, inh: String, cr: String, ci: String) -> RenalTransporter {
    return RenalTransporter { name: n, gene: g, accession: ac, segment: seg, membrane: mem, ions_moved: im, stoichiometry: st, energy_source: es, inhibitor: inh, clinical_relevance: cr, citation: ci }
}

fn gparam(n: String, nv: Float, u: String, d: String, de: String, ci: String) -> GlomerularParameter {
    return GlomerularParameter { name: n, normal_value: nv, unit: u, direction: d, description: de, citation: ci }
}

fn raas(sn: Int, n: String, g: String, ac: String, so: String, act: String, ct: String, ci: String) -> RAASComponent {
    return RAASComponent { step_number: sn, name: n, gene: g, accession: ac, source: so, action: act, clinical_target: ct, citation: ci }
}

fn diur(n: String, dc: String, ts: String, tt: String, mech: String, se: String, cu: String, ci: String) -> Diuretic {
    return Diuretic { name: n, drug_class: dc, target_segment: ts, target_transporter: tt, mechanism: mech, side_effects: se, clinical_use: cu, citation: ci }
}

fn ckd(sl: String, gl: Float, gh: Float, de: String, ac: String, ci: String) -> CKDStage {
    return CKDStage { stage_label: sl, gfr_low: gl, gfr_high: gh, description: de, action: ac, citation: ci }
}

fn abproc(n: String, seg: String, et: String, ac: String, mech: String, ne: String, ci: String) -> AcidBaseProcess {
    return AcidBaseProcess { name: n, segment: seg, enzyme_or_transporter: et, accession: ac, mechanism: mech, net_effect: ne, citation: ci }
}

fn csyn(n: String, cat: String, pp: String, kf: String, pr: String, co: String, ex: String, ci: String) -> ClinicalSyndrome {
    return ClinicalSyndrome { name: n, category: cat, pathophysiology: pp, key_findings: kf, proteinuria: pr, complement: co, examples: ex, citation: ci }
}

fn hreg(n: String, so: String, tr: String, re: String, ra: String, eff: String, nr: String, ci: String) -> HormonalRegulator {
    return HormonalRegulator { name: n, source: so, trigger: tr, receptor: re, receptor_accession: ra, renal_effect: eff, net_result: nr, citation: ci }
}

// ═══════════════════════════════════════════════════════
// NEPHRON ANATOMY -- segment by segment
// ═══════════════════════════════════════════════════════
// Each human kidney contains ~1 million nephrons. Two types:
// Cortical (~85%) -- short loops, peritubular capillaries
// Juxtamedullary (~15%) -- long loops into inner medulla, vasa recta
//
// Cited: Guyton 14th ed, Ch 27; Boron 3rd ed, Ch 33

fn lookup_nephron_segment(seg: String) -> NephronSegment {
    if seg == "glomerulus" { return nseg("Glomerulus", "GLOM", "Fenestrated endothelium (60-80 nm pores)", "freely filtered", "freely filtered", "Ultrafiltration of plasma. Produces ~180 L/day of filtrate. Size/charge barrier: passes molecules <7 kDa freely, blocks albumin (69 kDa) and larger. Negatively charged heparan sulfate proteoglycans repel anionic proteins.", "None (passive pressure-driven sieve)", 0.0, "Guyton 14th ed, Ch 27; Boron 3rd ed, Ch 33") }

    if seg == "bowmans_capsule" { return nseg("Bowman capsule", "BC", "Parietal: simple squamous. Visceral: podocytes with foot processes and slit diaphragms (40 nm). Nephrin (NPHS1, O60500) bridges slit diaphragms.", "freely permeable (continuous with filtrate)", "freely permeable", "Collects glomerular filtrate. Podocyte slit diaphragms are the final size-selective barrier. Loss of nephrin causes massive proteinuria (congenital nephrotic syndrome, Finnish type).", "Nephrin (slit diaphragm)", 0.0, "Boron 3rd ed, Ch 33; Kestila M et al. Mol Cell 1:575-582, 1998") }

    if seg == "pct" { return nseg("Proximal convoluted tubule", "PCT", "Simple cuboidal with prominent brush border (microvilli). Mitochondria-rich for active transport. Leaky tight junctions allow paracellular transport.", "high (obligatory water reabsorption via AQP1)", "high (paracellular and transcellular)", "Bulk reabsorption: 65% Na+, 65% water, 100% glucose (SGLT2/SGLT1), 100% amino acids, 80-90% HCO3- (via carbonic anhydrase), 65% K+, most phosphate (NaPi-IIa) and urea. Also secretes organic anions (PAH) and cations (creatinine). Isosmotic reabsorption -- fluid leaves at 300 mOsm/kg.", "Na+/K+ ATPase (BL), SGLT2 (AP), NHE3 (AP), NaPi-IIa (AP), AQP1 (AP+BL)", 0.65, "Guyton 14th ed, Ch 28; Boron 3rd ed, Ch 35") }

    if seg == "thin_descending" { return nseg("Thin descending limb of Henle", "tDLH", "Simple squamous. No brush border. Few mitochondria. Highly permeable to water (AQP1).", "very high (AQP1)", "low", "Water reabsorption driven by medullary hypertonicity. Tubular fluid becomes progressively concentrated (up to 1200 mOsm/kg at hairpin turn in inner medulla). No active NaCl transport in this segment.", "AQP1 (water only)", 0.0, "Boron 3rd ed, Ch 38") }

    if seg == "thin_ascending" { return nseg("Thin ascending limb of Henle", "tALH", "Simple squamous. Water-impermeable. Passively permeable to NaCl.", "impermeable (no aquaporins)", "moderate (passive NaCl exit)", "Passive NaCl reabsorption down concentration gradient (tubular fluid is hyperosmolar from descending limb concentration). Contributes to countercurrent multiplication by diluting tubular fluid as it ascends. Part of the inner medullary recycling mechanism.", "Passive NaCl leak (ClC-Ka chloride channels)", 0.0, "Boron 3rd ed, Ch 38") }

    if seg == "thick_ascending" { return nseg("Thick ascending limb of Henle", "TAL", "Simple cuboidal. Mitochondria-rich. Tight tight junctions (water-impermeable). Also called diluting segment.", "impermeable (no aquaporins)", "high (active NaCl transport via NKCC2)", "Active NaCl reabsorption via NKCC2 (apical) WITHOUT water -- the diluting segment. Generates medullary hypertonicity for countercurrent multiplication. Reabsorbs 25% of filtered Na+. Also reabsorbs K+, Ca2+, Mg2+ paracellularly (driven by lumen-positive potential from ROMK K+ recycling). Macula densa at end senses NaCl for tubuloglomerular feedback.", "NKCC2 (AP), ROMK (AP), Na+/K+ ATPase (BL), ClC-Kb (BL)", 0.25, "Guyton 14th ed, Ch 28; Mount DB. Clin J Am Soc Nephrol 9:1974-1986, 2014") }

    if seg == "dct" { return nseg("Distal convoluted tubule", "DCT", "Simple cuboidal. Mitochondria-rich. Tight junctions (water-impermeable without ADH).", "low (variable with ADH)", "moderate (NCC-mediated)", "Fine-tuning of NaCl reabsorption via NCC (thiazide-sensitive). Reabsorbs 5% of filtered Na+. Ca2+ reabsorption via TRPV5 (apical entry) stimulated by PTH. Mg2+ reabsorption via TRPM6. Site of thiazide diuretic action.", "NCC (AP), TRPV5 (AP), Na+/K+ ATPase (BL), NCX1 (BL), TRPM6 (AP)", 0.05, "Guyton 14th ed, Ch 28; Boron 3rd ed, Ch 35") }

    if seg == "collecting_duct" { return nseg("Collecting duct", "CD", "Principal cells: pale, few mitochondria, ENaC + AQP2. Intercalated cells: mitochondria-rich, H+/HCO3- transport (type A secrete H+, type B secrete HCO3-).", "variable (ADH-regulated AQP2 insertion)", "low (ENaC-mediated, aldosterone-sensitive)", "Final regulation of Na+, K+, water, and acid-base. Principal cells reabsorb Na+ via ENaC (aldosterone-sensitive) and secrete K+ via ROMK. ADH inserts AQP2 into apical membrane for water reabsorption (concentrates urine). Intercalated cells handle H+ secretion (type A) and HCO3- secretion (type B). Reabsorbs 1-3% of filtered Na+. Urea recycling via UT-A transporters in inner medullary CD.", "ENaC (AP), AQP2 (AP), AQP3/4 (BL), ROMK (AP), H+-ATPase (AP, intercalated A), pendrin (AP, intercalated B)", 0.03, "Guyton 14th ed, Ch 28-29; Boron 3rd ed, Ch 35-38") }

    return nseg("", "", "", "", "", "", "", 0.0, "")
}

// ═══════════════════════════════════════════════════════
// GLOMERULAR FILTRATION
// ═══════════════════════════════════════════════════════
// GFR = Kf * (PGC - PBS - piGC + piBS)
// Kf = filtration coefficient (~12.5 mL/min/mmHg for both kidneys)
// PGC = glomerular capillary hydrostatic pressure (~60 mmHg)
// PBS = Bowman space hydrostatic pressure (~18 mmHg)
// piGC = glomerular capillary oncotic pressure (~32 mmHg)
// piBS = Bowman space oncotic pressure (~0 mmHg, filtrate is protein-free)
// Net filtration pressure = 60 - 18 - 32 + 0 = ~10 mmHg
// GFR = 12.5 * 10 = ~125 mL/min = 180 L/day
//
// Cited: Guyton 14th ed, Ch 27

fn lookup_starling_force(force: String) -> GlomerularParameter {
    if force == "pgc" { return gparam("Glomerular capillary hydrostatic pressure (PGC)", 60.0, "mmHg", "favors filtration", "Drives fluid out of capillary into Bowman space. Set by afferent/efferent arteriolar tone. Higher than systemic capillaries due to efferent arteriolar resistance.", "Guyton 14th ed, Ch 27") }
    if force == "pbs" { return gparam("Bowman space hydrostatic pressure (PBS)", 18.0, "mmHg", "opposes filtration", "Back-pressure from fluid already in Bowman space. Increases in urinary obstruction (hydronephrosis), reducing GFR.", "Guyton 14th ed, Ch 27") }
    if force == "pi_gc" { return gparam("Glomerular capillary oncotic pressure (piGC)", 32.0, "mmHg", "opposes filtration", "Osmotic pull from plasma proteins (primarily albumin). Rises along capillary length as protein-free filtrate leaves (filtration equilibrium). Average ~32 mmHg.", "Guyton 14th ed, Ch 27") }
    if force == "pi_bs" { return gparam("Bowman space oncotic pressure (piBS)", 0.0, "mmHg", "favors filtration", "Negligible in health because filtration barrier excludes proteins. Elevated in nephrotic syndrome (proteinuria).", "Guyton 14th ed, Ch 27") }
    if force == "net" { return gparam("Net filtration pressure", 10.0, "mmHg", "favors filtration", "PGC - PBS - piGC + piBS = 60 - 18 - 32 + 0 = 10 mmHg. This net pressure drives ~125 mL/min through the filtration barrier.", "Guyton 14th ed, Ch 27") }
    if force == "kf" { return gparam("Filtration coefficient (Kf)", 12.5, "mL/min/mmHg", "N/A", "Product of capillary permeability and surface area. Much higher than systemic capillaries. Reduced in glomerulonephritis (loss of filtration area) and diabetic nephropathy (thickened basement membrane).", "Guyton 14th ed, Ch 27") }
    if force == "gfr" { return gparam("Glomerular filtration rate (GFR)", 125.0, "mL/min", "N/A", "Total volume filtered per minute by both kidneys. 180 L/day. 99% reabsorbed. Only ~1.5 L/day excreted as urine. Measured by inulin clearance (gold standard) or estimated by CKD-EPI equation.", "Guyton 14th ed, Ch 27") }
    if force == "rpf" { return gparam("Renal plasma flow (RPF)", 625.0, "mL/min", "N/A", "Plasma flow to both kidneys. Measured by PAH clearance. Renal blood flow ~1.1 L/min (20-25% of cardiac output). Filtration fraction = GFR/RPF = 125/625 = 0.20 (20%).", "Guyton 14th ed, Ch 27") }
    if force == "ff" { return gparam("Filtration fraction", 0.20, "dimensionless", "N/A", "GFR/RPF = 125/625 = 0.20. Twenty percent of plasma entering the glomerulus is filtered. Increased by efferent arteriolar constriction (angiotensin II). Decreased by afferent constriction.", "Guyton 14th ed, Ch 27") }
    return gparam("", 0.0, "", "", "", "")
}

fn filtration_barrier_layers() -> String {
    // Three layers of the glomerular filtration barrier:
    // Layer A: Fenestrated endothelium (pores 60-80 nm, size barrier)
    // Layer B: Glomerular basement membrane (GBM, type IV collagen + laminin + heparan sulfate proteoglycans, charge + size barrier)
    // Layer C: Podocyte foot processes with slit diaphragms (nephrin, 40 nm slits, final size barrier)
    return "Fenestrated endothelium (60-80 nm pores) -> GBM (type IV collagen, laminin, heparan sulfate; charge barrier) -> Podocyte slit diaphragms (nephrin O60500, 40 nm; final size gate). Freely passes water, electrolytes, glucose, urea, small molecules (<7 kDa). Blocks albumin (69 kDa, also repelled by negative charge), immunoglobulins, cells."
}

// ═══════════════════════════════════════════════════════
// KEY RENAL TRANSPORTERS -- with UniProt accessions
// ═══════════════════════════════════════════════════════
// AP = apical (luminal). BL = basolateral (blood side).
// Cited: Boron 3rd ed, Ch 35-36; Guyton 14th ed, Ch 28

fn lookup_transporter(name: String) -> RenalTransporter {
    if name == "na_k_atpase" { return rtrans("Na+/K+ ATPase (alpha-1 subunit)", "ATP1A1", "P05023", "All segments (basolateral)", "basolateral", "3 Na+ out, 2 K+ in", "3Na+out : 2K+in : 1ATP", "ATP hydrolysis (primary active)", "Cardiac glycosides (digoxin, ouabain)", "THE driving force. Creates low intracellular Na+ (~12 mM vs 140 mM extracellular) that powers all secondary active transporters. Electrogenic (net positive charge outward). Nobel Prize: Skou JC, 1997.", "Guyton 14th ed, Ch 28; Skou JC. Biochim Biophys Acta 23:394-401, 1957") }

    if name == "sglt2" { return rtrans("SGLT2 (Na+/glucose cotransporter 2)", "SLC5A2", "P31639", "PCT (S1 and S2 segments)", "apical", "1 Na+ + 1 glucose IN", "1Na+ : 1glucose (low affinity, high capacity)", "Na+ gradient (secondary active)", "SGLT2 inhibitors: empagliflozin, dapagliflozin, canagliflozin", "Reabsorbs ~90% of filtered glucose (~160 g/day). Transport maximum (Tm) ~375 mg/min. Above Tm -> glucosuria. SGLT2 inhibitors are first-line for type 2 diabetes AND heart failure AND CKD (DAPA-CKD, EMPA-KIDNEY trials). Mutations cause familial renal glucosuria (benign).", "Boron 3rd ed, Ch 35; Wright EM et al. Physiol Rev 91:733-794, 2011") }

    if name == "sglt1" { return rtrans("SGLT1 (Na+/glucose cotransporter 1)", "SLC5A1", "P13866", "PCT (S3 segment) and intestine", "apical", "2 Na+ + 1 glucose IN", "2Na+ : 1glucose (high affinity, low capacity)", "Na+ gradient (secondary active)", "None clinically used", "Mops up remaining ~10% of filtered glucose. Also expressed in intestinal brush border for dietary glucose absorption. Higher affinity than SGLT2 but lower capacity.", "Boron 3rd ed, Ch 35") }

    if name == "nhe3" { return rtrans("NHE3 (Na+/H+ exchanger 3)", "SLC9A3", "P48764", "PCT and TAL", "apical", "1 Na+ in, 1 H+ out", "1Na+in : 1H+out", "Na+ gradient (secondary active)", "Amiloride (weak, non-specific)", "Major mechanism of Na+ and HCO3- reabsorption in PCT. H+ secreted into lumen combines with filtered HCO3- -> H2CO3 -> CO2 + H2O (catalyzed by brush border carbonic anhydrase IV). CO2 diffuses into cell, recombines with H2O -> HCO3- (carbonic anhydrase II) -> exits basolateral via NBCe1.", "Guyton 14th ed, Ch 28; Boron 3rd ed, Ch 35") }

    if name == "nkcc2" { return rtrans("NKCC2 (Na+-K+-2Cl- cotransporter)", "SLC12A1", "Q13621", "Thick ascending limb (TAL)", "apical", "1 Na+ + 1 K+ + 2 Cl- IN", "1Na+ : 1K+ : 2Cl-", "Na+ gradient (secondary active)", "Loop diuretics: furosemide, bumetanide, torsemide, ethacrynic acid", "THE target of loop diuretics. Drives countercurrent multiplication by reabsorbing NaCl without water. Generates lumen-positive potential (ROMK recycles K+ to lumen) that drives paracellular Ca2+ and Mg2+ reabsorption. Mutations cause Bartter syndrome type I (salt-wasting, hypokalemic metabolic alkalosis).", "Mount DB. Clin J Am Soc Nephrol 9:1974-1986, 2014; Guyton 14th ed, Ch 28") }

    if name == "romk" { return rtrans("ROMK (renal outer medullary K+ channel)", "KCNJ1", "P48048", "TAL (apical) and CD (apical)", "apical", "K+ out (recycling in TAL; secretion in CD)", "K+ efflux", "K+ gradient (passive)", "None directly; indirectly affected by loop diuretics", "In TAL: recycles K+ back to lumen to sustain NKCC2 activity and generate lumen-positive voltage. In CD: mediates K+ secretion (aldosterone-stimulated). Mutations cause Bartter syndrome type II.", "Boron 3rd ed, Ch 35") }

    if name == "ncc" { return rtrans("NCC (Na+-Cl- cotransporter)", "SLC12A3", "P55017", "Distal convoluted tubule (DCT)", "apical", "1 Na+ + 1 Cl- IN", "1Na+ : 1Cl-", "Na+ gradient (secondary active)", "Thiazide diuretics: hydrochlorothiazide, chlorthalidone, metolazone", "Reabsorbs ~5% of filtered NaCl. Thiazide target. Mutations cause Gitelman syndrome (hypokalemic metabolic alkalosis with hypocalciuria and hypomagnesemia -- opposite of Bartter). WNK kinases regulate NCC phosphorylation -- WNK4 mutations cause Gordon syndrome (pseudohypoaldosteronism type II, hypertension with hyperkalemia).", "Guyton 14th ed, Ch 28; Boron 3rd ed, Ch 35") }

    if name == "enac" { return rtrans("ENaC (epithelial Na+ channel)", "SCNN1A/B/G", "P37088 (alpha), P51168 (beta), P51170 (gamma)", "Collecting duct (principal cells)", "apical", "Na+ IN (electrogenic)", "Na+ influx (creates lumen-negative potential)", "Na+ gradient (passive, down electrochemical gradient)", "K+-sparing diuretics: amiloride, triamterene. Indirectly by aldosterone antagonists (spironolactone, eplerenone)", "Final Na+ reabsorption. Aldosterone increases ENaC expression and open probability (via SGK1 phosphorylation). Lumen-negative potential drives K+ secretion via ROMK and H+ secretion. Gain-of-function: Liddle syndrome (severe hypertension). Loss-of-function: pseudohypoaldosteronism type I.", "Guyton 14th ed, Ch 28-29; Boron 3rd ed, Ch 35") }

    if name == "aqp1" { return rtrans("Aquaporin-1 (AQP1)", "AQP1", "P29972", "PCT and thin descending limb", "apical and basolateral", "H2O only (bidirectional)", "Single-file water transport, ~3 billion molecules/sec/tetramer", "Osmotic gradient (passive)", "Mercury (Hg2+) blocks AQP1 (historical)", "Constitutively expressed. Not regulated by ADH. Mediates obligatory water reabsorption in PCT (~65% of filtered water) and concentration of tubular fluid in thin descending limb. Knockout mice have defective urine concentration. Nobel Prize: Peter Agre, 2003.", "Boron 3rd ed, Ch 35; Agre P. Angew Chem Int Ed 43:4278-4290, 2004") }

    if name == "aqp2" { return rtrans("Aquaporin-2 (AQP2)", "AQP2", "P41181", "Collecting duct (principal cells)", "apical (regulated insertion)", "H2O only", "ADH-regulated insertion into apical membrane", "Osmotic gradient (passive, after membrane insertion)", "V2 receptor antagonists (tolvaptan, conivaptan)", "THE ADH-regulated water channel. Stored in intracellular vesicles. ADH binds V2 receptor (BL) -> cAMP -> PKA -> AQP2 phosphorylation -> vesicle fusion with apical membrane -> water reabsorption. Without ADH: AQP2 internalized, dilute urine. Mutations cause nephrogenic diabetes insipidus (autosomal recessive). Lithium downregulates AQP2 (iatrogenic NDI).", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 38") }

    if name == "aqp3" { return rtrans("Aquaporin-3 (AQP3)", "AQP3", "Q92482", "Collecting duct (principal cells)", "basolateral", "H2O and glycerol", "Constitutive basolateral water exit", "Osmotic gradient (passive)", "None clinically used", "Constitutively expressed on basolateral membrane of principal cells. Provides exit route for water that enters apically via AQP2. Also transports glycerol (aquaglyceroporin).", "Boron 3rd ed, Ch 38") }

    if name == "trpv5" { return rtrans("TRPV5 (Ca2+ entry channel)", "TRPV5", "Q9NQA5", "DCT", "apical", "Ca2+ IN", "Ca2+ influx (highly selective)", "Electrochemical gradient (passive)", "Ruthenium red (experimental)", "Apical Ca2+ entry step in transcellular Ca2+ reabsorption. PTH and calcitriol increase expression. Ca2+ then bound by calbindin-D28K intracellularly and exits basolaterally via NCX1 (Na+/Ca2+ exchanger) and PMCA1b (Ca2+-ATPase). This is why thiazides cause hypocalciuria -- enhanced proximal reabsorption.", "Boron 3rd ed, Ch 36") }

    if name == "napi_iia" { return rtrans("NaPi-IIa (Na+/phosphate cotransporter)", "SLC34A1", "Q06495", "PCT", "apical", "3 Na+ + 1 HPO4(2-) IN", "3Na+ : 1HPO4(2-)", "Na+ gradient (secondary active)", "None directly; PTH causes internalization", "Primary phosphate reabsorption (~80% of filtered Pi). PTH stimulates endocytosis and degradation of NaPi-IIa, causing phosphaturia. FGF23 (from bone osteocytes, P39905) also downregulates NaPi-IIa. Mutations cause Fanconi syndrome.", "Boron 3rd ed, Ch 36") }

    if name == "nbce1" { return rtrans("NBCe1 (electrogenic Na+/HCO3- cotransporter)", "SLC4A4", "Q9Y6R1", "PCT", "basolateral", "1 Na+ + 3 HCO3- OUT to blood", "1Na+ : 3HCO3- (electrogenic)", "HCO3- gradient", "None clinically used", "Basolateral exit of reabsorbed HCO3- in PCT. The final step in HCO3- reabsorption: luminal HCO3- -> CO2 (CA-IV) -> cell CO2 -> HCO3- (CA-II) -> exits BL via NBCe1. Mutations cause proximal renal tubular acidosis (type II RTA).", "Boron 3rd ed, Ch 35") }

    if name == "ut_a1" { return rtrans("UT-A1 (urea transporter A1)", "SLC14A2", "Q15849", "Inner medullary collecting duct", "apical", "Urea (bidirectional)", "Facilitated diffusion", "Concentration gradient (passive); ADH-regulated", "None clinically used", "ADH increases UT-A1 via cAMP/PKA. Allows urea recycling from inner medullary CD into medullary interstitium, contributing ~50% of inner medullary osmolality. Essential for maximal urine concentration.", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 38") }

    return rtrans("", "", "", "", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// RAAS -- Renin-Angiotensin-Aldosterone System
// ═══════════════════════════════════════════════════════
// The master volume/pressure control loop. Activated by low renal
// perfusion, low NaCl delivery to macula densa, or sympathetic
// stimulation. Net effect: Na+ retention, water retention, K+
// excretion, vasoconstriction, blood pressure increase.
//
// Cited: Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 40

fn lookup_raas(step: Int) -> RAASComponent {
    if step == 1 { return raas(1, "Renin", "REN", "P00797", "Juxtaglomerular (JG) granular cells of afferent arteriole", "Cleaves angiotensinogen to angiotensin I (decapeptide). Released in response to: (A) decreased renal perfusion pressure (baroreceptor), (B) decreased NaCl delivery to macula densa (tubuloglomerular feedback via NKCC2 sensing), (C) sympathetic stimulation (beta-1 receptors on JG cells). Rate-limiting step of RAAS.", "Direct renin inhibitors: aliskiren", "Guyton 14th ed, Ch 29") }

    if step == 2 { return raas(2, "Angiotensinogen", "AGT", "P01019", "Liver (constitutive secretion into plasma)", "Substrate for renin. 452-amino-acid alpha-2-globulin. Always present in plasma. Not rate-limiting. Production increased by estrogen, glucocorticoids, thyroid hormone, angiotensin II (positive feedback).", "Not a direct drug target", "Guyton 14th ed, Ch 29") }

    if step == 3 { return raas(3, "Angiotensin I", "N/A (decapeptide)", "N/A", "Formed in plasma from angiotensinogen by renin", "Biologically inactive decapeptide (Asp-Arg-Val-Tyr-Ile-His-Pro-Phe-His-Leu). Merely a precursor. Must be cleaved by ACE to become active angiotensin II.", "N/A", "Guyton 14th ed, Ch 29") }

    if step == 4 { return raas(4, "Angiotensin-converting enzyme (ACE)", "ACE", "P12821", "Pulmonary endothelium (highest concentration), also renal endothelium and other vascular beds", "Cleaves angiotensin I (decapeptide) to angiotensin II (octapeptide) by removing C-terminal His-Leu. Also degrades bradykinin (a vasodilator) -- this is why ACE inhibitors cause cough (bradykinin accumulation in lungs). Zinc metallopeptidase.", "ACE inhibitors: enalapril, lisinopril, ramipril, captopril. First-line for HTN, HF, diabetic nephropathy, post-MI. Cough in ~10% (bradykinin). Angioedema rare but dangerous.", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 40") }

    if step == 5 { return raas(5, "Angiotensin II", "N/A (octapeptide)", "N/A", "Formed from angiotensin I by ACE", "THE effector. Acts on AT1 receptors (P30556). Effects: (A) potent vasoconstriction (especially efferent arteriole, increasing filtration fraction and peritubular oncotic pressure for Na+ reabsorption), (B) stimulates aldosterone secretion from adrenal zona glomerulosa, (C) stimulates ADH release from posterior pituitary, (D) stimulates thirst (subfornical organ), (E) stimulates Na+ reabsorption in PCT (NHE3 upregulation), (F) promotes cardiac and vascular remodeling (fibrosis). Half-life ~1 min.", "AT1 receptor blockers (ARBs): losartan, valsartan, candesartan, irbesartan. Same indications as ACE inhibitors but no cough.", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 40") }

    if step == 6 { return raas(6, "Aldosterone", "CYP11B2 (synthase)", "P19099", "Adrenal cortex zona glomerulosa (stimulated by angiotensin II and hyperkalemia)", "Mineralocorticoid. Binds intracellular mineralocorticoid receptor (MR, P08235) in collecting duct principal cells. MR-aldosterone complex translocates to nucleus, upregulates: (A) ENaC (apical Na+ reabsorption), (B) ROMK (K+ secretion), (C) Na+/K+ ATPase (basolateral), (D) SGK1 kinase (prevents ENaC degradation). Net effect: Na+ retention, K+ excretion, H+ excretion. Takes 1-3 hours for genomic effects.", "Aldosterone antagonists: spironolactone, eplerenone. Block MR. K+-sparing. Used in HF (RALES trial: 30% mortality reduction), resistant HTN, primary hyperaldosteronism (Conn syndrome).", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 35") }

    return raas(0, "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// HORMONAL REGULATION -- ADH, ANP/BNP, PTH
// ═══════════════════════════════════════════════════════
// Cited: Guyton 14th ed, Ch 29-30; Boron 3rd ed, Ch 38-40

fn lookup_hormonal_regulator(hormone: String) -> HormonalRegulator {
    if hormone == "adh" { return hreg("ADH (vasopressin, AVP)", "Posterior pituitary (synthesized in hypothalamic supraoptic and paraventricular nuclei)", "Increased plasma osmolality (>280 mOsm/kg, sensed by osmoreceptors in anterior hypothalamus) and decreased blood volume/pressure (via baroreceptors in carotid/aortic arch)", "V2 receptor (collecting duct principal cells, basolateral)", "P30518", "V2 receptor -> Gs -> adenylyl cyclase -> cAMP -> PKA -> phosphorylates AQP2 -> AQP2 vesicle insertion into apical membrane -> water reabsorption. Also activates V1a receptors on vascular smooth muscle -> vasoconstriction. Also increases urea permeability in inner medullary CD (UT-A1).", "Water retention, concentrated urine (up to 1200 mOsm/kg). Absence = diabetes insipidus (central if no ADH synthesis, nephrogenic if V2/AQP2 defect). SIADH = excessive ADH -> dilutional hyponatremia.", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 38") }

    if hormone == "anp" { return hreg("ANP (atrial natriuretic peptide)", "Atrial cardiomyocytes (released on atrial stretch from volume expansion)", "Atrial wall stretch (volume overload, increased venous return)", "NPR-A (natriuretic peptide receptor A, guanylyl cyclase)", "P16066", "Increases GFR (afferent arteriolar dilation + efferent constriction). Inhibits Na+ reabsorption in collecting duct (reduces ENaC). Inhibits renin release. Inhibits aldosterone secretion. Inhibits ADH release. Produces cGMP that relaxes vascular smooth muscle.", "Natriuresis, diuresis, vasodilation, decreased blood pressure. The counter-regulatory hormone to RAAS. Physiological brake on volume expansion.", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 40") }

    if hormone == "bnp" { return hreg("BNP (B-type natriuretic peptide)", "Ventricular cardiomyocytes (released on ventricular wall stress)", "Ventricular wall stretch (volume/pressure overload, heart failure)", "NPR-A (same as ANP)", "P16066", "Same effects as ANP: natriuresis, diuresis, vasodilation, RAAS suppression. BNP (or NT-proBNP, the inactive fragment) is a key biomarker for heart failure diagnosis and monitoring. Nesiritide = recombinant BNP (IV for acute HF, largely replaced by other therapies).", "Natriuresis, diuresis, vasodilation. NT-proBNP >300 pg/mL suggests HF. Sacubitril inhibits neprilysin (BNP degradation) -> potentiates BNP -> PARADIGM-HF trial showed 20% mortality reduction when combined with valsartan (Entresto).", "Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 40") }

    if hormone == "pth" { return hreg("PTH (parathyroid hormone)", "Chief cells of parathyroid glands (four glands)", "Low plasma ionized Ca2+ (sensed by CaSR calcium-sensing receptor on parathyroid cells, P41180)", "PTH1R (PTH/PTHrP receptor) on PCT and DCT cells", "Q03431", "In PCT: inhibits NaPi-IIa -> phosphaturia. Stimulates 1-alpha-hydroxylase -> calcitriol synthesis. In TAL: enhances Ca2+ reabsorption (paracellular, via claudin-16). In DCT: increases TRPV5 expression -> transcellular Ca2+ reabsorption. Net: increases plasma Ca2+, decreases plasma phosphate.", "Raise plasma Ca2+, lower plasma phosphate. Hyperparathyroidism -> hypercalcemia, kidney stones, bone resorption. Hypoparathyroidism -> hypocalcemia (tetany, QT prolongation). CKD -> secondary hyperparathyroidism (phosphate retention + low calcitriol -> Ca2+ falls -> PTH rises).", "Guyton 14th ed, Ch 80; Boron 3rd ed, Ch 36") }

    if hormone == "calcitriol" { return hreg("Calcitriol (1,25-dihydroxyvitamin D3)", "PCT cells (final hydroxylation by 1-alpha-hydroxylase, CYP27B1, Q02318)", "PTH stimulates 1-alpha-hydroxylase. Low phosphate also stimulates. FGF23 inhibits.", "VDR (vitamin D receptor, nuclear receptor)", "P11473", "In intestine: increases Ca2+ and phosphate absorption. In kidney: increases Ca2+ reabsorption in DCT (upregulates TRPV5, calbindin). In bone: permits mineralization. Suppresses PTH gene transcription (negative feedback).", "Increases plasma Ca2+ and phosphate. Deficiency -> rickets (children), osteomalacia (adults). Used therapeutically in CKD (calcitriol or active analogs) to suppress secondary hyperparathyroidism.", "Guyton 14th ed, Ch 80; Boron 3rd ed, Ch 36") }

    if hormone == "fgf23" { return hreg("FGF23 (fibroblast growth factor 23)", "Osteocytes (bone)", "Elevated plasma phosphate, elevated calcitriol", "FGFR1c with co-receptor Klotho (required, Q9UEF7 Klotho)", "P22455", "In PCT: inhibits NaPi-IIa and NaPi-IIc -> phosphaturia. Inhibits 1-alpha-hydroxylase -> reduces calcitriol synthesis. Inhibits PTH secretion.", "Phosphaturia, reduced calcitriol. FGF23 excess: tumor-induced osteomalacia, X-linked hypophosphatemia. CKD: FGF23 rises early (compensatory phosphaturia) but eventually fails as nephron mass declines -> hyperphosphatemia.", "Boron 3rd ed, Ch 36; Shimada T et al. J Clin Invest 113:561-568, 2004") }

    return hreg("", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// ACID-BASE HANDLING
// ═══════════════════════════════════════════════════════
// The kidneys handle acid-base by: (A) reabsorbing filtered HCO3-,
// (B) generating new HCO3- (to replace that consumed buffering
// metabolic acid), and (C) excreting H+ as titratable acid and NH4+.
// Net acid excretion = titratable acid + NH4+ - HCO3- excreted
// ~70 mEq/day of net acid excreted (matching endogenous acid production)
//
// Cited: Guyton 14th ed, Ch 31; Boron 3rd ed, Ch 39

fn lookup_acid_base(process: String) -> AcidBaseProcess {
    if process == "hco3_reabsorption" { return abproc("HCO3- reabsorption (PCT, ~80-90%)", "PCT (with minor contribution from TAL and CD)", "Carbonic anhydrase IV (brush border, P22748) and carbonic anhydrase II (cytoplasmic, P00918)", "P22748 (CA-IV), P00918 (CA-II)", "Filtered HCO3- cannot cross apical membrane directly. NHE3 secretes H+ into lumen. H+ + HCO3- -> H2CO3 -> CO2 + H2O (catalyzed by CA-IV on brush border). CO2 freely diffuses into cell. Inside cell: CO2 + H2O -> H2CO3 -> H+ + HCO3- (catalyzed by CA-II). H+ recycled to lumen via NHE3. HCO3- exits basolateral via NBCe1 (Q9Y6R1). NET EFFECT: HCO3- effectively moves from lumen to blood without actually crossing the membrane as HCO3-.", "Reclaims ~4000 mEq/day of filtered HCO3-. This is not new HCO3- generation -- just prevents loss. Acetazolamide (CA inhibitor) blocks this -> bicarbonaturia -> metabolic acidosis (type II proximal RTA).", "Guyton 14th ed, Ch 31; Boron 3rd ed, Ch 39") }

    if process == "h_secretion" { return abproc("H+ secretion (titratable acidity)", "PCT (NHE3), CD type A intercalated cells (H+-ATPase, H+/K+-ATPase)", "H+-ATPase (vacuolar type, apical of intercalated A cells), H+/K+-ATPase (P54707)", "P54707 (H+/K+-ATPase alpha)", "Type A intercalated cells secrete H+ into lumen via H+-ATPase (primary active) and H+/K+-ATPase. Secreted H+ titrates urinary buffers, primarily HPO4(2-) -> H2PO4- (titratable acid). Also titrates creatinine and urate. Each H+ excreted with buffer = one new HCO3- generated and returned to blood via AE1 (Cl-/HCO3- exchanger, basolateral, P02730). Minimum urinary pH = 4.5 (H+-ATPase limit).", "Generates ~10-30 mEq/day new HCO3-. Titratable acid limited by buffer availability (mainly phosphate). Cannot lower urine pH below 4.5.", "Guyton 14th ed, Ch 31; Boron 3rd ed, Ch 39") }

    if process == "ammonium" { return abproc("Ammonium (NH4+) excretion", "PCT (production), TAL (reabsorption), CD (secretion -- NH3 trapping)", "Glutaminase (kidney-type, O94925) and glutamate dehydrogenase (P00367)", "O94925 (glutaminase), P00367 (GDH)", "PCT: Glutaminase cleaves glutamine -> glutamate + NH4+. Glutamate dehydrogenase -> alpha-ketoglutarate + NH4+. Each glutamine yields 2 NH4+ and 2 new HCO3-. NH4+ secreted into lumen (substitutes for H+ on NHE3) or enters lumen as NH3 gas. TAL: NH4+ reabsorbed from lumen (substitutes for K+ on NKCC2) into medullary interstitium. CD: NH3 diffuses from interstitium into acidic CD lumen, picks up H+ -> trapped as NH4+ (non-ionic diffusion trapping). Excreted.", "Major adaptive mechanism for acid excretion. Generates ~30-40 mEq/day new HCO3- at baseline; increases 5-10x in chronic metabolic acidosis (glutaminase upregulation). This is why NH4+ excretion is the kidney's main adaptive response to acid loads.", "Guyton 14th ed, Ch 31; Boron 3rd ed, Ch 39") }

    if process == "type_a_intercalated" { return abproc("Type A intercalated cell (acid secretion)", "Collecting duct", "H+-ATPase (apical), AE1/Band 3 (Cl-/HCO3- exchanger, basolateral, P02730)", "P02730 (AE1/Band 3)", "Apical H+-ATPase pumps H+ into lumen. Intracellular CO2 + H2O -> H+ + HCO3- (CA-II). H+ secreted apically. HCO3- exits basolateral via AE1 (Cl-/HCO3- exchange) -> new HCO3- added to blood. Active in acidosis. Mutations in H+-ATPase cause distal RTA (type I).", "Net acid secretion. Each H+ pumped = one HCO3- returned to blood. Failure -> type I distal RTA (inability to acidify urine below pH 5.5, metabolic acidosis, kidney stones, nephrocalcinosis).", "Boron 3rd ed, Ch 39") }

    if process == "type_b_intercalated" { return abproc("Type B intercalated cell (base secretion)", "Collecting duct", "Pendrin (Cl-/HCO3- exchanger, apical, O43511), H+-ATPase (basolateral)", "O43511 (pendrin/SLC26A4)", "Mirror image of type A. Pendrin secretes HCO3- into lumen (apical Cl-/HCO3- exchange). H+-ATPase on basolateral membrane acidifies blood. Active in metabolic alkalosis (HCO3- excess). Converts from type A to type B (or vice versa) depending on acid-base status -- polarity reversal.", "Net base secretion (HCO3- excretion). Active when body is alkalotic. Rare clinical significance compared to type A.", "Boron 3rd ed, Ch 39") }

    return abproc("", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// COUNTERCURRENT MULTIPLICATION AND CONCENTRATION
// ═══════════════════════════════════════════════════════
// The loop of Henle + vasa recta create and maintain a corticomedullary
// osmotic gradient (300 mOsm/kg cortex -> 1200 mOsm/kg inner medulla)
// that enables urine concentration when ADH is present.
//
// Cited: Guyton 14th ed, Ch 29; Boron 3rd ed, Ch 38

fn medullary_gradient() -> String {
    return "Cortex: 300 mOsm/kg | Outer medulla: 600 mOsm/kg | Inner medulla: 900-1200 mOsm/kg. Created by: (A) TAL active NaCl reabsorption without water (single effect ~200 mOsm gradient at each level), (B) countercurrent flow multiplies single effect along medullary axis, (C) urea recycling from inner medullary CD into interstitium contributes ~50% of inner medullary tonicity, (D) vasa recta countercurrent exchangers preserve gradient without dissipating it."
}

fn urine_osmolality_range() -> String {
    return "Minimum (ADH absent, maximal dilution): ~50 mOsm/kg (hypotonic). Maximum (maximal ADH, maximal concentration): ~1200 mOsm/kg (hypertonic). Isosthenuric (fixed at ~300 mOsm/kg) in CKD (loss of concentrating and diluting ability)."
}

fn free_water_clearance_concept() -> String {
    return "Free water clearance (CH2O) = V - Cosm. Positive CH2O = dilute urine (water diuresis, ADH absent). Negative CH2O = concentrated urine (free water reabsorbed, ADH present). Electrolyte-free water clearance is more clinically useful for dysnatremia management."
}

// ═══════════════════════════════════════════════════════
// DIURETICS BY SITE
// ═══════════════════════════════════════════════════════
// Cited: Guyton 14th ed, Ch 32; Boron 3rd ed, Ch 40;
// Ellison DH. Diuretic drugs and treatment of edema.
// In: Brenner and Rector's The Kidney, 11th ed, 2020.

fn lookup_diuretic(name: String) -> Diuretic {
    if name == "acetazolamide" { return diur("Acetazolamide", "Carbonic anhydrase inhibitor", "PCT", "Carbonic anhydrase II (P00918) and IV (P22748)", "Inhibits CA -> impairs H+ secretion via NHE3 -> HCO3- stays in lumen -> bicarbonaturia -> metabolic acidosis. Na+ accompanies HCO3- -> mild natriuresis. Self-limiting (as metabolic acidosis develops, less HCO3- filtered). Weak diuretic.", "Metabolic acidosis (predictable and desired in some uses), hypokalemia (increased distal Na+ delivery -> K+ secretion), paresthesias, kidney stones (alkaline urine + hypocitraturia).", "Glaucoma (reduces aqueous humor formation), altitude sickness (stimulates ventilation via mild acidosis), pseudotumor cerebri, metabolic alkalosis (rarely). Epilepsy (adjunct).", "Guyton 14th ed, Ch 32") }

    if name == "mannitol" { return diur("Mannitol", "Osmotic diuretic", "PCT and loop of Henle (entire tubule)", "No specific transporter target", "Freely filtered, not reabsorbed. Holds water in tubule osmotically -> reduces water reabsorption in PCT and thin descending limb. Increases medullary blood flow (washes out gradient). Expands intravascular volume before diuresing (can worsen HF).", "Volume expansion (initial, before diuresis), hyponatremia (dilutional), dehydration, hyperkalemia.", "Cerebral edema (osmotic shrinkage of brain), acute glaucoma, rhabdomyolysis (maintain urine output), prevent AKI during surgery. IV only.", "Guyton 14th ed, Ch 32") }

    if name == "furosemide" { return diur("Furosemide (Lasix)", "Loop diuretic", "Thick ascending limb (TAL)", "NKCC2 (SLC12A1, Q13621)", "Binds Cl- site on NKCC2 from luminal side (must reach tubular fluid via secretion in PCT). Blocks Na+-K+-2Cl- reabsorption. Abolishes lumen-positive potential -> reduces paracellular Ca2+ and Mg2+ reabsorption. Destroys medullary gradient -> impairs concentrating ability. Most powerful diuretics -- can excrete up to 25% of filtered Na+.", "Hypokalemia (massive distal Na+ delivery -> K+ secretion), metabolic alkalosis (volume contraction + K+ depletion), hypocalcemia, hypomagnesemia, ototoxicity (especially with aminoglycosides), hyperuricemia.", "Acute pulmonary edema, HF (decompensated), nephrotic syndrome, cirrhotic ascites, hypercalcemia (with saline), acute kidney injury (controversial). IV onset ~5 min, PO onset ~30 min, duration ~6 hr.", "Guyton 14th ed, Ch 32; Brenner 11th ed") }

    if name == "bumetanide" { return diur("Bumetanide (Bumex)", "Loop diuretic", "Thick ascending limb (TAL)", "NKCC2 (SLC12A1, Q13621)", "Same mechanism as furosemide. 40x more potent by weight (1 mg bumetanide ~ 40 mg furosemide). Better oral bioavailability (~80% vs ~50% for furosemide). Same class effects.", "Same as furosemide: hypokalemia, metabolic alkalosis, hypocalcemia, hypomagnesemia, ototoxicity.", "Same indications as furosemide. Preferred when consistent bioavailability needed (e.g., outpatient HF).", "Brenner 11th ed") }

    if name == "hctz" { return diur("Hydrochlorothiazide (HCTZ)", "Thiazide diuretic", "Distal convoluted tubule (DCT)", "NCC (SLC12A3, P55017)", "Blocks Na+-Cl- cotransporter from luminal side. Moderate diuretic (only 5% of Na+ reabsorbed at DCT). But: causes HYPOCALCIURIA (enhanced proximal Ca2+ reabsorption due to mild volume depletion + direct effect on DCT Ca2+ transport). Unique among diuretics for calcium-sparing.", "Hypokalemia, metabolic alkalosis, hyponatremia (especially elderly women -- impaired free water excretion), hyperuricemia, hyperglycemia (impaired insulin secretion), hypercalcemia (mild).", "First-line for essential hypertension (ALLHAT trial). Calcium oxalate kidney stones (reduces urinary Ca2+). Nephrogenic DI (paradoxical -- mild volume depletion enhances proximal reabsorption, less water reaches CD). Edema.", "Guyton 14th ed, Ch 32; Brenner 11th ed") }

    if name == "chlorthalidone" { return diur("Chlorthalidone", "Thiazide-like diuretic", "Distal convoluted tubule (DCT)", "NCC (SLC12A3, P55017)", "Same mechanism as HCTZ but longer half-life (45-60 hr vs 6-12 hr for HCTZ). More potent 24-hour natriuresis. Accumulates in RBCs (slow release). Preferred thiazide for hypertension in most guidelines.", "Same as HCTZ but potentially more hypokalemia and hyponatremia due to longer action.", "Preferred thiazide for hypertension (SPRINT trial used chlorthalidone). Same other indications as HCTZ.", "Brenner 11th ed") }

    if name == "spironolactone" { return diur("Spironolactone", "Aldosterone antagonist (K+-sparing)", "Collecting duct (principal cells)", "Mineralocorticoid receptor (MR, NR3C2, P08235) -- blocks aldosterone binding", "Competitive antagonist at intracellular MR. Prevents aldosterone-induced upregulation of ENaC, ROMK, and Na+/K+ ATPase. Reduces Na+ reabsorption, reduces K+ secretion. Onset delayed 2-3 days (blocks genomic effects). Also has antiandrogenic and progestational activity (non-selective).", "Hyperkalemia (especially with ACE inhibitors or renal impairment -- MONITOR K+), gynecomastia and breast tenderness (antiandrogenic), menstrual irregularities.", "Heart failure (RALES trial: 30% mortality reduction), primary hyperaldosteronism (Conn syndrome), cirrhotic ascites (first-line with furosemide), resistant hypertension, hirsutism/acne in women. Weak diuretic alone.", "Guyton 14th ed, Ch 32; Pitt B et al. N Engl J Med 341:709-717, 1999 (RALES)") }

    if name == "eplerenone" { return diur("Eplerenone", "Aldosterone antagonist (K+-sparing)", "Collecting duct", "Mineralocorticoid receptor (MR, NR3C2, P08235)", "Same mechanism as spironolactone but selective for MR (no antiandrogenic activity). 60% potency of spironolactone. Fewer endocrine side effects.", "Hyperkalemia. No gynecomastia (MR-selective).", "Post-MI heart failure (EPHESUS trial). HFrEF. Preferred over spironolactone when gynecomastia is problematic.", "Zannad F et al. N Engl J Med 364:11-21, 2011 (EMPHASIS-HF)") }

    if name == "amiloride" { return diur("Amiloride", "ENaC blocker (K+-sparing)", "Collecting duct (principal cells)", "ENaC (SCNN1A/B/G, P37088/P51168/P51170)", "Directly blocks ENaC pore from luminal side. Blocks Na+ entry independent of aldosterone. Reduces lumen-negative potential -> decreases K+ and H+ secretion. Weak diuretic alone (~2% of filtered Na+).", "Hyperkalemia (especially with K+ supplements or ACE inhibitors). Metabolic acidosis (reduced H+ secretion).", "Combined with thiazides to prevent K+ loss (e.g., amiloride/HCTZ combo). Lithium-induced nephrogenic DI (amiloride blocks Li+ entry via ENaC, reducing Li+ toxicity to principal cells). Liddle syndrome (off-label).", "Guyton 14th ed, Ch 32; Brenner 11th ed") }

    return diur("", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// CKD STAGING -- KDIGO 2012 / CKD-EPI
// ═══════════════════════════════════════════════════════
// GFR estimated by CKD-EPI (2021 creatinine equation, race-free):
// eGFR = 142 * min(Scr/k, 1)^alpha * max(Scr/k, 1)^(-1.200) * 0.9938^age
//   * 1.012 [if female]
//   where k = 0.7 (female), 0.9 (male)
//   alpha = -0.241 (female), -0.302 (male)
//
// Cited: KDIGO 2012 Clinical Practice Guideline for CKD;
// Inker LA et al. N Engl J Med 385:1737-1749, 2021 (CKD-EPI 2021)

fn lookup_ckd_stage(gfr_category: String) -> CKDStage {
    if gfr_category == "g1" { return ckd("G1 -- Normal or high", 90.0, 999.0, "Normal or high GFR. CKD only if kidney damage present (albuminuria, hematuria, structural abnormality) for >3 months.", "Identify and treat underlying cause. Cardiovascular risk reduction. Monitor annually.", "KDIGO 2012; Guyton 14th ed, Ch 32") }
    if gfr_category == "g2" { return ckd("G2 -- Mildly decreased", 60.0, 89.0, "Mild GFR reduction. CKD only if kidney damage markers present. Common in elderly without pathology.", "Same as G1. Estimate progression rate.", "KDIGO 2012") }
    if gfr_category == "g3a" { return ckd("G3a -- Mild to moderate decrease", 45.0, 59.0, "Mild-moderate reduction. May be asymptomatic. Begin to see PTH rise, early phosphate retention, mild anemia.", "Monitor every 6 months. Dose-adjust renally cleared medications. SGLT2 inhibitor if albuminuria (DAPA-CKD). ACEi/ARB if proteinuria.", "KDIGO 2012") }
    if gfr_category == "g3b" { return ckd("G3b -- Moderate to severe decrease", 30.0, 44.0, "Moderate-severe reduction. Significant metabolic complications: secondary hyperparathyroidism, hyperphosphatemia, anemia (EPO deficiency), metabolic acidosis, hyperkalemia risk.", "Monitor every 3 months. Nephrology referral. Phosphate binders. EPO-stimulating agents (ESA) if Hgb <10. Avoid nephrotoxins (NSAIDs, contrast, aminoglycosides).", "KDIGO 2012") }
    if gfr_category == "g4" { return ckd("G4 -- Severely decreased", 15.0, 29.0, "Severe reduction. Uremic symptoms may appear: fatigue, nausea, anorexia, pruritus, neuropathy, pericarditis. Fluid overload. Hyperkalemia. Severe anemia. Renal osteodystrophy.", "Prepare for renal replacement therapy (dialysis access, transplant evaluation). Monitor monthly. Intensive metabolic management. Dietary K+/PO4/protein restriction.", "KDIGO 2012; Guyton 14th ed, Ch 32") }
    if gfr_category == "g5" { return ckd("G5 -- Kidney failure", 0.0, 14.0, "Kidney failure (ESKD if on dialysis). GFR <15 or dialysis. Uremia: encephalopathy, seizures, pericarditis, bleeding (platelet dysfunction), profound anemia, hyperkalemia (arrhythmia risk), metabolic acidosis, volume overload, malnutrition.", "Renal replacement therapy: hemodialysis, peritoneal dialysis, or kidney transplant. Transplant is preferred (survival advantage over dialysis). Dialysis typically initiated when symptomatic or GFR <5-10.", "KDIGO 2012; Guyton 14th ed, Ch 32") }
    return ckd("", 0.0, 0.0, "", "", "")
}

// ═══════════════════════════════════════════════════════
// AKI -- Acute Kidney Injury
// ═══════════════════════════════════════════════════════
// KDIGO AKI staging: Stage 1 (Scr 1.5-1.9x baseline or UO <0.5 mL/kg/hr x 6hr)
//                    Stage 2 (Scr 2.0-2.9x baseline or UO <0.5 x 12hr)
//                    Stage 3 (Scr >=3x or >=4.0 or RRT or UO <0.3 x 24hr or anuria x12hr)
//
// Cited: KDIGO AKI Guideline 2012; Guyton 14th ed, Ch 32

fn lookup_aki_category(category: String) -> String {
    if category == "prerenal" { return "Prerenal AKI (~55-60% of cases). Reduced renal perfusion with intact nephrons. Causes: hypovolemia (hemorrhage, dehydration, vomiting/diarrhea), decreased cardiac output (HF, cardiogenic shock), systemic vasodilation (sepsis, anaphylaxis), renal vasoconstriction (NSAIDs block prostaglandin-mediated afferent dilation; ACEi/ARB block efferent constriction -> GFR drops). Labs: BUN/Cr ratio >20:1, FENa <1%, urine osmolality >500, concentrated urine with bland sediment. Reversible with volume resuscitation if caught early. Prolonged prerenal -> ATN." }
    if category == "intrinsic" { return "Intrinsic AKI (~35-40% of cases). Structural damage to nephron components. (A) Tubular: Acute tubular necrosis (ATN) -- ischemic (prolonged prerenal) or nephrotoxic (aminoglycosides, contrast, cisplatin, myoglobin). Muddy brown granular casts on UA. FENa >2%. (B) Glomerular: RPGN (crescentic GN), anti-GBM (Goodpasture), lupus nephritis. RBC casts, dysmorphic RBCs. (C) Interstitial: Acute interstitial nephritis (AIN) -- drugs (NSAIDs, penicillins, PPIs), infections. WBC casts, eosinophiluria. (D) Vascular: TTP/HUS, malignant HTN, renal artery thrombosis, cholesterol emboli." }
    if category == "postrenal" { return "Postrenal AKI (~5-10% of cases). Urinary tract obstruction. Causes: BPH (most common in elderly men), kidney stones (bilateral or unilateral in solitary kidney), retroperitoneal fibrosis, pelvic malignancy (cervical, bladder, prostate), neurogenic bladder, urethral stricture. Diagnosis: hydronephrosis on renal ultrasound. Bilateral obstruction required to cause AKI (unless solitary kidney). Treatment: relieve obstruction (Foley catheter, ureteral stent, nephrostomy). Post-obstructive diuresis common after relief." }
    return ""
}

// ═══════════════════════════════════════════════════════
// CLINICAL SYNDROMES -- Nephrotic vs Nephritic
// ═══════════════════════════════════════════════════════
// Cited: Guyton 14th ed, Ch 32; Brenner 11th ed

fn lookup_clinical_syndrome(syndrome: String) -> ClinicalSyndrome {
    if syndrome == "nephrotic" { return csyn("Nephrotic syndrome", "Podocyte/basement membrane injury -> massive proteinuria", "Injury to podocytes or GBM disrupts charge/size barrier -> albumin and other proteins leak into urine. Hypoalbuminemia -> decreased oncotic pressure -> edema. Liver compensatory lipoprotein synthesis -> hyperlipidemia. Loss of antithrombin III and protein S -> hypercoagulable state. Loss of immunoglobulins -> infection risk.", "Proteinuria >3.5 g/day, hypoalbuminemia (<3 g/dL), peripheral edema (periorbital in children), hyperlipidemia, lipiduria (oval fat bodies, Maltese cross under polarized light), hypercoagulability", ">3.5 g/day (nephrotic-range)", "Usually normal (except membranous GN with complement activation)", "Minimal change disease (MCD, children -- foot process effacement on EM, responds to steroids), focal segmental glomerulosclerosis (FSGS, adults -- sclerosis, may recur in transplant), membranous nephropathy (subepithelial deposits with anti-PLA2R antibodies, P14555), diabetic nephropathy (Kimmelstiel-Wilson nodules), amyloidosis (Congo red positive)", "Guyton 14th ed, Ch 32; Brenner 11th ed") }

    if syndrome == "nephritic" { return csyn("Nephritic syndrome", "Glomerular inflammation -> hematuria and reduced GFR", "Inflammatory infiltration of glomerulus disrupts capillary walls -> RBCs leak into urine. Proliferative/inflammatory changes reduce filtration area -> decreased GFR -> oliguria, fluid retention, hypertension. Complement consumption common.", "Hematuria (dysmorphic RBCs, RBC casts -- pathognomonic), mild-moderate proteinuria (<3.5 g/day), hypertension, oliguria, periorbital edema, elevated BUN/Cr", "<3.5 g/day (subnephrotic)", "Often low (complement consumption: C3, C4 depending on pathway)", "Post-streptococcal GN (children, 2-3 weeks after pharyngitis/skin infection -- subepithelial humps, low C3), IgA nephropathy (Berger disease, most common GN worldwide -- mesangial IgA deposits, episodic gross hematuria with URI), lupus nephritis (class III-IV -- full house IF pattern), anti-GBM disease (Goodpasture -- linear IgG on IF, pulmonary hemorrhage), ANCA vasculitis (GPA, MPA -- pauci-immune crescentic GN)", "Guyton 14th ed, Ch 32; Brenner 11th ed") }

    if syndrome == "rpgn" { return csyn("Rapidly progressive glomerulonephritis (RPGN)", "Crescentic GN -> rapid GFR decline over days to weeks", "Crescent formation in Bowman space (proliferating parietal epithelial cells + macrophages + fibrin) compresses the glomerular tuft. Three immunopathologic types: Type I (anti-GBM, linear IF), Type II (immune complex, granular IF), Type III (pauci-immune, ANCA-associated, negative IF).", "Rapid rise in creatinine (doubling over days-weeks), nephritic sediment (RBC casts), oliguria, >50% crescents on biopsy", "Variable (often nephrotic-range)", "Depends on type: low in type II (immune complex), normal in type I and III", "Type I: anti-GBM (Goodpasture, if pulmonary hemorrhage = Goodpasture syndrome. Treat: plasmapheresis + cyclophosphamide + steroids). Type II: lupus nephritis, post-infectious, IgA. Type III: ANCA-associated (GPA with PR3-ANCA, MPA with MPO-ANCA. Treat: rituximab or cyclophosphamide + steroids).", "Brenner 11th ed") }

    return csyn("", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// TUBULOGLOMERULAR FEEDBACK AND MYOGENIC RESPONSE
// ═══════════════════════════════════════════════════════
// GFR autoregulation maintains stable GFR over MAP 80-180 mmHg
// Cited: Guyton 14th ed, Ch 27; Boron 3rd ed, Ch 33

fn tubuloglomerular_feedback() -> String {
    return "Macula densa cells (specialized epithelium at junction of TAL and DCT, part of juxtaglomerular apparatus) sense NaCl concentration in tubular fluid via apical NKCC2. HIGH NaCl (indicates high GFR) -> ATP/adenosine release -> constricts afferent arteriole -> reduces GFR (negative feedback). LOW NaCl (indicates low GFR) -> releases prostaglandins/NO -> dilates afferent arteriole -> restores GFR. Also stimulates renin release from JG cells. This is why NSAIDs (which block prostaglandins) can precipitate AKI in volume-depleted patients."
}

fn myogenic_response() -> String {
    return "Intrinsic property of afferent arteriolar smooth muscle. Increased perfusion pressure stretches arteriolar wall -> voltage-gated Ca2+ channels open -> smooth muscle contraction -> increased resistance -> constant flow despite higher pressure. Operates within seconds. Together with TGF, maintains GFR autoregulation over MAP 80-180 mmHg. Below MAP 80: autoregulation fails, GFR falls linearly with pressure."
}

// ═══════════════════════════════════════════════════════
// CLINICAL EQUATIONS
// ═══════════════════════════════════════════════════════

fn gfr_normal() -> Float {
    return 125.0
}

fn gfr_units() -> String {
    return "mL/min/1.73m2"
}

fn ckd_epi_citation() -> String {
    return "Inker LA et al. New creatinine- and cystatin C-based equations to estimate GFR without race. N Engl J Med 385:1737-1749, 2021"
}

fn fractional_excretion_na_formula() -> String {
    return "FENa = (UNa * PCr) / (PNa * UCr) * 100%. FENa <1% = prerenal (avid Na+ reabsorption intact). FENa >2% = intrinsic renal (tubular damage, cannot reabsorb Na+). Caveat: diuretics invalidate FENa; use FEUrea instead (FEUrea <35% = prerenal)."
}

fn renal_clearance_formula() -> String {
    return "Clearance (Cx) = (Ux * V) / Px. Where Ux = urine concentration, V = urine flow rate, Px = plasma concentration. Inulin clearance = GFR (freely filtered, not reabsorbed, not secreted). PAH clearance = RPF (at low concentrations, completely cleared in single pass). Creatinine clearance slightly overestimates GFR (some tubular secretion)."
}

// ═══════════════════════════════════════════════════════
// QUICK ACCESS COUNTS
// ═══════════════════════════════════════════════════════

fn nephron_segment_count() -> Int {
    return 8
}

fn transporter_count() -> Int {
    return 16
}

fn starling_force_count() -> Int {
    return 9
}

fn raas_step_count() -> Int {
    return 6
}

fn diuretic_count() -> Int {
    return 9
}

fn ckd_stage_count() -> Int {
    return 6
}

fn acid_base_process_count() -> Int {
    return 5
}

fn hormonal_regulator_count() -> Int {
    return 6
}

fn clinical_syndrome_count() -> Int {
    return 3
}

fn aki_category_count() -> Int {
    return 3
}
