// organ_models.sy -- Organ-level drug handling models for in silico
// pharmacokinetic simulation as native Scyla.
//
// Sources:
//   Rowland M, Tozer TN. Clinical Pharmacokinetics, 5th ed, 2011.
//   Guyton AC, Hall JE. Textbook of Medical Physiology, 14th ed, 2021.
//   Brunton LL et al. Goodman and Gilman's, 14th ed, 2023.
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536

// =========================================================
// LIVER
// =========================================================

// Normal hepatic blood flow: ~1500 mL/min (25% of cardiac output)
fn liver_blood_flow() -> Float {
    return 1500.0
}

// Well-stirred model hepatic extraction ratio:
// E = fu * CLint / (Q + fu * CLint)
// fu = fraction unbound in blood, CLint = intrinsic clearance
// Rowland/Tozer 5th ed, Ch 5.
fn hepatic_extraction(cl_intrinsic: Float, blood_flow: Float, fu: Float) -> Float {
    return fu * cl_intrinsic / (blood_flow + fu * cl_intrinsic)
}

// Bioavailability from first-pass: F = 1 - E
fn first_pass_bioavailability(extraction: Float) -> Float {
    return 1.0 - extraction
}

// CYP enzyme expression in liver (% of total hepatic CYP content)
// Zanger UM, Schwab M. Pharmacol Ther 138:103-141, 2013.
fn cyp_expression_liver(enzyme: String) -> String {
    if enzyme == "CYP3A4" { return "30% of hepatic CYP. Most abundant. Metabolizes ~50% of marketed drugs. Induced by rifampin, carbamazepine, St. John wort. Inhibited by ketoconazole, itraconazole, ritonavir, grapefruit juice (intestinal)." }
    if enzyme == "CYP2C9" { return "20% of hepatic CYP. Metabolizes warfarin (S-enantiomer), phenytoin, NSAIDs, losartan. Polymorphic: CYP2C9*2/*3 = poor metabolizer (warfarin sensitivity)." }
    if enzyme == "CYP1A2" { return "13% of hepatic CYP. Metabolizes caffeine, theophylline, clozapine, olanzapine. Induced by smoking (PAH, not nicotine), charbroiled meat, cruciferous vegetables. Inhibited by ciprofloxacin, fluvoxamine." }
    if enzyme == "CYP2E1" { return "7% of hepatic CYP. Metabolizes ethanol, acetaminophen (to NAPQI), volatile anesthetics. Induced by ethanol (chronic), isoniazid. Zone 3 predominant (pericentral, explains acetaminophen hepatotoxicity pattern)." }
    if enzyme == "CYP2D6" { return "2% of hepatic CYP but metabolizes ~25% of drugs. Codeine to morphine, tamoxifen to endoxifen. NOT inducible. Highly polymorphic: PM 5-10% Caucasians, UM 1-10%. Inhibited by fluoxetine, paroxetine, bupropion, quinidine." }
    if enzyme == "CYP2C19" { return "1% of hepatic CYP. Metabolizes clopidogrel (prodrug activation), PPIs, voriconazole, citalopram. PM 2-5% Caucasians, 15-20% Asian. CYP2C19*2/*3 = PM. *17 = UM." }
    if enzyme == "CYP2B6" { return "<1% hepatic CYP. Metabolizes efavirenz, methadone, cyclophosphamide, bupropion. Induced by rifampin. Highly polymorphic." }
    return ""
}

// Hepatic zonation
fn liver_zone(zone: Int) -> String {
    if zone == 1 { return "Zone 1 (periportal): highest O2, first to receive portal blood. Gluconeogenesis, beta-oxidation, cholesterol synthesis, urea cycle. Least susceptible to ischemic damage. Phosphorus poisoning affects zone 1." }
    if zone == 2 { return "Zone 2 (mid-zonal): intermediate O2. Transitional functions." }
    if zone == 3 { return "Zone 3 (pericentral/centrilobular): lowest O2. CYP450 highest here. Glycolysis, lipogenesis, glutamine synthesis. Most susceptible to ischemic damage. Acetaminophen toxicity here (CYP2E1 generates NAPQI, GSH depleted first here). Alcoholic hepatitis. Cardiac hepatopathy." }
    return ""
}

