// acid_base.sy -- pH, acid-base chemistry, indicators, buffers, and
// blood gas homeostasis as native Scyla.
//
// Sources:
//   Lehninger Principles of Biochemistry, 8th ed, 2021.
//   Guyton and Hall Textbook of Medical Physiology, 14th ed, 2021.
//   Zumdahl SS. Chemistry, 10th ed, 2018.
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536

struct PHIndicator {
    name: String,
    low_color: String,
    high_color: String,
    transition_ph_low: Float,
    transition_ph_high: Float,
    indicator_type: String,
    citation: String,
}

struct BufferSystem {
    name: String,
    acid_form: String,
    base_form: String,
    pka: Float,
    biological_role: String,
    normal_range: String,
    citation: String,
}

struct BloodGasValue {
    parameter: String,
    normal_low: Float,
    normal_high: Float,
    unit: String,
    low_condition: String,
    high_condition: String,
    citation: String,
}

fn indicator(n: String, lc: String, hc: String, tl: Float, th: Float, it: String, ci: String) -> PHIndicator {
    return PHIndicator { name: n, low_color: lc, high_color: hc, transition_ph_low: tl, transition_ph_high: th, indicator_type: it, citation: ci }
}

fn buffer(n: String, af: String, bf: String, pk: Float, br: String, nr: String, ci: String) -> BufferSystem {
    return BufferSystem { name: n, acid_form: af, base_form: bf, pka: pk, biological_role: br, normal_range: nr, citation: ci }
}

fn abg(p: String, nl: Float, nh: Float, u: String, lc: String, hc: String, ci: String) -> BloodGasValue {
    return BloodGasValue { parameter: p, normal_low: nl, normal_high: nh, unit: u, low_condition: lc, high_condition: hc, citation: ci }
}

// ═══════════════════════════════════════════════════════
// pH INDICATORS
// ═══════════════════════════════════════════════════════

fn lookup_indicator(name: String) -> PHIndicator {
    if name == "litmus" { return indicator("Litmus", "red (acid)", "blue (base)", 4.5, 8.3, "natural (lichen extract)", "Zumdahl 10th ed") }
    if name == "phenolphthalein" { return indicator("Phenolphthalein", "colorless (acid)", "pink/magenta (base)", 8.2, 10.0, "synthetic", "Zumdahl 10th ed") }
    if name == "bromothymol_blue" { return indicator("Bromothymol blue", "yellow (acid)", "blue (base)", 6.0, 7.6, "synthetic sulfonephthalein", "Zumdahl 10th ed") }
    if name == "methyl_orange" { return indicator("Methyl orange", "red (acid)", "yellow (base)", 3.1, 4.4, "synthetic azo dye", "Zumdahl 10th ed") }
    if name == "methyl_red" { return indicator("Methyl red", "red (acid)", "yellow (base)", 4.4, 6.2, "synthetic azo dye", "Zumdahl 10th ed") }
    if name == "congo_red" { return indicator("Congo red", "blue (acid)", "red (base)", 3.0, 5.0, "synthetic diazo dye. Also used for amyloid staining in pathology.", "Zumdahl 10th ed") }
    if name == "thymol_blue" { return indicator("Thymol blue", "red (acid) / yellow (mid) / blue (base)", "blue", 1.2, 2.8, "synthetic. Diprotic: second transition 8.0-9.6.", "Zumdahl 10th ed") }
    if name == "phenol_red" { return indicator("Phenol red", "yellow (acid)", "red (base)", 6.8, 8.4, "synthetic sulfonephthalein. Used in cell culture media as pH indicator.", "Zumdahl 10th ed") }
    if name == "universal" { return indicator("Universal indicator", "red (pH 1) through green (pH 7) to violet (pH 14)", "full spectrum", 1.0, 14.0, "mixture of several indicators providing continuous color spectrum", "Zumdahl 10th ed") }
    if name == "pH_paper" { return indicator("pH paper (test strips)", "color chart comparison", "matches color to pH value", 0.0, 14.0, "impregnated paper strips with indicator dyes. Resolution ~0.5 pH units. Used in clinical urinalysis, soil testing, pool maintenance.", "Standard laboratory supply") }
    return indicator("", "", "", 0.0, 0.0, "", "")
}

// ═══════════════════════════════════════════════════════
// BIOLOGICAL BUFFER SYSTEMS
// ═══════════════════════════════════════════════════════

fn lookup_buffer(name: String) -> BufferSystem {
    if name == "bicarbonate" { return buffer("Bicarbonate buffer", "CO2 + H2O (carbonic acid, H2CO3)", "HCO3- (bicarbonate)", 6.1, "Primary extracellular buffer. Open system: CO2 exhaled by lungs. HCO3- reabsorbed by kidneys. Accounts for ~75% of blood buffering capacity.", "pH 7.35-7.45 | HCO3- 22-26 mEq/L | pCO2 35-45 mmHg", "Guyton 14th ed, Ch 31") }
    if name == "phosphate" { return buffer("Phosphate buffer", "H2PO4- (dihydrogen phosphate)", "HPO4 2- (hydrogen phosphate)", 6.8, "Major intracellular buffer. Important in urine (titratable acidity). pKa near physiological pH makes it effective.", "Intracellular [Pi] ~1-2 mM", "Lehninger 8th ed, Ch 2") }
    if name == "protein" { return buffer("Protein buffer (hemoglobin)", "Protonated histidine residues (HHb)", "Deprotonated histidine (Hb-)", 6.8, "Hemoglobin is the most important intracellular buffer in blood. Histidine pKa ~6.0-7.0. Deoxyhemoglobin is a better buffer than oxyhemoglobin (Bohr effect). Also albumin in plasma.", "Hgb 12-17 g/dL", "Guyton 14th ed, Ch 31") }
    if name == "ammonia" { return buffer("Ammonia/ammonium buffer", "NH4+ (ammonium)", "NH3 (ammonia)", 9.25, "Renal acid excretion. Glutaminase in proximal tubule generates NH3 from glutamine. NH3 diffuses into tubular lumen, picks up H+ to become NH4+, excreted. Each NH4+ = one net H+ excreted.", "Urine NH4+ ~30-50 mEq/day", "Guyton 14th ed, Ch 31") }
    return buffer("", "", "", 0.0, "", "", "")
}

