// clinical_labs.sy -- Complete clinical laboratory reference values
// as native Scyla. CBC, CMP, LFTs, coagulation, thyroid, cardiac,
// lipids, HbA1c, urinalysis, iron studies.
//
// Sources:
//   Wallach J. Interpretation of Diagnostic Tests, 10th ed, 2015.
//   Fischbach FT. Manual of Laboratory and Diagnostic Tests, 10th ed, 2018.
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536


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

struct LabTest {
    test_name: String,
    units: String,
    normal_low: Float,
    normal_high: Float,
    critical_low: Float,
    critical_high: Float,
    clinical_significance: String,
    citation: String,
}

struct LabPattern {
    pattern_name: String,
    category: String,
    criteria: String,
    interpretation: String,
    differential: String,
    citation: String,
}

struct UrinalysisComponent {
    component_name: String,
    normal_value: String,
    abnormal_significance: String,
    method: String,
    citation: String,
}

struct LabCalculation {
    calc_name: String,
    formula: String,
    normal_range: String,
    interpretation: String,
    limitations: String,
    citation: String,
}


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

fn lab(tn: String, u: String, nl: Float, nh: Float, cl: Float, ch: Float, cs: String, ci: String) -> LabTest {
    return LabTest { test_name: tn, units: u, normal_low: nl, normal_high: nh, critical_low: cl, critical_high: ch, clinical_significance: cs, citation: ci }
}

fn pattern(pn: String, cat: String, cr: String, interp: String, diff: String, ci: String) -> LabPattern {
    return LabPattern { pattern_name: pn, category: cat, criteria: cr, interpretation: interp, differential: diff, citation: ci }
}

fn ua_component(cn: String, nv: String, ab: String, meth: String, ci: String) -> UrinalysisComponent {
    return UrinalysisComponent { component_name: cn, normal_value: nv, abnormal_significance: ab, method: meth, citation: ci }
}

fn calc(cn: String, f: String, nr: String, interp: String, lim: String, ci: String) -> LabCalculation {
    return LabCalculation { calc_name: cn, formula: f, normal_range: nr, interpretation: interp, limitations: lim, citation: ci }
}


// ═══════════════════════════════════════════════════════════════
// SECTION ONE: COMPLETE BLOOD COUNT (CBC)
// ═══════════════════════════════════════════════════════════════
//
// The CBC is the single most ordered laboratory test in medicine.
// It quantifies the cellular components of blood: erythrocytes
// (oxygen transport), leukocytes (immune defense), and platelets
// (hemostasis). Every emergency department visit, preoperative
// assessment, and chemotherapy cycle starts with a CBC.
//
// Wallach, 10th ed, Ch 11: Hematology.
// Fischbach, 10th ed, Ch 2: Blood Studies.