// ALT half-life for monitoring drug hepatotoxicity
fn alt_half_life_hours() -> Float {
    return 47.0
}

// =========================================================
// KIDNEY
// =========================================================

// Normal renal blood flow: ~1200 mL/min (20% of cardiac output)
fn renal_blood_flow() -> Float {
    return 1200.0
}

// Normal GFR
fn gfr_normal() -> Float {
    return 120.0
}

// Tubular secretion transporters
fn tubular_transporter(name: String) -> String {
    if name == "OAT1" { return "Organic Anion Transporter 1 (SLC22A6). Basolateral uptake. Substrates: penicillins, cephalosporins, methotrexate, NSAIDs, adefovir, cidofovir, tenofovir. Probenecid inhibits (used to prolong penicillin half-life)." }
    if name == "OAT3" { return "Organic Anion Transporter 3 (SLC22A8). Basolateral uptake. Substrates: furosemide, bumetanide, pravastatin, ciprofloxacin." }
    if name == "OCT2" { return "Organic Cation Transporter 2 (SLC22A2). Basolateral uptake. Substrates: metformin, cisplatin, oxaliplatin. Cimetidine inhibits (falsely elevates creatinine without affecting GFR)." }
    if name == "MATE1" { return "Multidrug And Toxin Extrusion 1 (SLC47A1). Apical efflux. Substrates: metformin, cisplatin. Couples with OCT2 for tubular secretion." }
    if name == "Pgp" { return "P-glycoprotein (ABCB1/MDR1). Apical efflux. Substrates: digoxin, cyclosporine, HIV protease inhibitors. Limits renal reabsorption." }
    if name == "MRP2" { return "Multidrug Resistance Protein 2 (ABCC2). Apical efflux. Substrates: methotrexate, glutathione conjugates." }
    return ""
}

// Ion trapping: weak acids trapped in alkaline urine, weak bases in acidic urine
fn ion_trapping_reabsorbed(pka: Float, urine_ph: Float, is_weak_acid: Bool) -> Bool {
    // Weak acid: un-ionized (reabsorbed) when urine pH << pKa
    // Weak base: un-ionized (reabsorbed) when urine pH >> pKa
    if is_weak_acid {
        if urine_ph < pka { return true }
        return false
    }
    if urine_ph > pka { return true }
    return false
}

// Nephrotoxic drugs
fn nephrotoxic_drug(name: String) -> String {
    if name == "aminoglycosides" { return "Proximal tubular necrosis. Accumulate in lysosomes via megalin endocytosis. Dose-dependent, usually reversible. Risk: trough >2 mcg/mL (gentamicin). Monitor: SCr, trough levels." }
    if name == "vancomycin" { return "Acute tubular necrosis, interstitial nephritis. Risk increases with trough >20 mcg/mL, concurrent nephrotoxins, obesity. Monitor: AUC/MIC preferred over trough." }
    if name == "cisplatin" { return "Proximal and distal tubular damage. Dose-limiting toxicity. Cumulative. OCT2-mediated uptake. Prevention: aggressive IV hydration + amifostine. Irreversible Mg wasting common." }
    if name == "NSAIDs" { return "Hemodynamic (afferent arteriole constriction via prostaglandin inhibition). Prerenal AKI. Also: interstitial nephritis, minimal change disease, papillary necrosis (chronic). Risk: CKD, HF, dehydration, ACEi/ARB." }
    if name == "contrast_dye" { return "Contrast-induced nephropathy (CIN). Renal vasoconstriction + direct tubular toxicity. Peaks 3-5 days post-exposure. Prevention: IV NS hydration, minimize contrast volume. NAC controversial. Risk: CKD, diabetes, HF." }
    if name == "lithium" { return "Nephrogenic diabetes insipidus (collecting duct, downregulates AQP2). Chronic interstitial nephritis with long-term use. Monitor: Li levels, SCr, urine osmolality." }
    if name == "methotrexate" { return "Crystal nephropathy (MTX and 7-OH-MTX precipitate in tubules at low pH). Prevention: alkaline hydration (urine pH >7), leucovorin rescue, monitor levels at 24/48/72h." }
    if name == "acyclovir" { return "Crystal nephropathy (especially IV, high doses, dehydration). Prevention: adequate hydration, slow infusion, dose-adjust for renal function." }
    return ""
}