// ═══════════════════════════════════════════════════════
// BLOOD GAS VALUES — arterial blood gas (ABG)
// ═══════════════════════════════════════════════════════

fn lookup_abg(param: String) -> BloodGasValue {
    if param == "pH" { return abg("pH", 7.35, 7.45, "", "Acidemia (< 7.35). Respiratory: CO2 retention. Metabolic: HCO3- loss or acid gain (DKA, lactic acidosis, renal failure).", "Alkalemia (> 7.45). Respiratory: hyperventilation. Metabolic: HCO3- gain or H+ loss (vomiting, diuretics).", "Guyton 14th ed") }
    if param == "pCO2" { return abg("pCO2", 35.0, 45.0, "mmHg", "Respiratory alkalosis (hyperventilation blows off CO2). Anxiety, pain, PE, pregnancy, high altitude.", "Respiratory acidosis (hypoventilation retains CO2). COPD, opioid overdose, neuromuscular disease, obesity hypoventilation.", "Guyton 14th ed") }
    if param == "HCO3" { return abg("HCO3-", 22.0, 26.0, "mEq/L", "Metabolic acidosis. DKA, lactic acidosis, diarrhea (HCO3 loss), renal tubular acidosis, methanol/ethylene glycol poisoning.", "Metabolic alkalosis. Vomiting (HCl loss), NG suction, diuretics (volume contraction), Cushing, hyperaldosteronism.", "Guyton 14th ed") }
    if param == "pO2" { return abg("pO2", 80.0, 100.0, "mmHg", "Hypoxemia. V/Q mismatch, shunt, diffusion impairment, hypoventilation, low FiO2 (altitude).", "Hyperoxia (usually iatrogenic from supplemental O2). Can cause absorption atelectasis, O2 toxicity in neonates (ROP).", "Guyton 14th ed") }
    if param == "SaO2" { return abg("SaO2", 95.0, 100.0, "%", "Desaturation. Same causes as low pO2. SaO2 < 90% = pO2 ~60 mmHg (steep part of oxyhemoglobin dissociation curve).", "Normal (cannot exceed 100%).", "Guyton 14th ed") }
    if param == "base_excess" { return abg("Base excess (BE)", -2.0, 2.0, "mEq/L", "Negative BE = metabolic acidosis (base deficit). The body has used up buffering capacity.", "Positive BE = metabolic alkalosis (excess base).", "Guyton 14th ed") }
    if param == "anion_gap" { return abg("Anion gap", 8.0, 12.0, "mEq/L", "Normal anion gap metabolic acidosis: diarrhea, RTA, acetazolamide (hyperchloremic).", "Elevated anion gap metabolic acidosis (MUDPILES): Methanol, Uremia, DKA, Propylene glycol, INH/Iron, Lactic acidosis, Ethylene glycol, Salicylates.", "Guyton 14th ed") }
    return abg("", 0.0, 0.0, "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// pH CLASSIFICATION
// ═══════════════════════════════════════════════════════

fn classify_ph(ph: Float) -> String {
    if ph < 0.0 { return "invalid" }
    if ph < 3.0 { return "strongly acidic" }
    if ph < 5.0 { return "moderately acidic" }
    if ph < 6.5 { return "weakly acidic" }
    if ph < 7.5 { return "neutral to physiological" }
    if ph < 9.0 { return "weakly basic" }
    if ph < 11.0 { return "moderately basic" }
    if ph <= 14.0 { return "strongly basic" }
    return "invalid"
}

fn common_ph(substance: String) -> Float {
    if substance == "stomach_acid" { return 1.5 }
    if substance == "lemon_juice" { return 2.0 }
    if substance == "vinegar" { return 2.9 }
    if substance == "orange_juice" { return 3.5 }
    if substance == "coffee" { return 5.0 }
    if substance == "urine" { return 6.0 }
    if substance == "milk" { return 6.6 }
    if substance == "pure_water" { return 7.0 }
    if substance == "blood" { return 7.4 }
    if substance == "seawater" { return 8.1 }
    if substance == "baking_soda" { return 8.3 }
    if substance == "antacid" { return 10.0 }
    if substance == "ammonia" { return 11.6 }
    if substance == "bleach" { return 12.5 }
    if substance == "drain_cleaner" { return 14.0 }
    return 0.0
}

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

fn indicator_count() -> Int {
    return 10
}

fn buffer_count() -> Int {
    return 4
}

fn abg_parameter_count() -> Int {
    return 7
}

fn blood_ph_normal_low() -> Float {
    return 7.35
}

fn blood_ph_normal_high() -> Float {
    return 7.45
}