fn lookup_cbc(test: String) -> LabTest {
    // WBC: white blood cell count. First-line infection and immune marker.
    // Leukocytosis (> 11.0): infection, inflammation, stress, steroids, leukemia.
    // Leukopenia (< 4.5): bone marrow failure, viral infection, chemotherapy, aplastic anemia.
    // Critical low < 2.0: severe infection risk, consider protective isolation.
    // Critical high > 30.0: evaluate for leukemia, severe infection, or leukemoid reaction.
    // Wallach 10th ed, p 366; Fischbach 10th ed, p 60.
    if test == "WBC" { return lab("WBC", "x10^3/uL", 4.5, 11.0, 2.0, 30.0, "total_white_blood_cell_count. leukocytosis: infection_inflammation_stress_steroids_CML. leukopenia: marrow_failure_viral_chemo_aplastic", "Wallach 10th ed p366; Fischbach 10th ed p60") }

    // RBC male: red blood cell count. Oxygen-carrying capacity.
    // Low: anemia (iron deficiency, B12/folate, chronic disease, hemolysis, bleeding).
    // High: polycythemia vera, dehydration, chronic hypoxia (COPD, high altitude).
    // Wallach 10th ed, p 368; Fischbach 10th ed, p 63.
    if test == "RBC_male" { return lab("RBC (male)", "x10^6/uL", 4.5, 5.5, 2.5, 8.0, "red_cell_count_male. low: anemia. high: polycythemia_vera_dehydration_chronic_hypoxia", "Wallach 10th ed p368") }

    // RBC female: lower reference range due to menstruation and lower androgen levels.
    if test == "RBC_female" { return lab("RBC (female)", "x10^6/uL", 4.0, 5.0, 2.5, 8.0, "red_cell_count_female. lower_range_than_male_due_to_menses_and_lower_androgens", "Wallach 10th ed p368") }

    // Hemoglobin male: primary oxygen-carrying protein in RBCs.
    // Each gram carries 1.34 mL O2. Critical low < 7.0 = transfusion threshold.
    // Critical high > 20.0 = hyperviscosity risk.
    // Wallach 10th ed, p 370; Fischbach 10th ed, p 65.
    if test == "hemoglobin_male" { return lab("Hemoglobin (male)", "g/dL", 13.5, 17.5, 7.0, 20.0, "O2_carrying_protein. each_gram_carries_1.34mL_O2. low: anemia. high: polycythemia_dehydration", "Wallach 10th ed p370; Fischbach 10th ed p65") }

    // Hemoglobin female
    if test == "hemoglobin_female" { return lab("Hemoglobin (female)", "g/dL", 12.0, 16.0, 7.0, 20.0, "O2_carrying_protein_female. lower_range_reflects_lower_erythropoietin_and_menses", "Wallach 10th ed p370") }

    // Hematocrit male: percentage of blood volume occupied by RBCs.
    // Approximately three times the hemoglobin value.
    // Critical low < 20%: severe anemia, consider transfusion.
    // Critical high > 60%: hyperviscosity, stroke risk, phlebotomy needed.
    // Wallach 10th ed, p 372; Fischbach 10th ed, p 67.
    if test == "hematocrit_male" { return lab("Hematocrit (male)", "%", 38.0, 50.0, 20.0, 60.0, "packed_cell_volume_male. approximately_3x_hemoglobin. high: polycythemia_dehydration. low: anemia_bleeding", "Wallach 10th ed p372") }

    // Hematocrit female
    if test == "hematocrit_female" { return lab("Hematocrit (female)", "%", 36.0, 44.0, 20.0, 60.0, "packed_cell_volume_female. lower_range_than_male", "Wallach 10th ed p372") }

    // MCV: mean corpuscular volume. Size of the average red cell.
    // Microcytic (< 80): iron deficiency, thalassemia, sideroblastic, lead poisoning.
    // Normocytic (80-100): acute blood loss, anemia of chronic disease, mixed deficiency.
    // Macrocytic (> 100): B12/folate deficiency, liver disease, hypothyroidism, MDS, alcohol.
    // Wallach 10th ed, p 374; Fischbach 10th ed, p 70.
    if test == "MCV" { return lab("MCV", "fL", 80.0, 100.0, 60.0, 120.0, "mean_corpuscular_volume. microcytic: iron_def_thalassemia_lead. normocytic: chronic_disease_acute_bleed. macrocytic: B12_folate_liver_MDS_alcohol", "Wallach 10th ed p374") }

    // MCH: mean corpuscular hemoglobin. Average hemoglobin per red cell.
    // Parallels MCV. Low in microcytic anemias, high in macrocytic anemias.
    // Wallach 10th ed, p 376.
    if test == "MCH" { return lab("MCH", "pg", 27.0, 33.0, 20.0, 40.0, "mean_corpuscular_hemoglobin. average_Hgb_per_RBC. parallels_MCV_in_classification", "Wallach 10th ed p376") }

    // MCHC: mean corpuscular hemoglobin concentration. Hemoglobin concentration in RBCs.
    // Low: hypochromic (iron deficiency). High: hyperchromic (spherocytosis, severe dehydration).
    // MCHC > 36 is almost pathognomonic for hereditary spherocytosis.
    // Wallach 10th ed, p 376; Fischbach 10th ed, p 72.
    if test == "MCHC" { return lab("MCHC", "g/dL", 32.0, 36.0, 28.0, 40.0, "hemoglobin_concentration_in_RBCs. low: hypochromic_iron_def. high_above_36: hereditary_spherocytosis_nearly_pathognomonic", "Wallach 10th ed p376") }

    // RDW: red cell distribution width. Measure of anisocytosis (variation in RBC size).
    // Elevated RDW with low MCV: iron deficiency (vs thalassemia trait which has normal RDW).
    // This is the Mentzer index concept. Elevated RDW = mixed population of cell sizes.
    // Wallach 10th ed, p 378.
    if test == "RDW" { return lab("RDW", "%", 11.5, 14.5, 0.0, 25.0, "red_cell_distribution_width. measures_anisocytosis. elevated_RDW_low_MCV: iron_deficiency. normal_RDW_low_MCV: thalassemia_trait", "Wallach 10th ed p378") }

    // Platelets: essential for primary hemostasis (platelet plug formation).
    // Thrombocytopenia (< 150): ITP, TTP, HIT, DIC, marrow failure, splenomegaly.
    // Thrombocytosis (> 400): reactive (infection, inflammation, iron def) or essential thrombocythemia.
    // Critical low < 50: spontaneous bleeding risk. < 10: life-threatening hemorrhage.
    // Critical high > 1000: thrombosis risk, evaluate for myeloproliferative disorder.
    // Wallach 10th ed, p 384; Fischbach 10th ed, p 74.
    if test == "platelets" { return lab("Platelets", "x10^3/uL", 150.0, 400.0, 50.0, 1000.0, "primary_hemostasis. low: ITP_TTP_HIT_DIC_marrow_failure. high: reactive_or_essential_thrombocythemia. below_10: life_threatening", "Wallach 10th ed p384") }

    // MPV: mean platelet volume. Marker of platelet production.
    // High MPV: young platelets (ITP, recovery from thrombocytopenia -- marrow responding).
    // Low MPV: marrow failure (aplastic anemia, chemo -- marrow not responding).
    // Fischbach 10th ed, p 76.
    if test == "MPV" { return lab("MPV", "fL", 7.5, 11.5, 0.0, 15.0, "mean_platelet_volume. high: young_platelets_ITP_marrow_responding. low: marrow_failure_not_responding", "Fischbach 10th ed p76") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}


// ═══════════════════════════════════════════════════════════════
// SECTION TWO: WBC DIFFERENTIAL
// ═══════════════════════════════════════════════════════════════
//
// The differential classifies leukocytes into five categories.
// Each lineage responds to different pathologic stimuli.
// Reported as both percentage and absolute count (% x WBC).
//
// Wallach 10th ed, pp 386-392; Fischbach 10th ed, pp 78-84.

fn lookup_wbc_differential(cell: String) -> LabTest {
    // Neutrophils (segmented): first responders to bacterial infection.
    // Neutrophilia (> 70%): bacterial infection, steroids, stress, CML, burns.
    // Neutropenia (< 40%): viral infection, drugs, autoimmune, aplastic anemia.
    // ANC < 500 = severe neutropenia, febrile neutropenia protocol required.
    // Wallach 10th ed, p 386.
    if cell == "neutrophils" { return lab("Neutrophils (segs)", "%", 40.0, 70.0, 0.0, 100.0, "first_responders_bacterial_infection. high: bacterial_infection_steroids_stress_CML. low: viral_drugs_autoimmune_aplastic", "Wallach 10th ed p386") }

    // Lymphocytes: adaptive immunity. T cells and B cells.
    // Lymphocytosis (> 40%): viral infection (EBV, CMV, HIV), CLL, pertussis.
    // Lymphopenia (< 20%): HIV/AIDS, steroids, chemotherapy, radiation.
    // Wallach 10th ed, p 388.
    if cell == "lymphocytes" { return lab("Lymphocytes", "%", 20.0, 40.0, 0.0, 100.0, "adaptive_immunity_T_and_B_cells. high: viral_EBV_CMV_HIV_CLL_pertussis. low: HIV_steroids_chemo_radiation", "Wallach 10th ed p388") }

    // Monocytes: tissue macrophage precursors. Chronic inflammation markers.
    // Monocytosis: chronic infection (TB, endocarditis), autoimmune, CMML.
    // Wallach 10th ed, p 390.
    if cell == "monocytes" { return lab("Monocytes", "%", 2.0, 8.0, 0.0, 100.0, "macrophage_precursors. high: chronic_infection_TB_endocarditis_autoimmune_CMML", "Wallach 10th ed p390") }

    // Eosinophils: parasitic infection and allergic response.
    // Eosinophilia: parasites, allergy, asthma, drug reactions, Churg-Strauss,
    // hypereosinophilic syndrome, Hodgkin lymphoma.
    // Wallach 10th ed, p 390.
    if cell == "eosinophils" { return lab("Eosinophils", "%", 1.0, 4.0, 0.0, 100.0, "parasites_and_allergy. high: NAACP_mnemonic_Neoplasm_Allergy_Addisons_Collagen_vascular_Parasites", "Wallach 10th ed p390") }

    // Basophils: rarest WBC. IgE-mediated responses, histamine release.
    // Basophilia: CML (characteristic finding), allergic reactions, myeloproliferative disorders.
    // Wallach 10th ed, p 392.
    if cell == "basophils" { return lab("Basophils", "%", 0.0, 1.0, 0.0, 100.0, "IgE_mediated_histamine_release. high: CML_characteristic_allergic_myeloproliferative", "Wallach 10th ed p392") }

    // Bands (immature neutrophils): left shift marker.
    // Bandemia (> 5%): acute bacterial infection, sepsis, severe inflammation.
    // "Left shift" = increase in immature neutrophil forms = marrow stress response.
    // Wallach 10th ed, p 386.
    if cell == "bands" { return lab("Bands (immature neutrophils)", "%", 0.0, 5.0, 0.0, 100.0, "left_shift_marker. above_5pct: acute_bacterial_infection_sepsis_severe_inflammation. bandemia_indicates_marrow_stress", "Wallach 10th ed p386") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}


// ═══════════════════════════════════════════════════════════════
// CBC CALCULATIONS
// ═══════════════════════════════════════════════════════════════

// ANC: absolute neutrophil count.
// ANC = WBC x (segs% + bands%) / 100
// ANC < 1500: neutropenia. ANC < 500: severe. ANC < 100: profound.
// Febrile neutropenia (ANC < 500 + fever > 38.3C) = medical emergency.
// Fischbach 10th ed, p 82.
fn calculate_anc(wbc: Float, segs_pct: Float, bands_pct: Float) -> Float {
    return wbc * (segs_pct + bands_pct) / 100.0
}

fn classify_anc(anc: Float) -> String {
    if anc >= 1500.0 { return "normal" }
    if anc >= 1000.0 { return "mild_neutropenia" }
    if anc >= 500.0 { return "moderate_neutropenia" }
    if anc >= 100.0 { return "severe_neutropenia" }
    return "profound_neutropenia_life_threatening"
}

// Reticulocyte production index (RPI).
// Corrects reticulocyte count for degree of anemia.
// RPI = reticulocyte% x (patient Hct / normal Hct) / maturation factor
// Maturation factor: Hct 45%=1.0, 35%=1.5, 25%=2.0, 15%=2.5
// RPI > 2: adequate marrow response (hemolysis, bleeding).
// RPI < 2: inadequate response (marrow failure, nutritional deficiency).
// Wallach 10th ed, p 380.
fn reticulocyte_maturation_factor(hct: Float) -> Float {
    if hct >= 40.0 { return 1.0 }
    if hct >= 30.0 { return 1.5 }
    if hct >= 20.0 { return 2.0 }
    return 2.5
}

fn calculate_rpi(retic_pct: Float, patient_hct: Float, normal_hct: Float) -> Float {
    let mf: Float = reticulocyte_maturation_factor(patient_hct)
    return retic_pct * (patient_hct / normal_hct) / mf
}

fn classify_rpi(rpi: Float) -> String {
    if rpi >= 2.0 { return "adequate_marrow_response_hemolysis_or_bleeding" }
    return "inadequate_marrow_response_production_defect"
}

fn cbc_test_count() -> Int {
    return 14
}

fn wbc_differential_count() -> Int {
    return 6
}


// ═══════════════════════════════════════════════════════════════
// SECTION THREE: COMPREHENSIVE METABOLIC PANEL (CMP)
// ═══════════════════════════════════════════════════════════════
//
// The CMP is the metabolic snapshot: glucose, electrolytes, renal
// function, and hepatic function in a single draw. Fourteen analytes
// that together reveal dehydration, kidney injury, liver damage,
// electrolyte derangement, and acid-base disturbance.
//
// Wallach 10th ed, Ch 3-4; Fischbach 10th ed, Ch 6.

fn lookup_cmp(test: String) -> LabTest {
    // Glucose (fasting): primary fuel for brain and RBCs.
    // Hypoglycemia (< 70): insulin excess, sulfonylureas, insulinoma, adrenal insufficiency.
    // Hyperglycemia (> 100 fasting): diabetes, stress response, steroids, Cushing.
    // Critical low < 40: seizures, coma, death. Critical high > 500: DKA or HHS.
    // Wallach 10th ed, p 49; Fischbach 10th ed, p 208.
    if test == "glucose" { return lab("Glucose (fasting)", "mg/dL", 70.0, 100.0, 40.0, 500.0, "primary_brain_fuel. low: insulin_excess_insulinoma_adrenal_insufficiency. high: diabetes_stress_steroids_Cushing. critical_low: seizures_coma", "Wallach 10th ed p49; Fischbach 10th ed p208") }

    // BUN: blood urea nitrogen. End product of protein catabolism.
    // Elevated: dehydration (prerenal), renal failure, GI bleed, high protein diet, catabolic states.
    // Low: liver failure (cannot make urea), malnutrition, overhydration, pregnancy.
    // Wallach 10th ed, p 97; Fischbach 10th ed, p 223.
    if test == "BUN" { return lab("BUN", "mg/dL", 7.0, 20.0, 2.0, 100.0, "urea_nitrogen. high: dehydration_renal_failure_GI_bleed_catabolism. low: liver_failure_malnutrition_overhydration", "Wallach 10th ed p97; Fischbach 10th ed p223") }

    // Creatinine: byproduct of muscle creatine phosphate metabolism.
    // Filtered by glomerulus, not reabsorbed. Better GFR marker than BUN.
    // Elevated: renal insufficiency (acute or chronic), rhabdomyolysis, muscle mass (falsely elevated).
    // Low: muscle wasting, liver disease, pregnancy.
    // Critical high > 10.0: dialysis may be indicated.
    // Wallach 10th ed, p 99; Fischbach 10th ed, p 225.
    if test == "creatinine" { return lab("Creatinine", "mg/dL", 0.7, 1.3, 0.2, 10.0, "GFR_marker. high: renal_insufficiency_rhabdomyolysis. low: muscle_wasting_liver_disease. critical_high: dialysis_consideration", "Wallach 10th ed p99; Fischbach 10th ed p225") }

    // Sodium: primary extracellular cation. Controls osmolality and water balance.
    // Hyponatremia (< 136): SIADH, CHF, cirrhosis, diuretics, psychogenic polydipsia.
    // Hypernatremia (> 145): dehydration, diabetes insipidus, osmotic diuresis.
    // Critical low < 120: cerebral edema, seizures. Critical high > 160: CNS hemorrhage.
    // Wallach 10th ed, p 104; Fischbach 10th ed, p 230.
    if test == "sodium" { return lab("Sodium", "mEq/L", 136.0, 145.0, 120.0, 160.0, "primary_extracellular_cation. low: SIADH_CHF_cirrhosis_diuretics. high: dehydration_DI_osmotic_diuresis. critical_low: cerebral_edema_seizures", "Wallach 10th ed p104; Fischbach 10th ed p230") }

    // Potassium: primary intracellular cation. Critical for cardiac conduction.
    // Hypokalemia (< 3.5): diuretics, vomiting, diarrhea, alkalosis, renal tubular acidosis.
    // Hyperkalemia (> 5.0): renal failure, ACEi/ARB, K-sparing diuretics, acidosis, hemolysis (artifact).
    // Critical low < 2.5: cardiac arrest (torsades). Critical high > 6.5: cardiac arrest (Vfib).
    // POTASSIUM IS THE MOST DANGEROUS ELECTROLYTE.
    // Wallach 10th ed, p 106; Fischbach 10th ed, p 232.
    if test == "potassium" { return lab("Potassium", "mEq/L", 3.5, 5.0, 2.5, 6.5, "MOST_DANGEROUS_ELECTROLYTE. low: diuretics_vomiting_diarrhea_alkalosis. high: renal_failure_ACEi_acidosis. both_extremes: cardiac_arrest", "Wallach 10th ed p106; Fischbach 10th ed p232") }

    // Chloride: primary extracellular anion. Follows sodium in most cases.
    // Hyperchloremia: normal anion gap metabolic acidosis (diarrhea, RTA, NS infusion).
    // Hypochloremia: vomiting (HCl loss), metabolic alkalosis, diuretics.
    // Wallach 10th ed, p 108; Fischbach 10th ed, p 234.
    if test == "chloride" { return lab("Chloride", "mEq/L", 98.0, 106.0, 80.0, 120.0, "primary_extracellular_anion. follows_sodium. high: normal_AG_metabolic_acidosis. low: vomiting_metabolic_alkalosis", "Wallach 10th ed p108; Fischbach 10th ed p234") }

    // CO2/Bicarbonate: metabolic component of acid-base.
    // Low: metabolic acidosis (DKA, lactic acidosis, renal failure, diarrhea).
    // High: metabolic alkalosis (vomiting, diuretics, Cushing), respiratory compensation for chronic respiratory acidosis.
    // Wallach 10th ed, p 110; Fischbach 10th ed, p 236.
    if test == "CO2" { return lab("CO2 (Bicarbonate)", "mEq/L", 22.0, 29.0, 10.0, 40.0, "metabolic_acid_base_component. low: metabolic_acidosis_DKA_lactic_renal. high: metabolic_alkalosis_vomiting_diuretics", "Wallach 10th ed p110; Fischbach 10th ed p236") }

    // Calcium: critical for muscle contraction, coagulation, bone metabolism, nerve function.
    // Hypocalcemia (< 8.5): hypoparathyroidism, vitamin D deficiency, renal failure, pancreatitis.
    // Hypercalcemia (> 10.5): hyperparathyroidism, malignancy (PTHrP, bone mets, myeloma), granulomatous disease.
    // Critical low < 6.5: tetany, laryngospasm, seizures. Critical high > 13.0: cardiac arrest, coma.
    // Corrected calcium = measured + 0.8 x (4.0 - albumin).
    // Wallach 10th ed, p 112; Fischbach 10th ed, p 240.
    if test == "calcium" { return lab("Calcium (total)", "mg/dL", 8.5, 10.5, 6.5, 13.0, "muscle_nerve_bone_coagulation. low: hypoparathyroidism_vitD_def_renal_failure_pancreatitis. high: hyperPTH_malignancy_granulomatous. always_correct_for_albumin", "Wallach 10th ed p112; Fischbach 10th ed p240") }

    // Total protein: albumin + globulins. Nutritional and immune status marker.
    // Low: malnutrition, liver failure, nephrotic syndrome, burns, protein-losing enteropathy.
    // High: dehydration (hemoconcentration), multiple myeloma, chronic inflammation.
    // Wallach 10th ed, p 114.
    if test == "total_protein" { return lab("Total Protein", "g/dL", 6.0, 8.3, 3.0, 12.0, "albumin_plus_globulins. low: malnutrition_liver_failure_nephrotic. high: dehydration_myeloma_chronic_inflammation", "Wallach 10th ed p114") }

    // Albumin: most abundant plasma protein. Oncotic pressure, transport, nutrition marker.
    // Low: liver failure (decreased synthesis), nephrotic syndrome (urinary loss),
    // malnutrition, burns, sepsis (capillary leak), protein-losing enteropathy.
    // Half-life approximately twenty days -- slow to reflect acute changes.
    // Prealbumin (transthyretin, half-life two days) is better for acute nutrition.
    // Wallach 10th ed, p 116; Fischbach 10th ed, p 244.
    if test == "albumin" { return lab("Albumin", "g/dL", 3.5, 5.5, 1.5, 7.0, "oncotic_pressure_transport_nutrition. low: liver_failure_nephrotic_malnutrition_sepsis_burns. half_life_20_days. prealbumin_better_for_acute_nutrition", "Wallach 10th ed p116; Fischbach 10th ed p244") }

    // Total bilirubin: heme degradation product. Conjugated in liver, excreted in bile.
    // Elevated: hemolysis (indirect), hepatocellular damage (mixed), biliary obstruction (direct).
    // Jaundice visible at approximately 2.5 mg/dL.
    // Neonatal: critical high varies by age in hours (Bhutani nomogram).
    // Wallach 10th ed, p 122; Fischbach 10th ed, p 248.
    if test == "total_bilirubin" { return lab("Total Bilirubin", "mg/dL", 0.1, 1.2, 0.0, 15.0, "heme_degradation_product. high: hemolysis_indirect_hepatocellular_mixed_obstruction_direct. jaundice_visible_at_2.5", "Wallach 10th ed p122; Fischbach 10th ed p248") }

    // ALP: alkaline phosphatase. Present in liver (biliary epithelium), bone, placenta, intestine.
    // Elevated: biliary obstruction, cholestasis, bone disease (Paget, mets, fracture healing),
    // pregnancy (placental isoenzyme), growing children (physiologic).
    // Isolated elevation: check GGT to confirm hepatic origin (GGT elevated = liver, GGT normal = bone).
    // Wallach 10th ed, p 128; Fischbach 10th ed, p 256.
    if test == "ALP" { return lab("Alkaline Phosphatase", "IU/L", 44.0, 147.0, 0.0, 1000.0, "biliary_bone_marker. high: biliary_obstruction_cholestasis_Paget_bone_mets_pregnancy. check_GGT_to_differentiate_liver_vs_bone", "Wallach 10th ed p128; Fischbach 10th ed p256") }

    // AST (SGOT): present in liver, heart, skeletal muscle, kidney, RBCs.
    // Less specific for liver than ALT. Elevated in MI (before troponin era), rhabdomyolysis.
    // Hepatocellular injury: ALT > AST (viral hepatitis, NAFLD).
    // Alcoholic liver disease: AST:ALT > 2:1 (B6 depletion impairs ALT synthesis).
    // Wallach 10th ed, p 124; Fischbach 10th ed, p 252.
    if test == "AST" { return lab("AST (SGOT)", "IU/L", 10.0, 40.0, 0.0, 1000.0, "liver_heart_muscle. less_specific_than_ALT_for_liver. AST_gt_ALT_2to1: alcoholic_liver. ALT_gt_AST: viral_hepatitis_NAFLD", "Wallach 10th ed p124; Fischbach 10th ed p252") }

    // ALT (SGPT): most specific liver enzyme. Cytoplasmic -- released with hepatocyte damage.
    // Elevated: viral hepatitis, NAFLD/NASH, drug-induced liver injury, autoimmune hepatitis.
    // Very high (> 1000): acute viral hepatitis, ischemic hepatitis (shock liver), acetaminophen toxicity.
    // Wallach 10th ed, p 126; Fischbach 10th ed, p 254.
    if test == "ALT" { return lab("ALT (SGPT)", "IU/L", 7.0, 56.0, 0.0, 1000.0, "most_specific_liver_enzyme. high: viral_hep_NAFLD_NASH_drug_injury_autoimmune. very_high_gt_1000: acute_viral_ischemic_acetaminophen", "Wallach 10th ed p126; Fischbach 10th ed p254") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

fn cmp_test_count() -> Int {
    return 14
}


// ═══════════════════════════════════════════════════════════════
// CMP CALCULATIONS
// ═══════════════════════════════════════════════════════════════

// Anion gap: Na - (Cl + HCO3). Normal 8-12 mEq/L.
// Elevated AG metabolic acidosis (MUDPILES):
// Methanol, Uremia, DKA, Propylene glycol, INH/Iron, Lactic acidosis,
// Ethylene glycol, Salicylates.
// Normal AG (hyperchloremic) metabolic acidosis: diarrhea, RTA, acetazolamide.
// Fischbach 10th ed, p 238.
fn calculate_anion_gap(na: Float, cl: Float, hco3: Float) -> Float {
    return na - (cl + hco3)
}

fn classify_anion_gap(ag: Float) -> String {
    if ag < 8.0 { return "low_anion_gap: hypoalbuminemia_lithium_bromide_or_lab_error" }
    if ag <= 12.0 { return "normal_anion_gap" }
    if ag <= 20.0 { return "mildly_elevated: consider_MUDPILES" }
    return "significantly_elevated: DKA_lactic_acidosis_toxic_ingestion_uremia"
}

// Corrected calcium: adjusts total calcium for albumin.
// For every 1 g/dL albumin below 4.0, calcium is 0.8 mg/dL higher than measured.
// Formula: corrected Ca = measured Ca + 0.8 x (4.0 - albumin)
// Only needed when albumin < 4.0. If albumin is normal, correction is unnecessary.
// Wallach 10th ed, p 113.
fn calculate_corrected_calcium(measured_ca: Float, albumin: Float) -> Float {
    return measured_ca + 0.8 * (4.0 - albumin)
}

// BUN/Creatinine ratio: differentiates prerenal from intrinsic renal failure.
// > 20:1 prerenal (dehydration, CHF, GI bleed -- urea reabsorbed in concentrated urine).
// Ratio ten-to-twenty to one is normal.
// < 10:1 intrinsic renal (ATN -- tubular damage prevents urea reabsorption),
// liver disease (decreased urea synthesis), malnutrition, rhabdomyolysis.
// Wallach 10th ed, p 100.
fn calculate_bun_creatinine_ratio(bun: Float, creatinine: Float) -> Float {
    if creatinine <= 0.0 { return 0.0 }
    return bun / creatinine
}

fn classify_bun_creatinine_ratio(ratio: Float) -> String {
    if ratio > 20.0 { return "prerenal: dehydration_CHF_GI_bleed_catabolic_state" }
    if ratio >= 10.0 { return "normal_ratio" }
    return "intrinsic_renal_or_liver_disease_or_malnutrition"
}

// Estimated GFR (CKD-EPI 2021 equation, race-free).
// Simplified for Scyla: uses creatinine, age, and sex.
// Full CKD-EPI uses natural log transformations. Here we provide the linear
// approximation: eGFR ~ 142 x min(Cr/kappa, 1)^alpha x max(Cr/kappa, 1)^-1.200 x 0.9938^age x (1.012 if female)
// where kappa = 0.7 (F) or 0.9 (M), alpha = -0.241 (F) or -0.302 (M)
// For a quick screening estimate when full math unavailable:
// Cockcroft-Gault: CrCl = [(140 - age) x weight(kg)] / [72 x Cr] x 0.85 if female
// Wallach 10th ed, p 101; Fischbach 10th ed, p 226.
fn calculate_cockcroft_gault(age: Float, weight_kg: Float, creatinine: Float, is_female: Bool) -> Float {
    if creatinine <= 0.0 { return 0.0 }
    let base: Float = (140.0 - age) * weight_kg / (72.0 * creatinine)
    if is_female { return base * 0.85 }
    return base
}

fn classify_gfr(gfr: Float) -> String {
    if gfr >= 90.0 { return "G1_normal_or_high" }
    if gfr >= 60.0 { return "G2_mildly_decreased" }
    if gfr >= 45.0 { return "G3a_mild_to_moderate_decrease" }
    if gfr >= 30.0 { return "G3b_moderate_to_severe_decrease" }
    if gfr >= 15.0 { return "G4_severely_decreased" }
    return "G5_kidney_failure_dialysis_indicated"
}

// Osmolality calculation.
// Serum osmolality = 2(Na) + glucose/18 + BUN/2.8
// Normal: 275-295 mOsm/kg.
// Osmolar gap = measured - calculated. Gap > 10: methanol, ethylene glycol, ethanol, mannitol.
// Wallach 10th ed, p 105.
fn calculate_serum_osmolality(na: Float, glucose: Float, bun: Float) -> Float {
    return 2.0 * na + glucose / 18.0 + bun / 2.8
}

fn classify_osmolality(osm: Float) -> String {
    if osm < 275.0 { return "hypo_osmolar: SIADH_water_intoxication_hypothyroidism" }
    if osm <= 295.0 { return "normal_osmolality" }
    return "hyperosmolar: dehydration_DKA_HHS_mannitol_DI"
}


// ═══════════════════════════════════════════════════════════════
// SECTION FOUR: LIVER FUNCTION TESTS (LFTs) -- PATTERN ANALYSIS
// ═══════════════════════════════════════════════════════════════
//
// Individual liver enzymes are in the CMP section above.
// This section encodes the PATTERNS that distinguish hepatocellular
// injury from cholestatic injury from mixed, and the R-factor
// for drug-induced liver injury (DILI) classification.
//
// Wallach 10th ed, Ch 8: Hepatic Disorders.
// Fischbach 10th ed, Ch 12: Liver Function Tests.

fn lookup_lft_pattern(name: String) -> LabPattern {
    // Hepatocellular pattern: ALT predominates over ALP.
    // ALT and AST dramatically elevated (often > 300-1000 IU/L).
    // ALP mildly elevated or normal.
    // Causes: viral hepatitis (A, B, C, D, E), NAFLD/NASH, drug-induced hepatocellular injury
    // (acetaminophen, isoniazid, statins), autoimmune hepatitis, Wilson disease, ischemic hepatitis.
    // Wallach 10th ed, p 260.
    if name == "hepatocellular" { return pattern("Hepatocellular pattern", "liver_injury", "ALT > AST and ALT disproportionately elevated relative to ALP", "hepatocyte_damage_predominates. transaminases_often_300_to_1000_plus", "viral_hepatitis_ABCDE_NAFLD_NASH_acetaminophen_isoniazid_autoimmune_Wilson_ischemic", "Wallach 10th ed p260") }

    // Cholestatic pattern: ALP predominates over ALT.
    // ALP markedly elevated. GGT elevated (confirms hepatic origin of ALP).
    // Direct bilirubin elevated. ALT mildly elevated or normal.
    // Causes: biliary obstruction (stones, tumor, stricture), PBC, PSC, drug-induced cholestasis
    // (augmentin, erythromycin, oral contraceptives, anabolic steroids).
    // Wallach 10th ed, p 262.
    if name == "cholestatic" { return pattern("Cholestatic pattern", "liver_injury", "ALP disproportionately elevated relative to ALT. GGT elevated confirms hepatic origin", "biliary_obstruction_or_intrahepatic_cholestasis. direct_bilirubin_elevated", "gallstones_pancreatic_head_tumor_cholangiocarcinoma_PBC_PSC_drug_induced", "Wallach 10th ed p262") }

    // Alcoholic pattern: AST:ALT ratio > 2:1.
    // Classic finding in alcoholic hepatitis. AST usually < 300 (rarely > 500).
    // Mechanism: alcohol depletes pyridoxal-5-phosphate (B6), which is the
    // cofactor for ALT synthesis. AST uses a different cofactor pathway.
    // Also see elevated GGT (enzyme induction by alcohol) and elevated MCV.
    // Wallach 10th ed, p 264.
    if name == "alcoholic" { return pattern("Alcoholic liver pattern", "liver_injury", "AST:ALT ratio > 2:1. AST usually < 300 IU/L. Elevated GGT and MCV", "alcohol_depletes_B6_cofactor_for_ALT_synthesis. AST_unaffected", "alcoholic_hepatitis_alcoholic_cirrhosis. GGT_elevated_by_enzyme_induction", "Wallach 10th ed p264") }

    // Mixed hepatocellular-cholestatic pattern.
    // Both transaminases and ALP significantly elevated.
    // Causes: drug-induced liver injury (mixed type), infiltrative disease,
    // granulomatous hepatitis (sarcoidosis, TB), cholestatic hepatitis.
    // Wallach 10th ed, p 266.
    if name == "mixed" { return pattern("Mixed hepatocellular-cholestatic", "liver_injury", "Both ALT and ALP significantly elevated without clear predominance", "overlapping_hepatocellular_and_cholestatic_mechanisms", "drug_induced_mixed_type_infiltrative_granulomatous_sarcoid_TB", "Wallach 10th ed p266") }

    return pattern("", "", "", "", "", "")
}

// R-factor (R-value) for Drug-Induced Liver Injury (DILI) classification.
// R = (ALT / ALT_ULN) / (ALP / ALP_ULN)
// R > 5: hepatocellular DILI (acetaminophen, isoniazid, diclofenac)
// R 2-5: mixed DILI
// R < 2: cholestatic DILI (amoxicillin-clavulanate, erythromycin)
// ALT ULN = 40 IU/L (commonly used), ALP ULN = 120 IU/L (commonly used).
// Wallach 10th ed, p 268.
fn calculate_r_factor(alt: Float, alt_uln: Float, alp: Float, alp_uln: Float) -> Float {
    if alp_uln <= 0.0 { return 0.0 }
    if alt_uln <= 0.0 { return 0.0 }
    let alp_ratio: Float = alp / alp_uln
    if alp_ratio <= 0.0 { return 0.0 }
    return (alt / alt_uln) / alp_ratio
}

fn classify_r_factor(r: Float) -> String {
    if r > 5.0 { return "hepatocellular_DILI: acetaminophen_isoniazid_diclofenac_statins" }
    if r >= 2.0 { return "mixed_DILI: phenytoin_sulfonamides_nitrofurantoin" }
    return "cholestatic_DILI: amoxicillin_clavulanate_erythromycin_oral_contraceptives"
}

// MELD score: Model for End-Stage Liver Disease. Used for transplant prioritization.
// MELD = 3.78 x ln(bilirubin mg/dL) + 11.2 x ln(INR) + 9.57 x ln(creatinine mg/dL) + 6.43
// Minimum value for each variable = 1.0. Maximum creatinine = 4.0.
// MELD cap = 40.
// MELD-Na adds sodium correction for hyponatremia.
// Wallach 10th ed, p 270.
fn classify_meld(meld: Float) -> String {
    if meld < 10.0 { return "mild_liver_disease_low_mortality" }
    if meld < 20.0 { return "moderate_liver_disease" }
    if meld < 30.0 { return "severe_liver_disease_high_transplant_priority" }
    return "very_severe_liver_disease_highest_priority"
}

fn lft_pattern_count() -> Int {
    return 4
}


// ═══════════════════════════════════════════════════════════════
// SECTION FIVE: COAGULATION PANEL
// ═══════════════════════════════════════════════════════════════
//
// Coagulation tests measure the extrinsic pathway (PT/INR),
// intrinsic pathway (PTT), common pathway (thrombin time),
// and fibrinolysis (D-dimer, fibrinogen). These are the tests
// that guide anticoagulation, diagnose DIC, and screen for
// bleeding disorders.
//
// Wallach 10th ed, Ch 11; Fischbach 10th ed, Ch 3.

fn lookup_coagulation(test: String) -> LabTest {
    // PT: prothrombin time. Measures extrinsic pathway (factors VII, X, V, II, fibrinogen).
    // Prolonged: warfarin, liver disease, vitamin K deficiency, DIC, factor VII deficiency.
    // The PT is the test used to monitor warfarin therapy (reported as INR).
    // Wallach 10th ed, p 398; Fischbach 10th ed, p 130.
    if test == "PT" { return lab("Prothrombin Time", "seconds", 11.0, 13.5, 0.0, 30.0, "extrinsic_pathway_VII_X_V_II_fibrinogen. prolonged: warfarin_liver_disease_vitamin_K_def_DIC_factor_VII_def", "Wallach 10th ed p398; Fischbach 10th ed p130") }

    // INR: international normalized ratio. Standardized PT across reagent lots.
    // INR = (patient PT / mean normal PT) ^ ISI
    // Normal: 0.8-1.1. Therapeutic on warfarin: 2.0-3.0 (most indications),
    // Range 2.5-3.5 for mechanical heart valves.
    // Supratherapeutic > 4.0: bleeding risk. > 9.0: major hemorrhage risk, give vitamin K.
    // Wallach 10th ed, p 399; Fischbach 10th ed, p 132.
    if test == "INR" { return lab("INR", "ratio", 0.8, 1.1, 0.0, 9.0, "standardized_PT. therapeutic_warfarin_2.0_to_3.0. mechanical_valve_2.5_to_3.5. supratherapeutic_gt_4: bleeding_risk", "Wallach 10th ed p399; Fischbach 10th ed p132") }

    // PTT (aPTT): activated partial thromboplastin time. Measures intrinsic pathway
    // (factors XII, XI, IX, VIII) plus common pathway (X, V, II, fibrinogen).
    // Prolonged: heparin therapy, hemophilia A (VIII) or B (IX), vWD, lupus anticoagulant, DIC.
    // PTT is the test used to monitor unfractionated heparin.
    // Wallach 10th ed, p 400; Fischbach 10th ed, p 134.
    if test == "PTT" { return lab("PTT (aPTT)", "seconds", 25.0, 35.0, 0.0, 100.0, "intrinsic_pathway_XII_XI_IX_VIII_plus_common. prolonged: heparin_hemophilia_vWD_lupus_anticoagulant_DIC", "Wallach 10th ed p400; Fischbach 10th ed p134") }

    // Fibrinogen: acute phase reactant and final substrate in coagulation cascade.
    // Factor I. Converted to fibrin by thrombin.
    // Elevated: acute inflammation, infection, pregnancy, malignancy (acute phase).
    // Low: DIC (consumption), liver failure (decreased synthesis), dysfibrinogenemia.
    // Critical low < 100: high bleeding risk. < 50 in DIC: very high bleeding risk.
    // Wallach 10th ed, p 402; Fischbach 10th ed, p 136.
    if test == "fibrinogen" { return lab("Fibrinogen", "mg/dL", 200.0, 400.0, 100.0, 800.0, "factor_I_acute_phase_reactant. low: DIC_consumption_liver_failure. high: inflammation_infection_pregnancy_malignancy", "Wallach 10th ed p402; Fischbach 10th ed p136") }

    // D-dimer: fibrin degradation product. Marker of fibrinolysis.
    // Elevated: PE, DVT, DIC, surgery, trauma, malignancy, pregnancy, inflammation.
    // High sensitivity but low specificity for thromboembolism.
    // Age-adjusted cutoff: age x 10 ng/mL (for patients > 50 years, in FEU assays).
    // Negative D-dimer with low pretest probability effectively rules out PE/DVT.
    // Wallach 10th ed, p 404; Fischbach 10th ed, p 138.
    if test == "d_dimer" { return lab("D-dimer", "ng/mL FEU", 0.0, 500.0, 0.0, 10000.0, "fibrin_degradation_product. high_sensitivity_low_specificity. negative_with_low_pretest_rules_out_PE_DVT. age_adjusted_cutoff: age_x_10", "Wallach 10th ed p404; Fischbach 10th ed p138") }

    // Thrombin time: measures conversion of fibrinogen to fibrin by thrombin.
    // Prolonged: heparin contamination (most common), low fibrinogen, dysfibrinogenemia,
    // high FDPs (DIC), direct thrombin inhibitors (dabigatran, argatroban).
    // Normal thrombin time with prolonged PT/PTT = factor deficiency, not fibrinogen problem.
    // Wallach 10th ed, p 406.
    if test == "thrombin_time" { return lab("Thrombin Time", "seconds", 14.0, 19.0, 0.0, 60.0, "fibrinogen_to_fibrin_conversion. prolonged: heparin_contamination_low_fibrinogen_dysfibrinogenemia_DIC_dabigatran", "Wallach 10th ed p406") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

fn coagulation_test_count() -> Int {
    return 6
}


// ═══════════════════════════════════════════════════════════════
// DIC DIAGNOSTIC CRITERIA
// ═══════════════════════════════════════════════════════════════
//
// Disseminated intravascular coagulation (DIC) is simultaneous
// widespread clotting and bleeding. The coagulation cascade is
// activated diffusely, consuming factors and platelets while
// generating fibrin that is then lysed (elevated D-dimer).
//
// ISTH DIC scoring: platelets, PT, fibrinogen, D-dimer.
// Score >= 5 = overt DIC.
//
// Wallach 10th ed, p 410; Fischbach 10th ed, p 140.

fn lookup_dic_criteria(component: String) -> LabPattern {
    if component == "platelets" { return pattern("DIC - platelet consumption", "DIC_criteria", "platelets < 100 (moderate) or < 50 (severe)", "consumption_by_widespread_microthrombi", "DIC_TTP_HUS_ITP_marrow_failure_splenomegaly", "Wallach 10th ed p410") }
    if component == "PT" { return pattern("DIC - prolonged PT", "DIC_criteria", "PT prolonged > 3 sec above upper normal limit", "consumption_of_factors_VII_X_V_II", "liver_failure_warfarin_vitamin_K_deficiency", "Wallach 10th ed p410") }
    if component == "fibrinogen" { return pattern("DIC - low fibrinogen", "DIC_criteria", "fibrinogen < 100 mg/dL", "consumption_by_thrombin. note: fibrinogen_is_acute_phase_reactant_so_may_be_falsely_normal_early", "liver_failure_congenital_afibrinogenemia_L_asparaginase", "Wallach 10th ed p410") }
    if component == "d_dimer" { return pattern("DIC - elevated D-dimer", "DIC_criteria", "D-dimer markedly elevated (often > 4x ULN)", "extensive_fibrinolysis_of_disseminated_microthrombi", "PE_DVT_surgery_trauma_malignancy_pregnancy", "Wallach 10th ed p410") }
    if component == "schistocytes" { return pattern("DIC - schistocytes on smear", "DIC_criteria", "fragmented RBCs (schistocytes, helmet cells) on peripheral smear", "mechanical_shearing_of_RBCs_through_fibrin_strands_in_microvasculature", "TTP_HUS_HELLP_mechanical_heart_valve_march_hemoglobinuria", "Wallach 10th ed p410") }
    return pattern("", "", "", "", "", "")
}

fn dic_criteria_count() -> Int {
    return 5
}


// ═══════════════════════════════════════════════════════════════
// SECTION SIX: THYROID FUNCTION TESTS
// ═══════════════════════════════════════════════════════════════
//
// The hypothalamic-pituitary-thyroid axis: TRH -> TSH -> T4/T3.
// TSH is the single best screening test. Free T4 confirms.
// Free T3 is useful for T3 thyrotoxicosis and sick euthyroid.
//
// Wallach 10th ed, Ch 13: Endocrine Tests.
// Fischbach 10th ed, Ch 8: Thyroid Function.

fn lookup_thyroid(test: String) -> LabTest {
    // TSH: thyroid-stimulating hormone (thyrotropin). Most sensitive thyroid test.
    // Inverse log-linear relationship with T4: small T4 changes = large TSH changes.
    // High TSH: primary hypothyroidism (Hashimoto, post-thyroidectomy, post-RAI, iodine deficiency).
    // Low TSH: hyperthyroidism (Graves, toxic nodule, thyroiditis, exogenous T4).
    // Central hypothyroidism (pituitary/hypothalamic): TSH inappropriately normal or low with low T4.
    // Wallach 10th ed, p 450; Fischbach 10th ed, p 320.
    if test == "TSH" { return lab("TSH", "mIU/L", 0.4, 4.0, 0.01, 100.0, "most_sensitive_thyroid_screening. high: primary_hypothyroidism_Hashimoto. low: hyperthyroidism_Graves_toxic_nodule. central_hypothyroid: inappropriately_normal_TSH", "Wallach 10th ed p450; Fischbach 10th ed p320") }

    // Free T4: unbound thyroxine. Active hormone fraction (0.03% of total).
    // Low + high TSH: primary hypothyroidism.
    // High + low TSH: hyperthyroidism.
    // Low + low/normal TSH: central hypothyroidism (pituitary failure).
    // Preferred over total T4 because unaffected by TBG changes (pregnancy, OCP, hepatitis).
    // Wallach 10th ed, p 452; Fischbach 10th ed, p 322.
    if test == "free_T4" { return lab("Free T4", "ng/dL", 0.8, 1.8, 0.2, 6.0, "active_thyroxine_unaffected_by_TBG. low_plus_high_TSH: primary_hypothyroid. high_plus_low_TSH: hyperthyroid. low_plus_low_TSH: central_hypothyroid", "Wallach 10th ed p452; Fischbach 10th ed p322") }

    // Free T3: triiodothyronine. Most metabolically active thyroid hormone.
    // T4 is converted to T3 peripherally by deiodinases (type 1 and 2).
    // T3 thyrotoxicosis: elevated T3 with normal T4 (early Graves, toxic nodule).
    // Sick euthyroid (nonthyroidal illness): low T3 with normal TSH and T4 (acute illness
    // inhibits T4-to-T3 conversion; this is appropriate and should NOT be treated).
    // Wallach 10th ed, p 454.
    if test == "free_T3" { return lab("Free T3", "pg/mL", 2.3, 4.2, 1.0, 10.0, "most_metabolically_active. T3_thyrotoxicosis: high_T3_normal_T4. sick_euthyroid: low_T3_is_appropriate_do_NOT_treat", "Wallach 10th ed p454") }

    // Total T4: protein-bound + free T4. Affected by TBG levels.
    // Elevated TBG (increases total T4 but NOT free T4): pregnancy, OCP, estrogen, hepatitis, genetic.
    // Decreased TBG (decreases total T4 but NOT free T4): androgens, nephrotic syndrome, chronic illness.
    // Free T4 is preferred in almost all clinical scenarios.
    // Wallach 10th ed, p 456.
    if test == "total_T4" { return lab("Total T4", "mcg/dL", 4.5, 12.0, 1.0, 25.0, "protein_bound_plus_free. affected_by_TBG: pregnancy_OCP_hepatitis_increase_total_T4. free_T4_preferred_clinically", "Wallach 10th ed p456") }

    // Total T3: mostly protein-bound. Same TBG limitations as total T4.
    // Useful for confirming hyperthyroidism when T3 thyrotoxicosis suspected.
    // Wallach 10th ed, p 458.
    if test == "total_T3" { return lab("Total T3", "ng/dL", 80.0, 200.0, 40.0, 500.0, "mostly_protein_bound. confirms_T3_thyrotoxicosis. same_TBG_limitations_as_total_T4", "Wallach 10th ed p458") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

fn thyroid_test_count() -> Int {
    return 5
}


// ═══════════════════════════════════════════════════════════════
// THYROID PATTERN INTERPRETATION
// ═══════════════════════════════════════════════════════════════

fn lookup_thyroid_pattern(name: String) -> LabPattern {
    // Primary hypothyroidism: high TSH, low free T4.
    // Most common: Hashimoto thyroiditis (autoimmune destruction of thyroid gland).
    // Antibodies: anti-TPO and anti-thyroglobulin.
    // Other causes: post-thyroidectomy, post-radioactive iodine, iodine deficiency (worldwide),
    // lithium, amiodarone (type 2), congenital.
    // Wallach 10th ed, p 460.
    if name == "primary_hypothyroid" { return pattern("Primary hypothyroidism", "thyroid", "high TSH + low free T4", "thyroid_gland_failure. most_common: Hashimoto_thyroiditis_anti_TPO_positive", "Hashimoto_post_thyroidectomy_post_RAI_iodine_deficiency_lithium_amiodarone_congenital", "Wallach 10th ed p460") }

    // Subclinical hypothyroidism: high TSH, normal free T4.
    // Thyroid is failing but still producing enough T4 to maintain normal levels.
    // TSH is elevated because the pituitary detects the subtle decline.
    // Treat if TSH > 10 or if symptomatic or if pregnant/planning pregnancy.
    // Wallach 10th ed, p 462.
    if name == "subclinical_hypothyroid" { return pattern("Subclinical hypothyroidism", "thyroid", "high TSH + normal free T4", "early_thyroid_failure_compensated. pituitary_detects_subtle_T4_decline", "treat_if_TSH_gt_10_or_symptomatic_or_pregnant. monitor_if_mild", "Wallach 10th ed p462") }

    // Primary hyperthyroidism: low TSH, high free T4.
    // Graves disease (diffuse toxic goiter): TSI (thyroid-stimulating immunoglobulin) positive.
    // Toxic multinodular goiter. Toxic adenoma.
    // Thyroiditis (transient): subacute (de Quervain), postpartum, painless.
    // Exogenous thyroid hormone (factitious or iatrogenic).
    // Wallach 10th ed, p 464.
    if name == "primary_hyperthyroid" { return pattern("Primary hyperthyroidism", "thyroid", "low TSH + high free T4", "thyroid_overproduction_or_leakage_or_exogenous", "Graves_TSI_positive_toxic_multinodular_toxic_adenoma_thyroiditis_factitious", "Wallach 10th ed p464") }

    // Subclinical hyperthyroidism: low TSH, normal free T4 and T3.
    // Risk: atrial fibrillation (especially in elderly), accelerated bone loss.
    // Treat if TSH persistently < 0.1 or if age > 65 or if cardiovascular risk factors.
    // Wallach 10th ed, p 466.
    if name == "subclinical_hyperthyroid" { return pattern("Subclinical hyperthyroidism", "thyroid", "low TSH + normal free T4 and free T3", "mild_thyroid_excess_suppressing_TSH", "risk: atrial_fibrillation_in_elderly_bone_loss. treat_if_TSH_lt_0.1_or_age_gt_65", "Wallach 10th ed p466") }

    // T3 thyrotoxicosis: low TSH, normal free T4, high free T3.
    // Early hyperthyroidism where T3 rises before T4.
    // Common in Graves disease and toxic adenoma.
    // Must check T3 if TSH is suppressed but T4 is normal.
    // Wallach 10th ed, p 468.
    if name == "T3_thyrotoxicosis" { return pattern("T3 thyrotoxicosis", "thyroid", "low TSH + normal free T4 + high free T3", "early_hyperthyroidism_T3_rises_before_T4", "Graves_early_toxic_adenoma. always_check_T3_when_TSH_suppressed_with_normal_T4", "Wallach 10th ed p468") }

    // Sick euthyroid (nonthyroidal illness syndrome, NTIS).
    // Low T3, normal or low TSH, normal or low T4.
    // Acute illness inhibits peripheral T4-to-T3 conversion (reduced deiodinase activity).
    // This is an APPROPRIATE adaptive response. DO NOT treat with thyroid hormone.
    // Wallach 10th ed, p 470.
    if name == "sick_euthyroid" { return pattern("Sick euthyroid (NTIS)", "thyroid", "low T3 + normal or low T4 + normal or low TSH", "adaptive_response_to_acute_illness. reduced_peripheral_T4_to_T3_conversion", "DO_NOT_TREAT. resolves_with_recovery_from_underlying_illness", "Wallach 10th ed p470") }

    // Central hypothyroidism: pituitary or hypothalamic failure.
    // Low free T4 with low or inappropriately normal TSH.
    // Causes: pituitary adenoma, Sheehan syndrome, craniopharyngioma, pituitary surgery/radiation.
    // TSH alone will MISS this diagnosis -- must check free T4.
    // Wallach 10th ed, p 472.
    if name == "central_hypothyroid" { return pattern("Central hypothyroidism", "thyroid", "low free T4 + low or inappropriately normal TSH", "pituitary_or_hypothalamic_failure. TSH_cannot_respond_appropriately", "pituitary_adenoma_Sheehan_syndrome_craniopharyngioma_surgery_radiation. TSH_alone_will_MISS_this", "Wallach 10th ed p472") }

    return pattern("", "", "", "", "", "")
}

fn thyroid_pattern_count() -> Int {
    return 7
}


// ═══════════════════════════════════════════════════════════════
// SECTION SEVEN: CARDIAC BIOMARKERS
// ═══════════════════════════════════════════════════════════════
//
// Cardiac biomarkers diagnose myocardial infarction (troponin),
// heart failure (BNP/NT-proBNP), and myocardial damage (CK-MB, LDH).
// Troponin is the gold standard for MI diagnosis.
//
// Wallach 10th ed, Ch 3: Cardiac Markers.
// Fischbach 10th ed, Ch 5: Cardiac Assessment.

fn lookup_cardiac(test: String) -> LabTest {
    // Troponin I: cardiac-specific structural protein. Gold standard for MI diagnosis.
    // Rises 3-6 hours after injury, peaks 12-24 hours, elevated for 7-10 days.
    // Any elevation above 99th percentile with rise/fall pattern = acute MI.
    // Non-MI causes of elevation: PE, myocarditis, heart failure, renal failure,
    // sepsis, cardioversion, cardiac surgery, Takotsubo.
    // Wallach 10th ed, p 76; Fischbach 10th ed, p 190.
    if test == "troponin_I" { return lab("Troponin I", "ng/mL", 0.0, 0.04, 0.0, 50.0, "gold_standard_MI_marker. rises_3_to_6hr_peaks_12_to_24hr_elevated_7_to_10_days. any_elevation_with_rise_fall_is_acute_MI. non_MI: PE_myocarditis_HF_renal_sepsis", "Wallach 10th ed p76; Fischbach 10th ed p190") }

    // High-sensitivity troponin T (hs-cTnT): newer assay with lower detection limit.
    // The 99th percentile URL is 14 ng/L. Detects smaller MIs earlier.
    // Serial measurements (0h, 1h, 3h) enable rapid rule-in/rule-out algorithms.
    // Very low hs-cTnT (< 5 ng/L) at presentation: negative predictive value > 99%.
    // Wallach 10th ed, p 78.
    if test == "troponin_T_hs" { return lab("Troponin T (hs-cTnT)", "ng/L", 0.0, 14.0, 0.0, 10000.0, "high_sensitivity_assay. 99th_percentile_14_ng/L. serial_0h_1h_3h_rapid_rule_out. below_5: NPV_gt_99pct", "Wallach 10th ed p78") }

    // BNP: B-type natriuretic peptide. Released by ventricles in response to volume overload/stretch.
    // < 100: HF unlikely (NPV ~90%).
    // Range 100-400: grey zone. Correlate clinically.
    // > 400: HF likely (PPV ~90%).
    // Elevated in renal failure (decreased clearance), PE, pulmonary HTN, sepsis.
    // Decreased (falsely low) in obesity (adipose tissue clears BNP).
    // Wallach 10th ed, p 82; Fischbach 10th ed, p 194.
    if test == "BNP" { return lab("BNP", "pg/mL", 0.0, 100.0, 0.0, 5000.0, "ventricular_volume_overload_marker. below_100: HF_unlikely. above_400: HF_likely. falsely_low_in_obesity. elevated_in_renal_failure_PE_sepsis", "Wallach 10th ed p82; Fischbach 10th ed p194") }

    // NT-proBNP: inactive fragment released with BNP. Longer half-life (120 min vs 20 min).
    // Age-adjusted cutoffs for HF diagnosis:
    // < 50 years: > 450 pg/mL suggests HF
    // Age 50-75 years: > 900 pg/mL suggests HF
    // > 75 years: > 1800 pg/mL suggests HF
    // Exclusion cutoff: < 300 pg/mL rules out acute HF (NPV > 98%).
    // More affected by renal function than BNP (renally cleared).
    // Wallach 10th ed, p 84.
    if test == "NT_proBNP" { return lab("NT-proBNP", "pg/mL", 0.0, 300.0, 0.0, 30000.0, "age_adjusted_HF_marker. below_300: rules_out_acute_HF. age_lt_50: above_450_suggests_HF. age_50_75: above_900. age_gt_75: above_1800. renally_cleared", "Wallach 10th ed p84") }

    // CK-MB: creatine kinase MB isoenzyme. Historically used for MI diagnosis.
    // Now largely replaced by troponin. Still useful for detecting reinfarction
    // (CK-MB falls faster than troponin, so a re-rise indicates new injury).
    // CK-MB relative index: (CK-MB / total CK) x 100. > 2.5-3%: cardiac source.
    // Wallach 10th ed, p 80.
    if test == "CK_MB" { return lab("CK-MB", "ng/mL", 0.0, 5.0, 0.0, 100.0, "MB_isoenzyme. largely_replaced_by_troponin. still_useful_for_reinfarction_detection. CK_MB_index_gt_2.5pct: cardiac_source", "Wallach 10th ed p80") }

    // LDH: lactate dehydrogenase. Nonspecific tissue damage marker.
    // Five isoenzymes: LDH1 (heart, RBC), LDH2 (heart, RBC), LDH3 (lung, lymph),
    // LDH4 (liver, muscle), LDH5 (liver, muscle).
    // "Flipped" LDH (LDH1 > LDH2): MI or hemolysis.
    // Elevated in: MI, hemolysis, liver disease, malignancy, PE, muscle injury.
    // Wallach 10th ed, p 86.
    if test == "LDH" { return lab("LDH", "IU/L", 140.0, 280.0, 0.0, 2000.0, "nonspecific_tissue_damage. flipped_LDH1_gt_LDH2: MI_or_hemolysis. elevated_in: MI_hemolysis_liver_malignancy_PE_muscle", "Wallach 10th ed p86") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

fn cardiac_test_count() -> Int {
    return 6
}


// ═══════════════════════════════════════════════════════════════
// CARDIAC PATTERN INTERPRETATION
// ═══════════════════════════════════════════════════════════════

fn lookup_cardiac_pattern(name: String) -> LabPattern {
    // STEMI: ST-elevation MI criteria.
    // Troponin rise/fall with at least one value > 99th percentile URL
    // PLUS new ST elevation at J-point in two contiguous leads:
    // >= 1mm in all leads except V2-V3 where:
    // >= 2mm in men >= 40 years, >= 2.5mm in men < 40, >= 1.5mm in women.
    // Door-to-balloon time < 90 min for primary PCI.
    // Wallach 10th ed, p 88.
    if name == "STEMI" { return pattern("STEMI criteria", "cardiac", "troponin elevated with rise/fall + new ST elevation >= 1mm in 2 contiguous leads (V2-V3: >= 2mm M >= 40yr, >= 2.5mm M < 40yr, >= 1.5mm F)", "transmural_myocardial_infarction. door_to_balloon_lt_90_min_for_PCI", "acute_MI_requiring_emergent_reperfusion. also_consider: pericarditis_LVH_Brugada_early_repolarization", "Wallach 10th ed p88") }

    // NSTEMI: non-ST-elevation MI.
    // Troponin rise/fall with at least one value > 99th percentile URL
    // WITHOUT persistent ST elevation. May have ST depression, T-wave inversions, or normal ECG.
    // Risk stratify with TIMI or GRACE score. Invasive vs conservative strategy.
    // Wallach 10th ed, p 90.
    if name == "NSTEMI" { return pattern("NSTEMI criteria", "cardiac", "troponin elevated with rise/fall WITHOUT persistent ST elevation. may have ST depression or T-wave inversion", "subendocardial_MI_partial_thickness_injury", "risk_stratify_TIMI_GRACE. invasive_strategy_for_high_risk. anticoagulation_antiplatelet", "Wallach 10th ed p90") }

    // Heart failure staging by BNP.
    // NYHA Class I-IV correlates roughly with BNP levels.
    // BNP is prognostic: higher BNP = worse outcomes.
    // Serial BNP monitoring guides therapy: BNP-guided treatment reduces mortality.
    // Wallach 10th ed, p 92.
    if name == "HF_by_BNP" { return pattern("Heart failure staging by BNP", "cardiac", "BNP < 100: HF unlikely. BNP 100-400: possible HF or other cause. BNP > 400: HF likely. Serial trending guides therapy", "ventricular_volume_overload_correlates_with_wall_stress", "NYHA_I: BNP_often_lt_100. NYHA_II: 100-200. NYHA_III: 200-800. NYHA_IV: often_gt_800", "Wallach 10th ed p92") }

    return pattern("", "", "", "", "", "")
}

fn cardiac_pattern_count() -> Int {
    return 3
}


// ═══════════════════════════════════════════════════════════════
// SECTION EIGHT: LIPID PANEL
// ═══════════════════════════════════════════════════════════════
//
// The lipid panel measures cardiovascular risk through cholesterol
// and triglyceride levels. ATP III/ACC/AHA guidelines use these
// values with the Pooled Cohort Equation to determine statin eligibility.
//
// Wallach 10th ed, Ch 4; Fischbach 10th ed, Ch 6.

fn lookup_lipid(test: String) -> LabTest {
    // Total cholesterol: sum of LDL + HDL + VLDL.
    // Desirable < 200. Borderline 200-239. High >= 240.
    // Total cholesterol alone is inadequate for risk assessment --
    // must fractionate into LDL and HDL.
    // Wallach 10th ed, p 134; Fischbach 10th ed, p 270.
    if test == "total_cholesterol" { return lab("Total Cholesterol", "mg/dL", 0.0, 200.0, 0.0, 500.0, "desirable_lt_200. borderline_200_to_239. high_ge_240. must_fractionate_LDL_HDL_for_risk_assessment", "Wallach 10th ed p134; Fischbach 10th ed p270") }

    // LDL cholesterol: "bad" cholesterol. Primary target of statin therapy.
    // < 100: optimal. 100-129: near optimal. 130-159: borderline high.
    // Range 160-189: high. Range >= 190: very high.
    // High-risk patients (ASCVD, diabetes): target < 70 mg/dL.
    // Very high risk: target < 55 mg/dL (2019 ESC/EAS guidelines).
    // Calculated by Friedewald when TG < 400.
    // Wallach 10th ed, p 136; Fischbach 10th ed, p 272.
    if test == "LDL" { return lab("LDL Cholesterol", "mg/dL", 0.0, 100.0, 0.0, 400.0, "primary_statin_target. optimal_lt_100. ASCVD_DM_target_lt_70. very_high_risk_lt_55. Friedewald_if_TG_lt_400", "Wallach 10th ed p136; Fischbach 10th ed p272") }

    // HDL cholesterol: "good" cholesterol. Reverse cholesterol transport.
    // Low HDL is an independent CVD risk factor.
    // Low (risk): < 40 mg/dL (male), < 50 mg/dL (female).
    // High (protective): >= 60 mg/dL.
    // Raising HDL pharmacologically has NOT shown mortality benefit (niacin, CETP inhibitors failed).
    // Exercise and moderate alcohol are the best HDL raisers.
    // Wallach 10th ed, p 138; Fischbach 10th ed, p 274.
    if test == "HDL_male" { return lab("HDL Cholesterol (male)", "mg/dL", 40.0, 100.0, 0.0, 200.0, "reverse_cholesterol_transport. low_lt_40_independent_CVD_risk_factor. high_ge_60_protective. pharmacologic_HDL_raising_has_NOT_reduced_mortality", "Wallach 10th ed p138; Fischbach 10th ed p274") }

    if test == "HDL_female" { return lab("HDL Cholesterol (female)", "mg/dL", 50.0, 100.0, 0.0, 200.0, "reverse_cholesterol_transport_female. low_lt_50_independent_CVD_risk_factor. high_ge_60_protective", "Wallach 10th ed p138") }

    // Triglycerides: transport form of fatty acids. Dietary and hepatic synthesis.
    // Normal < 150. Borderline 150-199. High 200-499. Very high >= 500.
    // Very high (>= 500): pancreatitis risk. This is the clinical emergency threshold.
    // Elevated: obesity, diabetes, metabolic syndrome, alcohol, medications (steroids, estrogen,
    // thiazides, beta-blockers, protease inhibitors).
    // Fasting specimen required (nonfasting TG includes chylomicrons).
    // Wallach 10th ed, p 140; Fischbach 10th ed, p 276.
    if test == "triglycerides" { return lab("Triglycerides", "mg/dL", 0.0, 150.0, 0.0, 500.0, "fasting_specimen_required. normal_lt_150. high_200_499. very_high_ge_500: pancreatitis_risk. elevated: obesity_DM_metabolic_syndrome_alcohol", "Wallach 10th ed p140; Fischbach 10th ed p276") }

    // VLDL cholesterol: triglyceride-rich lipoprotein synthesized by liver.
    // Estimated as TG/5 (Friedewald). Normal 5-40 mg/dL.
    // Elevated: same causes as elevated triglycerides.
    // Wallach 10th ed, p 142.
    if test == "VLDL" { return lab("VLDL Cholesterol", "mg/dL", 5.0, 40.0, 0.0, 100.0, "estimated_as_TG_div_5. elevated_with_triglycerides. hepatic_triglyceride_export_particle", "Wallach 10th ed p142") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

fn lipid_test_count() -> Int {
    return 6
}


// ═══════════════════════════════════════════════════════════════
// LIPID CALCULATIONS
// ═══════════════════════════════════════════════════════════════

// Friedewald LDL calculation.
// LDL = Total cholesterol - HDL - (Triglycerides / 5)
// ONLY VALID WHEN TRIGLYCERIDES < 400 mg/dL.
// When TG >= 400: direct LDL measurement required.
// Friedewald WT, Levy RI, Fredrickson DS. Clin Chem 18:499-502, 1972.
// Wallach 10th ed, p 136.
fn calculate_friedewald_ldl(total_chol: Float, hdl: Float, trig: Float) -> Float {
    return total_chol - hdl - trig / 5.0
}

fn friedewald_valid(trig: Float) -> Bool {
    if trig < 400.0 { return true }
    return false
}

// Non-HDL cholesterol: Total cholesterol - HDL.
// Includes LDL + VLDL + IDL + Lp(a). Better predictor than LDL alone
// when TG elevated (captures all atherogenic particles).
// Target: LDL goal + 30 mg/dL.
// Wallach 10th ed, p 144.
fn calculate_non_hdl(total_chol: Float, hdl: Float) -> Float {
    return total_chol - hdl
}

// TC/HDL ratio: total cholesterol / HDL.
// < 3.5: low risk. 3.5-5.0: moderate risk. > 5.0: high risk.
// Wallach 10th ed, p 144.
fn calculate_tc_hdl_ratio(total_chol: Float, hdl: Float) -> Float {
    if hdl <= 0.0 { return 0.0 }
    return total_chol / hdl
}

fn classify_tc_hdl_ratio(ratio: Float) -> String {
    if ratio < 3.5 { return "low_cardiovascular_risk" }
    if ratio <= 5.0 { return "moderate_cardiovascular_risk" }
    return "high_cardiovascular_risk"
}

fn classify_ldl(ldl: Float) -> String {
    if ldl < 70.0 { return "optimal_for_very_high_risk" }
    if ldl < 100.0 { return "optimal" }
    if ldl < 130.0 { return "near_optimal_above_optimal" }
    if ldl < 160.0 { return "borderline_high" }
    if ldl < 190.0 { return "high" }
    return "very_high_consider_familial_hypercholesterolemia"
}


// ═══════════════════════════════════════════════════════════════
// SECTION NINE: HbA1c AND GLUCOSE MONITORING
// ═══════════════════════════════════════════════════════════════
//
// HbA1c reflects average glucose over preceding 2-3 months
// (lifespan of RBC approximately 120 days). It is the standard
// for diabetes diagnosis and monitoring.
//
// Wallach 10th ed, p 54; Fischbach 10th ed, p 212.

fn lookup_hba1c(test: String) -> LabTest {
    // HbA1c: glycated hemoglobin. Nonenzymatic glycation of hemoglobin beta chain N-terminus.
    // Normal: < 5.7%. Prediabetes: 5.7-6.4%. Diabetes: >= 6.5%.
    // Treatment target: < 7.0% for most adults with diabetes (ADA recommendation).
    // Less stringent (< 8.0%): elderly, limited life expectancy, hypoglycemia risk, comorbidities.
    // More stringent (< 6.5%): young, newly diagnosed, no CVD, if achievable without significant hypoglycemia.
    // Falsely LOW: hemolytic anemia, blood loss, hemoglobin variants (HbS, HbC, HbF),
    // chronic kidney disease (shortened RBC survival), transfusion.
    // Falsely HIGH: iron deficiency (prolonged RBC survival), splenectomy, alcoholism.
    // Wallach 10th ed, p 54; Fischbach 10th ed, p 212.
    if test == "HbA1c" { return lab("HbA1c", "%", 4.0, 5.7, 0.0, 20.0, "average_glucose_over_2_to_3_months. normal_lt_5.7. prediabetes_5.7_to_6.4. diabetes_ge_6.5. target_lt_7_for_most. falsely_low: hemolysis_variants_CKD. falsely_high: iron_def", "Wallach 10th ed p54; Fischbach 10th ed p212") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

// Estimated average glucose (eAG).
// eAG (mg/dL) = 28.7 x A1c - 46.7
// Nathan DM et al. Translating the A1C assay into estimated average glucose values.
// Diabetes Care 31:1473-1478, 2008.
fn calculate_eag(a1c: Float) -> Float {
    return 28.7 * a1c - 46.7
}

fn classify_a1c(a1c: Float) -> String {
    if a1c < 5.7 { return "normal" }
    if a1c < 6.5 { return "prediabetes" }
    if a1c < 7.0 { return "diabetes_at_ADA_target" }
    if a1c < 8.0 { return "diabetes_above_target_consider_intensification" }
    if a1c < 9.0 { return "diabetes_poorly_controlled" }
    return "diabetes_very_poorly_controlled_urgent_intervention"
}

// Reference table: A1c to eAG mapping.
fn a1c_to_eag_reference(a1c_pct: Float) -> Float {
    // A1c 5.0% = 97 mg/dL, 6.0% = 126, 7.0% = 154, 8.0% = 183,
    // A1c 9.0% = 212, 10.0% = 240, 11.0% = 269, 12.0% = 298
    return 28.7 * a1c_pct - 46.7
}


// ═══════════════════════════════════════════════════════════════
// SECTION TEN: URINALYSIS
// ═══════════════════════════════════════════════════════════════
//
// Urinalysis is the oldest clinical lab test. It combines physical
// examination (color, clarity, specific gravity), chemical dipstick
// testing (pH, protein, glucose, ketones, blood, bilirubin, nitrites,
// leukocyte esterase), and microscopic sediment analysis (cells,
// casts, crystals). A complete urinalysis can diagnose UTI, kidney
// disease, diabetes, liver disease, and urolithiasis.
//
// Wallach 10th ed, Ch 14; Fischbach 10th ed, Ch 3.

fn lookup_urinalysis(component: String) -> UrinalysisComponent {
    // pH: normal 4.5-8.0. Average around 6.0 (slightly acidic).
    // Acidic (< 5.5): high protein diet, metabolic acidosis, uric acid stones, cranberry juice.
    // Alkaline (> 7.5): UTI with urea-splitting organisms (Proteus), RTA, vegetarian diet,
    // stale specimen (bacterial conversion of urea to ammonia).
    // Wallach 10th ed, p 510.
    if component == "pH" { return ua_component("pH", "4.5 to 8.0 (average 6.0)", "acidic_lt_5.5: high_protein_metabolic_acidosis_uric_acid_stones. alkaline_gt_7.5: UTI_Proteus_urea_splitting_RTA_vegetarian_stale_specimen", "dipstick_indicator", "Wallach 10th ed p510") }

    // Specific gravity: concentration of urine. Reflects hydration and concentrating ability.
    // Normal range 1.005-1.030.
    // Low (< 1.005): diabetes insipidus, overhydration, renal tubular damage.
    // High (> 1.030): dehydration, SIADH, glycosuria, contrast dye, proteinuria.
    // Fixed at 1.010: renal failure (isosthenuria -- kidneys cannot concentrate or dilute).
    // Wallach 10th ed, p 512.
    if component == "specific_gravity" { return ua_component("Specific gravity", "1.005 to 1.030", "low_lt_1.005: DI_overhydration_tubular_damage. high_gt_1.030: dehydration_SIADH_glycosuria. fixed_1.010: isosthenuria_renal_failure", "refractometer_or_dipstick", "Wallach 10th ed p512") }

    // Protein: normally < 150 mg/day (dipstick negative or trace).
    // Dipstick detects albumin primarily (misses Bence Jones light chains -- use sulfosalicylic acid test).
    // Proteinuria: glomerular (nephrotic > 3.5g/day), tubular, overflow (myeloma), orthostatic (benign in young).
    // Microalbuminuria (30-300 mg/day): earliest sign of diabetic nephropathy.
    // Wallach 10th ed, p 514; Fischbach 10th ed, p 168.
    if component == "protein" { return ua_component("Protein", "negative to trace (< 150 mg/day)", "proteinuria: glomerular_nephrotic_gt_3.5g_tubular_overflow_orthostatic. microalbuminuria_30_300: earliest_diabetic_nephropathy. dipstick_misses_Bence_Jones", "dipstick_detects_albumin_primarily", "Wallach 10th ed p514; Fischbach 10th ed p168") }

    // Glucose: normally negative (reabsorbed completely in proximal tubule).
    // Glucosuria: blood glucose > 180 mg/dL (renal threshold exceeded), pregnancy (lower threshold),
    // Fanconi syndrome (tubular defect), SGLT2 inhibitors (pharmacologically induced).
    // Wallach 10th ed, p 516.
    if component == "glucose" { return ua_component("Glucose", "negative", "glucosuria: blood_glucose_gt_180_renal_threshold_pregnancy_Fanconi_SGLT2_inhibitors", "dipstick_glucose_oxidase", "Wallach 10th ed p516") }

    // Ketones: acetoacetate and acetone detected by dipstick (NOT beta-hydroxybutyrate).
    // Positive: DKA, starvation ketosis, alcoholic ketoacidosis, low-carb diet, pregnancy.
    // In DKA, serum beta-hydroxybutyrate is the better test (dipstick underestimates ketosis).
    // Wallach 10th ed, p 518.
    if component == "ketones" { return ua_component("Ketones", "negative", "positive: DKA_starvation_alcoholic_ketoacidosis_low_carb_diet. dipstick_detects_acetoacetate_NOT_beta_hydroxybutyrate. serum_BHB_better_for_DKA", "dipstick_nitroprusside_reaction", "Wallach 10th ed p518") }

    // Blood: detects hemoglobin (hemolysis or hematuria) and myoglobin (rhabdomyolysis).
    // Hematuria: UTI, stones, glomerulonephritis, malignancy, trauma, menstrual contamination.
    // Positive dipstick with no RBCs on microscopy: hemoglobinuria or myoglobinuria.
    // False positive: dehydration, exercise, menstrual blood.
    // Wallach 10th ed, p 520.
    if component == "blood" { return ua_component("Blood (hemoglobin)", "negative", "hematuria: UTI_stones_glomerulonephritis_malignancy_trauma. positive_no_RBCs: hemoglobinuria_or_myoglobinuria_rhabdomyolysis", "dipstick_peroxidase_activity", "Wallach 10th ed p520") }

    // Bilirubin: conjugated (direct) bilirubin spills into urine.
    // Positive: obstructive jaundice, hepatocellular disease.
    // Absent: hemolytic jaundice (unconjugated bilirubin is NOT water-soluble, does not filter).
    // Dark "tea-colored" urine before jaundice is visible.
    // Wallach 10th ed, p 522.
    if component == "bilirubin" { return ua_component("Bilirubin", "negative", "positive: obstructive_jaundice_hepatocellular_disease_conjugated_bilirubin. absent_in_hemolytic_jaundice_unconjugated_not_water_soluble. tea_colored_urine", "dipstick_diazo_reaction", "Wallach 10th ed p522") }

    // Urobilinogen: normal in small amounts (0.2-1.0 EU/dL).
    // Increased: hemolytic anemia (increased bilirubin production), hepatocellular disease.
    // Absent: complete biliary obstruction (no bilirubin reaching gut for bacterial conversion).
    // Wallach 10th ed, p 524.
    if component == "urobilinogen" { return ua_component("Urobilinogen", "0.2 to 1.0 EU/dL (small amount normal)", "increased: hemolytic_anemia_hepatocellular_disease. absent: complete_biliary_obstruction_no_bilirubin_reaching_gut", "dipstick_Ehrlich_aldehyde_reaction", "Wallach 10th ed p524") }

    // Nitrites: bacterial conversion of dietary nitrates to nitrites.
    // Positive: UTI with gram-negative organisms (E. coli, Proteus, Klebsiella, Enterobacter).
    // FALSE NEGATIVE: organisms that do not reduce nitrates (Enterococcus, Staphylococcus,
    // Pseudomonas), insufficient bladder dwell time (< 4 hours), dilute urine, low dietary nitrate.
    // Wallach 10th ed, p 526.
    if component == "nitrites" { return ua_component("Nitrites", "negative", "positive: UTI_gram_negative_E_coli_Proteus_Klebsiella. false_negative: Enterococcus_Staph_Pseudomonas_insufficient_dwell_time_lt_4hrs", "dipstick_Griess_reaction", "Wallach 10th ed p526") }

    // Leukocyte esterase: enzyme released by lysed WBCs.
    // Positive: pyuria (UTI, interstitial nephritis, contamination).
    // Combined with nitrites: LE+ and nitrites+ has high specificity for UTI.
    // False negative: high glucose, high protein, high specific gravity, cephalexin, gentamicin.
    // Wallach 10th ed, p 528.
    if component == "leukocyte_esterase" { return ua_component("Leukocyte esterase", "negative", "positive: pyuria_UTI_interstitial_nephritis. LE_plus_nitrites_plus: high_specificity_for_UTI. false_negative: high_glucose_protein_SG_cephalexin", "dipstick_esterase_substrate", "Wallach 10th ed p528") }

    // WBC (microscopic): > 5 WBC/HPF is pyuria.
    // UTI, interstitial nephritis, glomerulonephritis, contamination.
    // Sterile pyuria: TB, chlamydia, interstitial nephritis, renal stones, polycystic kidney.
    // Wallach 10th ed, p 530.
    if component == "WBC_micro" { return ua_component("WBC (microscopic)", "0 to 5 per HPF", "gt_5_HPF: pyuria. UTI_interstitial_nephritis_GN. sterile_pyuria: TB_chlamydia_interstitial_nephritis_stones_PKD", "microscopy_400x", "Wallach 10th ed p530") }

    // RBC (microscopic): > 3 RBC/HPF is hematuria.
    // Dysmorphic RBCs: glomerular origin (GN). Isomorphic RBCs: lower tract (stones, tumor, UTI).
    // Wallach 10th ed, p 532.
    if component == "RBC_micro" { return ua_component("RBC (microscopic)", "0 to 3 per HPF", "gt_3_HPF: hematuria. dysmorphic: glomerular_origin_GN. isomorphic: lower_tract_stones_tumor_UTI", "microscopy_400x", "Wallach 10th ed p532") }

    // Casts: cylindrical protein structures formed in renal tubules.
    // Hyaline: normal in small numbers, dehydration, exercise.
    // Granular (muddy brown): ATN (acute tubular necrosis). THE classic ATN finding.
    // RBC casts: glomerulonephritis (diagnostic). WBC casts: pyelonephritis, interstitial nephritis.
    // Waxy/broad casts: chronic renal failure (stasis in dilated tubules).
    // Wallach 10th ed, p 534.
    if component == "casts" { return ua_component("Casts", "occasional hyaline (0-2 per LPF)", "granular_muddy_brown: ATN_classic. RBC_casts: glomerulonephritis_DIAGNOSTIC. WBC_casts: pyelonephritis_interstitial_nephritis. waxy_broad: chronic_renal_failure", "microscopy_100x_LPF", "Wallach 10th ed p534") }

    // Crystals: depend on urine pH and composition.
    // Acidic urine: uric acid (yellow-brown, rhomboid), calcium oxalate (envelope-shaped).
    // Alkaline urine: triple phosphate (coffin lid), calcium phosphate.
    // Pathologic: cystine (hexagonal, pathognomonic for cystinuria), tyrosine/leucine (liver failure).
    // Wallach 10th ed, p 536.
    if component == "crystals" { return ua_component("Crystals", "none or few (pH dependent)", "acidic: uric_acid_rhomboid_calcium_oxalate_envelope. alkaline: triple_phosphate_coffin_lid. pathologic: cystine_hexagonal_pathognomonic_for_cystinuria", "microscopy_polarized_light_helpful", "Wallach 10th ed p536") }

    return ua_component("", "", "", "", "")
}

fn urinalysis_component_count() -> Int {
    return 14
}


// ═══════════════════════════════════════════════════════════════
// SECTION ELEVEN: IRON STUDIES
// ═══════════════════════════════════════════════════════════════
//
// Iron studies differentiate the causes of anemia: iron deficiency,
// anemia of chronic disease (ACD), sideroblastic anemia, and
// hemochromatosis. The four core tests (serum iron, TIBC, ferritin,
// transferrin saturation) together create diagnostic patterns that
// no single test can provide alone.
//
// Wallach 10th ed, Ch 11; Fischbach 10th ed, Ch 2.

fn lookup_iron_study(test: String) -> LabTest {
    // Serum iron: circulating iron bound to transferrin.
    // Diurnal variation (highest in morning). Affected by recent iron intake.
    // Low: iron deficiency, anemia of chronic disease, hypothyroidism.
    // High: hemochromatosis, iron overload (transfusions), sideroblastic anemia,
    // hemolytic anemia, hepatitis, lead poisoning.
    // Wallach 10th ed, p 392; Fischbach 10th ed, p 102.
    if test == "serum_iron" { return lab("Serum Iron", "mcg/dL", 60.0, 170.0, 20.0, 500.0, "circulating_iron_on_transferrin. diurnal_variation. low: iron_def_ACD_hypothyroid. high: hemochromatosis_iron_overload_sideroblastic_hemolytic", "Wallach 10th ed p392; Fischbach 10th ed p102") }

    // TIBC: total iron-binding capacity. Indirect measure of transferrin.
    // High TIBC: iron deficiency (body makes more transferrin to capture scarce iron).
    // Low TIBC: anemia of chronic disease (inflammation downregulates transferrin),
    // hemochromatosis (iron overload suppresses transferrin production),
    // liver disease (decreased synthesis), nephrotic syndrome (urinary loss).
    // Wallach 10th ed, p 394.
    if test == "TIBC" { return lab("TIBC", "mcg/dL", 250.0, 370.0, 100.0, 600.0, "indirect_transferrin_measure. high: iron_deficiency_body_upregulates_transferrin. low: ACD_inflammation_hemochromatosis_liver_disease_nephrotic", "Wallach 10th ed p394") }

    // Ferritin: intracellular iron storage protein. Best single test for iron stores.
    // Low: iron deficiency (most sensitive and specific single test).
    // Ferritin < 12-15 ng/mL is essentially diagnostic of iron deficiency.
    // High: iron overload, inflammation (acute phase reactant), infection, liver disease,
    // malignancy, hemolytic anemia, Still disease, hemophagocytic lymphohistiocytosis (HLH).
    // Ferritin > 1000: consider hemochromatosis, HLH, adult-onset Still disease.
    // CAUTION: ferritin is an acute phase reactant -- can be normal or elevated in iron
    // deficiency with concurrent inflammation. Use transferrin saturation to clarify.
    // Wallach 10th ed, p 396; Fischbach 10th ed, p 104.
    if test == "ferritin_male" { return lab("Ferritin (male)", "ng/mL", 12.0, 300.0, 5.0, 1000.0, "best_single_test_for_iron_stores. below_12: diagnostic_iron_deficiency. above_1000: hemochromatosis_HLH_Still. CAUTION: acute_phase_reactant_may_be_falsely_normal_in_iron_def_with_inflammation", "Wallach 10th ed p396; Fischbach 10th ed p104") }

    if test == "ferritin_female" { return lab("Ferritin (female)", "ng/mL", 12.0, 150.0, 5.0, 1000.0, "best_single_test_for_iron_stores_female. lower_upper_limit_than_male. below_12: diagnostic_iron_deficiency. acute_phase_reactant_caveat_applies", "Wallach 10th ed p396") }

    // Transferrin saturation: (serum iron / TIBC) x 100.
    // Normal: 20-50%. This is the percentage of transferrin binding sites occupied by iron.
    // Low (< 20%): iron deficiency, anemia of chronic disease.
    // High (> 45-50%): hemochromatosis screening cutoff. > 60%: strongly suggests iron overload.
    // Fasting morning sample most reliable (diurnal iron variation).
    // Wallach 10th ed, p 398.
    if test == "transferrin_sat" { return lab("Transferrin Saturation", "%", 20.0, 50.0, 5.0, 100.0, "pct_transferrin_occupied_by_iron. low_lt_20: iron_def_or_ACD. high_gt_45: hemochromatosis_screen. gt_60: strongly_suggests_iron_overload. fasting_morning_preferred", "Wallach 10th ed p398") }

    return lab("", "", 0.0, 0.0, 0.0, 0.0, "", "")
}

fn iron_study_count() -> Int {
    return 5
}


// ═══════════════════════════════════════════════════════════════
// IRON STUDY PATTERN INTERPRETATION
// ═══════════════════════════════════════════════════════════════

fn lookup_iron_pattern(name: String) -> LabPattern {
    // Iron deficiency anemia: most common anemia worldwide.
    // Low serum iron, HIGH TIBC, LOW ferritin, LOW transferrin sat (< 20%).
    // MCV low (microcytic), RDW elevated (anisocytosis).
    // Peripheral smear: hypochromic microcytes, pencil cells, target cells.
    // Causes: chronic blood loss (GI, menstrual), malabsorption (celiac, gastric bypass),
    // increased demand (pregnancy, growth), dietary insufficiency.
    // Wallach 10th ed, p 400.
    if name == "iron_deficiency" { return pattern("Iron deficiency anemia", "iron_studies", "low serum iron, HIGH TIBC, LOW ferritin (< 12), LOW transferrin sat (< 20%)", "iron_stores_depleted. microcytic_hypochromic_anemia_with_elevated_RDW", "chronic_blood_loss_GI_menstrual_malabsorption_celiac_increased_demand_pregnancy_dietary", "Wallach 10th ed p400") }

    // Anemia of chronic disease (ACD): second most common anemia.
    // Low serum iron, LOW TIBC (key distinguisher from IDA), NORMAL or HIGH ferritin, LOW transferrin sat.
    // MCV normal or low. Ferritin elevated because it is an acute phase reactant.
    // Mechanism: hepcidin (liver peptide) elevated by IL-6 in inflammation.
    // Hepcidin blocks ferroportin, trapping iron in macrophages and enterocytes.
    // Causes: infection, autoimmune disease, malignancy, CKD.
    // Wallach 10th ed, p 402.
    if name == "anemia_chronic_disease" { return pattern("Anemia of chronic disease", "iron_studies", "low serum iron, LOW TIBC (vs HIGH in IDA), NORMAL or HIGH ferritin, LOW transferrin sat", "hepcidin_mediated_iron_sequestration. ferritin_elevated_as_acute_phase_reactant. TIBC_low_is_key_distinguisher_from_IDA", "chronic_infection_autoimmune_malignancy_CKD. treat_underlying_cause_not_iron", "Wallach 10th ed p402") }

    // Hemochromatosis: iron overload disorder.
    // HIGH serum iron, LOW TIBC, VERY HIGH ferritin (often > 1000), HIGH transferrin sat (> 45-60%).
    // Hereditary (HFE gene, C282Y mutation): autosomal recessive, northern European.
    // Secondary: transfusion-dependent anemias (thalassemia, MDS, sickle cell).
    // Complications: cirrhosis, hepatocellular carcinoma, diabetes ("bronze diabetes"),
    // cardiomyopathy, arthropathy, hypogonadism.
    // Treatment: phlebotomy (hereditary), chelation (secondary).
    // Wallach 10th ed, p 404.
    if name == "hemochromatosis" { return pattern("Hemochromatosis", "iron_studies", "HIGH serum iron, LOW TIBC, VERY HIGH ferritin (> 1000), HIGH transferrin sat (> 45-60%)", "iron_overload_depositing_in_organs. hereditary_HFE_C282Y_or_secondary_transfusional", "cirrhosis_HCC_bronze_diabetes_cardiomyopathy_arthropathy_hypogonadism. treat: phlebotomy_or_chelation", "Wallach 10th ed p404") }

    // Sideroblastic anemia: defective heme synthesis in mitochondria.
    // HIGH serum iron, NORMAL or LOW TIBC, HIGH ferritin, HIGH transferrin sat.
    // MCV may be low, normal, or high (dimorphic population).
    // Diagnosis: ring sideroblasts on iron stain of bone marrow aspirate.
    // Causes: hereditary (ALAS2 mutations), acquired (MDS, lead poisoning, B6 deficiency,
    // isoniazid, alcohol, copper deficiency).
    // Wallach 10th ed, p 406.
    if name == "sideroblastic" { return pattern("Sideroblastic anemia", "iron_studies", "HIGH serum iron, NORMAL or LOW TIBC, HIGH ferritin, HIGH transferrin sat. Ring sideroblasts on marrow", "defective_heme_synthesis_iron_accumulates_in_mitochondria", "hereditary_ALAS2_acquired_MDS_lead_B6_deficiency_isoniazid_alcohol_copper_deficiency", "Wallach 10th ed p406") }

    return pattern("", "", "", "", "", "")
}

fn iron_pattern_count() -> Int {
    return 4
}


// ═══════════════════════════════════════════════════════════════
// IRON CALCULATIONS
// ═══════════════════════════════════════════════════════════════

fn calculate_transferrin_saturation(serum_iron: Float, tibc: Float) -> Float {
    if tibc <= 0.0 { return 0.0 }
    return (serum_iron / tibc) * 100.0
}


// ═══════════════════════════════════════════════════════════════
// SECTION TWELVE: ADDITIONAL CALCULATIONS AND LOOKUPS
// ═══════════════════════════════════════════════════════════════

fn lookup_lab_calculation(name: String) -> LabCalculation {
    if name == "anion_gap" { return calc("Anion gap", "Na - (Cl + HCO3)", "8 to 12 mEq/L", "elevated: MUDPILES (Methanol Uremia DKA Propylene_glycol INH/Iron Lactic_acidosis Ethylene_glycol Salicylates). normal AG acidosis: diarrhea RTA acetazolamide", "albumin correction: for every 1 g/dL albumin below 4.0, expected AG decreases by 2.5 mEq/L", "Wallach 10th ed; Fischbach 10th ed") }

    if name == "corrected_calcium" { return calc("Corrected calcium", "measured Ca + 0.8 x (4.0 - albumin)", "8.5 to 10.5 mg/dL", "adjusts for hypoalbuminemia. each 1g decrease in albumin falsely lowers total calcium by 0.8 mg/dL", "only needed when albumin < 4.0 g/dL. ionized calcium is gold standard when available", "Wallach 10th ed p113") }

    if name == "bun_creatinine_ratio" { return calc("BUN/Creatinine ratio", "BUN / Creatinine", "10:1 to 20:1", "gt 20: prerenal (dehydration CHF GI bleed). lt 10: intrinsic renal or liver disease or malnutrition or rhabdomyolysis", "GI bleed elevates BUN (digested blood protein). steroids increase BUN via catabolism", "Wallach 10th ed p100") }

    if name == "friedewald_ldl" { return calc("Friedewald LDL", "Total cholesterol - HDL - (TG / 5)", "optimal < 100 mg/dL", "only valid when TG < 400 mg/dL. when TG >= 400 use direct LDL measurement", "inaccurate with nonfasting specimen or hypertriglyceridemia. Martin-Hopkins equation more accurate at TG 200-399", "Friedewald WT et al. Clin Chem 18:499-502, 1972") }

    if name == "eag" { return calc("Estimated average glucose", "28.7 x A1c - 46.7", "A1c 5.0% = 97 mg/dL, 7.0% = 154, 10.0% = 240", "derived from ADAG study correlating A1c with continuous glucose monitoring data", "correlation is population average. individual variation exists. less reliable with hemoglobin variants", "Nathan DM et al. Diabetes Care 31:1473-1478, 2008") }

    if name == "cockcroft_gault" { return calc("Cockcroft-Gault CrCl", "[(140 - age) x weight(kg)] / [72 x Cr] x 0.85 if female", "normal > 90 mL/min", "estimates creatinine clearance for drug dosing. overestimates GFR because creatinine is tubularly secreted", "inaccurate in extremes of weight, muscle mass, and age. CKD-EPI is preferred for CKD staging", "Cockcroft DW, Gault MH. Nephron 16:31-41, 1976") }

    if name == "anc" { return calc("Absolute neutrophil count", "WBC x (segs% + bands%) / 100", "normal > 1500 cells/uL", "ANC lt 1500: neutropenia. lt 500: severe (febrile neutropenia protocol). lt 100: profound (life-threatening infection risk)", "automated differential may differ from manual. band counts have high interobserver variability", "Fischbach 10th ed p82") }

    if name == "r_factor" { return calc("R-factor (DILI)", "(ALT / ALT_ULN) / (ALP / ALP_ULN)", "not applicable (classification tool)", "R gt 5: hepatocellular DILI. R 2-5: mixed DILI. R lt 2: cholestatic DILI. guides Hy's Law assessment", "ALT and ALP ULN vary by laboratory. commonly ALT ULN = 40, ALP ULN = 120", "Wallach 10th ed p268") }

    if name == "transferrin_sat" { return calc("Transferrin saturation", "(serum iron / TIBC) x 100", "20 to 50%", "lt 20: iron deficiency or ACD. gt 45: hemochromatosis screening cutoff. gt 60: strongly suggests iron overload", "fasting morning specimen most reliable due to diurnal iron variation", "Wallach 10th ed p398") }

    if name == "osmolality" { return calc("Serum osmolality", "2(Na) + glucose/18 + BUN/2.8", "275 to 295 mOsm/kg", "osmolar gap = measured - calculated. gap gt 10: methanol ethylene_glycol ethanol mannitol", "does not account for ethanol. add EtOH/4.6 if ethanol suspected", "Wallach 10th ed p105") }

    return calc("", "", "", "", "", "")
}

fn lab_calculation_count() -> Int {
    return 10
}


// ═══════════════════════════════════════════════════════════════
// AGGREGATE COUNTS
// ═══════════════════════════════════════════════════════════════

fn total_lab_test_count() -> Int {
    // CBC (14) + WBC diff (6) + CMP (14) + Coag (6) + Thyroid (5) + Cardiac (6) + Lipid (6) + HbA1c (1) + Iron (5)
    return 63
}

fn total_pattern_count() -> Int {
    // LFT (4) + DIC (5) + Thyroid (7) + Cardiac (3) + Iron (4)
    return 23
}

fn total_urinalysis_count() -> Int {
    return 14
}

fn total_calculation_count() -> Int {
    return 10
}