// Drug dialyzability criteria
fn drug_dialyzable(mw: Float, protein_binding_pct: Float, vd_l_kg: Float) -> Bool {
    // Dialyzable if: MW <500 Da, low protein binding (<80%), small Vd (<1 L/kg)
    if mw > 500.0 { return false }
    if protein_binding_pct > 80.0 { return false }
    if vd_l_kg > 1.0 { return false }
    return true
}

// =========================================================
// HEART
// =========================================================

// Normal cardiac output
fn cardiac_output() -> Float {
    return 5000.0
}

// QT-prolonging drugs by risk level
fn qt_drug_risk(drug: String) -> String {
    if drug == "AMIODARONE" { return "Known risk. Class III antiarrhythmic. Blocks IKr (hERG), IKs, INa, ICaL. Paradoxically low TdP risk despite marked QT prolongation (also blocks INa preventing EADs). Half-life 40-55 days." }
    if drug == "SOTALOL" { return "Known risk. Class III antiarrhythmic (also non-selective beta-blocker). Blocks IKr. TdP risk 2-4%, dose-dependent. Requires inpatient initiation with telemetry." }
    if drug == "HALOPERIDOL" { return "Known risk. Blocks IKr (hERG). Risk increases with IV use, high doses, hypokalemia, hypomagnesemia. Black box warning for IV haloperidol and QT prolongation." }
    if drug == "METHADONE" { return "Known risk. Blocks IKr (hERG). Risk increases >100 mg/day. ECG recommended before and after initiation. Dose-dependent." }
    if drug == "ERYTHROMYCIN" { return "Known risk. Blocks IKr. Risk especially with IV administration and CYP3A4 inhibitors. Azithromycin: possible risk (lower than erythromycin)." }
    if drug == "CIPROFLOXACIN" { return "Possible risk. Blocks IKr. Lower risk than moxifloxacin. Avoid with other QT-prolonging drugs." }
    if drug == "MOXIFLOXACIN" { return "Known risk. Blocks IKr. Highest QT risk among fluoroquinolones. ~6 ms QTc prolongation at therapeutic doses." }
    if drug == "ONDANSETRON" { return "Possible risk. Blocks IKr. Dose-dependent: 32 mg IV dose withdrawn. Max single IV dose now 16 mg. ECG for high-risk patients." }
    if drug == "CITALOPRAM" { return "Known risk. Dose-dependent QT prolongation. Max dose 40 mg (20 mg if >60 years, hepatic impairment, CYP2C19 PM). FDA safety communication 2012." }
    if drug == "QUETIAPINE" { return "Possible risk. Moderate IKr block. Risk lower than haloperidol." }
    return ""
}

// Ejection fraction classification
fn ef_classification(ef_pct: Float) -> String {
    if ef_pct < 40.0 { return "HFrEF (heart failure with reduced ejection fraction). Guideline-directed medical therapy: ACEi/ARB/ARNI + beta-blocker + MRA + SGLT2i (four pillars). Consider ICD if EF <=35%." }
    if ef_pct < 50.0 { return "HFmrEF (heart failure with mildly reduced EF, 40-49%). Treat like HFrEF per 2022 AHA/ACC guidelines. SGLT2i recommended." }
    return "HFpEF (heart failure with preserved EF, >=50%). SGLT2i (empagliflozin, dapagliflozin) now recommended. Diuretics for congestion. Treat comorbidities (HTN, AFib, obesity, CAD)."
}

// =========================================================
// BRAIN / CNS
// =========================================================

// BBB permeability prediction (Lipinski-like for CNS)
fn bbb_permeable(log_p: Float, mw: Float, hbd: Int, psa: Float) -> Bool {
    if log_p < 1.0 { return false }
    if log_p > 3.0 { return false }
    if mw > 450.0 { return false }
    if hbd > 3 { return false }
    if psa > 90.0 { return false }
    return true
}

// P-glycoprotein substrates at BBB
fn pgp_substrate_bbb(drug: String) -> Bool {
    if drug == "LOPERAMIDE" { return true }
    if drug == "DIGOXIN" { return true }
    if drug == "CYCLOSPORINE" { return true }
    if drug == "TACROLIMUS" { return true }
    if drug == "RITONAVIR" { return true }
    if drug == "INDINAVIR" { return true }
    if drug == "SAQUINAVIR" { return true }
    if drug == "DOXORUBICIN" { return true }
    if drug == "VINBLASTINE" { return true }
    if drug == "COLCHICINE" { return true }
    if drug == "IVERMECTIN" { return true }
    return false
}

// Circumventricular organs (areas without BBB)
fn circumventricular_organ(name: String) -> String {
    if name == "area_postrema" { return "Area postrema (chemoreceptor trigger zone): detects toxins/drugs in blood, triggers vomiting. Target of antiemetics (ondansetron, metoclopramide). Located in medulla at floor of 4th ventricle." }
    if name == "median_eminence" { return "Median eminence: hypothalamic releasing hormones enter portal blood to anterior pituitary. GnRH, CRH, TRH, GHRH, somatostatin, dopamine." }
    if name == "neurohypophysis" { return "Posterior pituitary (neurohypophysis): releases ADH and oxytocin directly into systemic circulation." }
    if name == "pineal" { return "Pineal gland: releases melatonin. No BBB allows melatonin direct access to circulation." }
    if name == "SFO" { return "Subfornical organ: detects angiotensin II in blood, triggers thirst and ADH release. Cardiovascular regulation." }
    if name == "OVLT" { return "Organum vasculosum of lamina terminalis: detects pyrogens (IL-1, PGE2), mediates fever response. Also osmosensing." }
    return ""
}

// =========================================================
// LUNG
// =========================================================

// Pulmonary blood flow = 100% of cardiac output
fn pulmonary_blood_flow() -> Float {
    return 5000.0
}

// Inhaled drug deposition by particle size (MMAD)
fn inhaled_deposition(particle_size_um: Float) -> String {
    if particle_size_um > 5.0 { return "Oropharyngeal deposition: >5 um particles impact in mouth and throat. Swallowed (contributes to systemic absorption and oral candidiasis with ICS). Use spacer to reduce." }
    if particle_size_um > 2.0 { return "Bronchial deposition: 2-5 um reaches conducting airways (bronchi, bronchioles). Target for asthma/COPD inhalers. Optimal for bronchodilators and ICS." }
    if particle_size_um > 0.5 { return "Alveolar deposition: 0.5-2 um reaches alveoli. Deep lung penetration. Systemic absorption possible. Target for systemic delivery (insulin inhalation, Afrezza)." }
    return "Exhaled: <0.5 um particles remain suspended in air and are exhaled without depositing. Too small for effective drug delivery."
}

// First-pass pulmonary extraction
fn first_pass_pulmonary(drug: String) -> String {
    if drug == "FENTANYL" { return "High pulmonary extraction (75%). Lung serves as reservoir. Rapid uptake on first pass, then slow release. Explains rapid onset of IV fentanyl." }
    if drug == "PROPRANOLOL" { return "High pulmonary extraction (~70%). Significant first-pass pulmonary metabolism. Lung is a major site of propranolol clearance." }
    if drug == "LIDOCAINE" { return "High pulmonary extraction (~70%). Lung buffers lidocaine bolus, preventing cardiac toxicity from rapid IV push." }
    if drug == "NOREPINEPHRINE" { return "High pulmonary uptake and metabolism by COMT/MAO in lung endothelium. Protects systemic circulation from excess catecholamines." }
    return ""
}

// =========================================================
// GI TRACT
// =========================================================

// pH by GI region
fn gi_ph(region: String) -> Float {
    if region == "stomach" { return 1.5 }
    if region == "duodenum" { return 5.5 }
    if region == "jejunum" { return 6.5 }
    if region == "ileum" { return 7.5 }
    if region == "colon" { return 6.0 }
    if region == "rectum" { return 7.0 }
    return 7.0
}

// Drug absorption site prediction
fn drug_absorption_site(pka: Float, is_weak_acid: Bool) -> String {
    if is_weak_acid {
        if pka < 4.0 { return "Stomach (pH 1.5): weak acid with low pKa is un-ionized in stomach, absorbed by passive diffusion across gastric mucosa. However, small surface area limits total absorption. Most absorption still in small intestine due to huge surface area (200 m2)." }
        return "Small intestine (pH 5.5-7.5): despite being more ionized at intestinal pH, the enormous surface area (villi, microvilli, 200 m2) means most drug absorption occurs here regardless of ionization state."
    }
    return "Small intestine (pH 5.5-7.5): weak bases are more un-ionized at intestinal pH, favoring absorption. Intestinal surface area dominates absorption for most drugs."
}

// CYP3A4 in gut wall
fn cyp3a4_gut_description() -> String {
    return "CYP3A4 is expressed in enterocytes of small intestinal villi (highest in duodenum/jejunum, decreasing distally). Contributes to intestinal first-pass metabolism BEFORE drug reaches portal circulation. Grapefruit juice irreversibly inhibits intestinal CYP3A4 (furanocoumarins), increasing bioavailability of CYP3A4 substrates (felodipine 3x, simvastatin 15x, cyclosporine 1.5x). Effect lasts 24-72 hours (time to regenerate enterocytes). Rifampin induces intestinal CYP3A4."
}

// =========================================================
// PLACENTA
// =========================================================

// Placental drug transfer prediction
fn placental_transfer_likely(mw: Float, protein_binding_pct: Float, is_lipophilic: Bool) -> Bool {
    // Most drugs cross placenta by passive diffusion
    // Favored by: low MW (<500), low protein binding, lipophilic, un-ionized
    if mw > 1000.0 { return false }
    if protein_binding_pct > 95.0 { return false }
    if is_lipophilic { return true }
    if mw < 500.0 { return true }
    return false
}

// Known teratogenic drugs (FDA category X or known teratogens)
fn teratogenic_drug(drug: String) -> String {
    if drug == "THALIDOMIDE" { return "Phocomelia (limb reduction defects). Critical period: days 21-36 post-conception. Now used for multiple myeloma, ENL (leprosy) with strict REMS (THALOMID REMS). Anti-angiogenic mechanism." }
    if drug == "ISOTRETINOIN" { return "Retinoid embryopathy: craniofacial (microtia, micrognathia), cardiac (conotruncal defects), CNS (hydrocephalus), thymic aplasia. iPLEDGE REMS program. Two forms of contraception required." }
    if drug == "WARFARIN" { return "Warfarin embryopathy: nasal hypoplasia, stippled epiphyses (chondrodysplasia punctata). Critical period: weeks 6-9. CNS abnormalities with 2nd/3rd trimester exposure. Switch to LMWH in pregnancy." }
    if drug == "VALPROIC_ACID" { return "Neural tube defects (1-2% risk, 10-20x background), facial dysmorphism, cognitive impairment, autism. Dose-dependent. Contraindicated in pregnancy for migraine/bipolar. Folic acid may partially mitigate." }
    if drug == "METHOTREXATE" { return "Aminopterin/methotrexate syndrome: cranial dysostosis, limb defects, growth restriction. Folic acid antagonist. Abortifacient. Must stop 3+ months before conception." }
    if drug == "ACE_INHIBITORS" { return "Renal dysgenesis, oligohydramnios, pulmonary hypoplasia, skull ossification defects (2nd/3rd trimester). Relatively safe in 1st trimester. Switch to labetalol/nifedipine/methyldopa in pregnancy." }
    if drug == "PHENYTOIN" { return "Fetal hydantoin syndrome: craniofacial (broad nasal bridge, cleft lip/palate), digital hypoplasia, IUGR, intellectual disability. Risk ~5-10%." }
    if drug == "LITHIUM" { return "Ebstein anomaly (tricuspid valve malformation). Risk ~0.1% (lower than previously thought, but still elevated over background 0.005%). Benefits may outweigh risks for severe bipolar." }
    if drug == "DIETHYLSTILBESTROL" { return "Clear cell adenocarcinoma of vagina/cervix in daughters exposed in utero. T-shaped uterus. Reproductive tract abnormalities. Banned in pregnancy since 1971." }
    return ""
}

// =========================================================
// COUNTS
// =========================================================

fn organ_model_count() -> Int {
    return 7
}

fn organ_function_count() -> Int {
    return 35
}
