// hematology.sy -- Blood cells, hemoglobin, coagulation cascade,
// and clinical hematology as native Scyla.
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536
//
// Blood is the only tissue that is also a transport medium. It carries
// oxygen, nutrients, waste, hormones, immune cells, and clotting factors
// to every cell in the body. This module encodes the cellular components,
// the oxygen-carrying protein hemoglobin with its cooperative binding
// kinetics, the coagulation cascade that prevents hemorrhage, the
// fibrinolytic system that dissolves clots, and the ABO/Rh blood group
// antigens that determine transfusion compatibility.
//
// Every clotting factor, hemoglobin chain, and growth factor carries its
// UniProt accession so the proteome module can look up the full sequence.
//
// CITATIONS:
//   Hoffbrand AV, Steensma DP. Hoffbrand's Essential Haematology,
//     8th ed. Wiley-Blackwell, 2019.
//   Hall JE, Hall ME. Guyton and Hall Textbook of Medical Physiology,
//     14th ed. Elsevier, 2021.
//   Furie B, Furie BC. Mechanisms of thrombus formation.
//     N Engl J Med 359:938-949, 2008.
//   Perutz MF. Stereochemistry of cooperative effects in haemoglobin.
//     Nature 228:726-734, 1970. (Nobel 1962)
//   Davie EW, Ratnoff OD. Waterfall sequence for intrinsic blood
//     clotting. Science 145:1310-1312, 1964.


// ═══════════════════════════════════════════════════════════════
// SECTION ONE: HEMATOPOIETIC GROWTH FACTORS
// ═══════════════════════════════════════════════════════════════
//
// Growth factors control hematopoiesis: the production of all blood
// cells from hematopoietic stem cells (HSCs) in the bone marrow.
// Each factor drives a specific lineage commitment.
//
// Hoffbrand 8th ed, Ch 1: Haemopoiesis, pp 1-14.
// Guyton 14th ed, Ch 33: Red Blood Cells, Anemia, and Polycythemia.

struct GrowthFactor {
    address: Int,
    name: String,
    abbreviation: String,
    uniprot: String,
    gene: String,
    target_lineage: String,
    primary_function: String,
    clinical_use: String,
}

fn gf(addr: Int, nm: String, abbr: String, up: String, gn: String, tgt: String, func: String, clin: String) -> GrowthFactor {
    return GrowthFactor { address: addr, name: nm, abbreviation: abbr, uniprot: up, gene: gn, target_lineage: tgt, primary_function: func, clinical_use: clin }
}

fn unknown_growth_factor() -> GrowthFactor {
    return gf(0, "Unknown", "", "", "", "", "", "")
}

fn lookup_growth_factor(addr: Int) -> GrowthFactor {
    // EPO: erythropoietin. Produced by peritubular interstitial cells of kidney
    // in response to hypoxia (HIF-2alpha pathway). Drives erythroid progenitors
    // to mature RBCs. Recombinant EPO (epoetin alfa) treats anemia of CKD.
    // Hoffbrand 8th ed, Ch 3, pp 26-29.
    if addr == 1 { return gf(1, "Erythropoietin", "EPO", "P01588", "EPO", "erythroid", "stimulates_erythroid_progenitor_proliferation_and_differentiation", "epoetin_alfa_for_CKD_anemia_and_chemotherapy_anemia") }

    // TPO: thrombopoietin. Produced constitutively by liver. Binds c-Mpl receptor
    // on megakaryocytes. Drives platelet production.
    // Hoffbrand 8th ed, Ch 25, pp 337-338.
    if addr == 2 { return gf(2, "Thrombopoietin", "TPO", "P40225", "THPO", "megakaryocytic", "stimulates_megakaryocyte_proliferation_and_platelet_release", "romiplostim_and_eltrombopag_for_ITP") }

    // G-CSF: granulocyte colony-stimulating factor. Drives neutrophil production.
    // Clinical: filgrastim for chemotherapy-induced neutropenia.
    // Hoffbrand 8th ed, Ch 1, p 8.
    if addr == 3 { return gf(3, "Granulocyte colony-stimulating factor", "G-CSF", "P09919", "CSF3", "granulocytic_neutrophil", "stimulates_neutrophil_production_and_release_from_marrow", "filgrastim_for_neutropenia") }

    // GM-CSF: granulocyte-macrophage CSF. Broader than G-CSF: drives both
    // granulocyte and monocyte/macrophage lineages.
    // Hoffbrand 8th ed, Ch 1, p 8.
    if addr == 4 { return gf(4, "Granulocyte-macrophage colony-stimulating factor", "GM-CSF", "P04141", "CSF2", "granulocytic_and_monocytic", "stimulates_granulocyte_and_macrophage_progenitors", "sargramostim_post_transplant") }

    // M-CSF: macrophage CSF. Drives monocyte/macrophage differentiation.
    // Hoffbrand 8th ed, Ch 1, p 8.
    if addr == 5 { return gf(5, "Macrophage colony-stimulating factor", "M-CSF", "P09603", "CSF1", "monocytic_macrophage", "stimulates_monocyte_and_macrophage_differentiation", "research_and_immunotherapy") }

    // IL-3: interleukin-3, multi-lineage. Acts early in hematopoiesis on
    // multipotent progenitors. Synergizes with lineage-specific factors.
    // Hoffbrand 8th ed, Ch 1, p 7.
    if addr == 6 { return gf(6, "Interleukin-3", "IL-3", "P08700", "IL3", "multi_lineage", "stimulates_multipotent_progenitor_expansion", "research_use_primarily") }

    // IL-7: critical for lymphoid development. Without IL-7 signaling,
    // T and B lymphocyte development arrests. SCID results from IL-7R mutations.
    // Hoffbrand 8th ed, Ch 1, p 9; Ch 9, pp 100-101.
    if addr == 7 { return gf(7, "Interleukin-7", "IL-7", "P13232", "IL7", "lymphoid_T_and_B", "essential_for_T_and_B_lymphocyte_development_and_survival", "CYT107_immunotherapy_trials") }

    // SCF: stem cell factor (c-Kit ligand). Acts on the earliest HSCs.
    // Essential for HSC self-renewal and maintenance.
    // Hoffbrand 8th ed, Ch 1, pp 6-7.
    if addr == 8 { return gf(8, "Stem cell factor", "SCF", "P21583", "KITLG", "hematopoietic_stem_cell", "HSC_self_renewal_and_early_progenitor_survival", "research_ex_vivo_expansion") }

    // IL-5: eosinophil differentiation factor. Drives eosinophil lineage.
    // Targeted by mepolizumab (anti-IL-5) for severe eosinophilic asthma.
    // Hoffbrand 8th ed, Ch 1, p 8.
    if addr == 9 { return gf(9, "Interleukin-5", "IL-5", "P05113", "IL5", "eosinophilic", "stimulates_eosinophil_differentiation_and_activation", "mepolizumab_targets_IL5_in_severe_asthma") }

    // IL-11: synergizes with TPO for megakaryocyte maturation.
    // Also has anti-inflammatory properties in gut.
    if addr == 10 { return gf(10, "Interleukin-11", "IL-11", "P20809", "IL11", "megakaryocytic", "synergizes_with_TPO_for_megakaryocyte_maturation", "oprelvekin_for_thrombocytopenia") }

    return unknown_growth_factor()
}

fn growth_factor_count() -> Int {
    return 10
}


// ═══════════════════════════════════════════════════════════════
// SECTION TWO: HEMATOPOIETIC STEM CELL AND LINEAGE COMMITMENT
// ═══════════════════════════════════════════════════════════════
//
// All blood cells derive from a single pluripotent HSC in bone marrow.
// The HSC first commits to either myeloid (CMP) or lymphoid (CLP) lineage.
//
// Myeloid: granulocytes (neutrophils, eosinophils, basophils),
//          monocytes/macrophages, erythrocytes, megakaryocytes/platelets
// Lymphoid: T cells, B cells, NK cells
//
// Hoffbrand 8th ed, Ch 1, Figure 1.3 (hematopoietic tree).

struct HematopoieticProgenitor {
    name: String,
    abbreviation: String,
    lineage: String,
    cd_markers: String,
    gives_rise_to: String,
    key_transcription_factors: String,
    required_growth_factors: String,
}

fn hp(nm: String, abbr: String, lin: String, cd: String, grt: String, tf: String, rgf: String) -> HematopoieticProgenitor {
    return HematopoieticProgenitor { name: nm, abbreviation: abbr, lineage: lin, cd_markers: cd, gives_rise_to: grt, key_transcription_factors: tf, required_growth_factors: rgf }
}

fn lookup_progenitor(abbr: String) -> HematopoieticProgenitor {
    if abbr == "HSC" { return hp("Hematopoietic stem cell", "HSC", "pluripotent", "CD34+CD38-CD90+CD45RA-", "CMP_and_CLP", "RUNX1_TAL1_GATA2", "SCF_TPO_IL3") }
    if abbr == "CMP" { return hp("Common myeloid progenitor", "CMP", "myeloid", "CD34+CD38+IL3Ra_lo_CD45RA-", "GMP_and_MEP", "PU1_CEBPA", "GM-CSF_IL3_SCF") }
    if abbr == "CLP" { return hp("Common lymphoid progenitor", "CLP", "lymphoid", "CD34+CD38+CD10+IL7Ra+", "T_cell_B_cell_NK_cell", "IKAROS_E2A_PAX5", "IL7_SCF_FLT3L") }
    if abbr == "GMP" { return hp("Granulocyte-monocyte progenitor", "GMP", "myeloid", "CD34+CD38+IL3Ra+CD45RA+", "neutrophil_eosinophil_basophil_monocyte", "PU1_CEBPA_CEBPE", "G-CSF_GM-CSF_M-CSF") }
    if abbr == "MEP" { return hp("Megakaryocyte-erythrocyte progenitor", "MEP", "myeloid", "CD34+CD38+IL3Ra-CD45RA-", "erythrocyte_megakaryocyte_platelet", "GATA1_FOG1_KLF1", "EPO_TPO_SCF") }
    if abbr == "proB" { return hp("Pro-B cell", "proB", "lymphoid", "CD34+CD19+CD10+", "pre_B_cell_then_mature_B_cell", "PAX5_EBF1_E2A", "IL7_SCF") }
    if abbr == "proT" { return hp("Pro-T cell", "proT", "lymphoid", "CD34+CD7+CD44+CD25-", "double_positive_then_mature_T_cell", "NOTCH1_GATA3_TCF1", "IL7_SCF_DLL4") }
    return hp("Unknown", "", "", "", "", "", "")
}

fn progenitor_count() -> Int {
    return 7
}


// ═══════════════════════════════════════════════════════════════
// SECTION THREE: RED BLOOD CELLS (ERYTHROCYTES)
// ═══════════════════════════════════════════════════════════════
//
// RBCs are biconcave discs, enucleated, packed with hemoglobin.
// Lifespan ~120 days. Destroyed by splenic macrophages (extravascular
// hemolysis) when they lose deformability.
//
// Normal count: male 4.5-6.5 x10^12/L, female 3.9-5.6 x10^12/L
//
// Hoffbrand 8th ed, Ch 2: Erythropoiesis and general aspects of
//   anaemia, pp 15-25.
// Guyton 14th ed, Ch 33, pp 445-455.

struct ErythrocyteProfile {
    diameter_um: Float,
    volume_fl: Float,
    lifespan_days: Int,
    hemoglobin_pg_per_cell: Float,
    surface_area_um2: Float,
    shape: String,
    nucleus: Bool,
    mitochondria: Bool,
    energy_source: String,
    normal_count_male_per_L: String,
    normal_count_female_per_L: String,
    key_membrane_proteins: String,
    destruction_site: String,
}

fn normal_rbc() -> ErythrocyteProfile {
    return ErythrocyteProfile {
        diameter_um: 7.2,
        volume_fl: 90.0,
        lifespan_days: 120,
        hemoglobin_pg_per_cell: 30.0,
        surface_area_um2: 140.0,
        shape: "biconcave_disc",
        nucleus: false,
        mitochondria: false,
        energy_source: "anaerobic_glycolysis_only",
        normal_count_male_per_L: "4.5-6.5e12",
        normal_count_female_per_L: "3.9-5.6e12",
        key_membrane_proteins: "spectrin_ankyrin_band3_glycophorinA",
        destruction_site: "splenic_macrophages_extravascular_hemolysis",
    }
}


// ═══════════════════════════════════════════════════════════════
// SECTION THREE-A: RBC DISEASES
// ═══════════════════════════════════════════════════════════════
//
// Sickle cell disease: HbS (Glu6Val in beta-globin). HbS polymerizes
// under deoxygenation, distorting RBCs into sickle shapes. Vaso-occlusion,
// hemolysis, organ damage. Heterozygous carriers (sickle trait) have
// malaria resistance (balanced polymorphism).
//
// Thalassemia: reduced or absent globin chain synthesis. Alpha-thal
// (chromosome 16, HBA1/HBA2 deletions) or beta-thal (chromosome 11,
// HBB point mutations). Imbalanced chains precipitate, damaging RBCs.
//
// Hereditary spherocytosis: defects in spectrin, ankyrin, or band 3.
// RBCs lose biconcave shape, become spheres, trapped in spleen.
//
// Hoffbrand 8th ed, Ch 7: Genetic disorders of haemoglobin, pp 72-90.
// Hoffbrand 8th ed, Ch 6: Haemolytic anaemias, pp 56-71.

struct RBCDisease {
    address: Int,
    name: String,
    inheritance: String,
    molecular_defect: String,
    affected_gene: String,
    chromosome: String,
    pathophysiology: String,
    clinical_features: String,
    treatment: String,
}

fn rbc_disease(addr: Int, nm: String, inh: String, def: String, gn: String, chr: String, path: String, clin: String, tx: String) -> RBCDisease {
    return RBCDisease { address: addr, name: nm, inheritance: inh, molecular_defect: def, affected_gene: gn, chromosome: chr, pathophysiology: path, clinical_features: clin, treatment: tx }
}

fn lookup_rbc_disease(addr: Int) -> RBCDisease {
    if addr == 1 { return rbc_disease(1, "Sickle cell disease", "autosomal_recessive", "Glu6Val_in_beta_globin_HbS_polymerizes_when_deoxygenated", "HBB", "11p15.4", "HbS_polymers_distort_RBC_into_sickle_shape_causing_vaso_occlusion_and_hemolysis", "pain_crises_acute_chest_stroke_splenic_sequestration_chronic_hemolytic_anemia", "hydroxyurea_increases_HbF_voxelotor_crizanlizumab_gene_therapy_BMT_curative") }
    if addr == 2 { return rbc_disease(2, "Beta-thalassemia major", "autosomal_recessive", "absent_or_reduced_beta_globin_chain_synthesis_over_200_mutations", "HBB", "11p15.4", "excess_alpha_chains_precipitate_in_erythroid_precursors_causing_ineffective_erythropoiesis_and_hemolysis", "severe_anemia_by_6_months_hepatosplenomegaly_bone_expansion_iron_overload", "regular_transfusions_plus_iron_chelation_desferrioxamine_deferasirox_BMT_curative") }
    if addr == 3 { return rbc_disease(3, "Alpha-thalassemia", "autosomal_recessive", "deletion_of_1_to_4_alpha_globin_genes", "HBA1_HBA2", "16p13.3", "reduced_alpha_chains_excess_beta_chains_form_HbH_tetramers_or_gamma_tetramers_Hb_Barts_in_hydrops", "silent_carrier_1del_trait_2del_HbH_disease_3del_hydrops_fetalis_4del_lethal", "transfusion_for_HbH_disease_hydrops_fetalis_incompatible_with_life") }
    if addr == 4 { return rbc_disease(4, "Hereditary spherocytosis", "autosomal_dominant_most", "defects_in_spectrin_ankyrin_band3_or_protein4.2_membrane_skeleton", "ANK1_SLC4A1_SPTA1_SPTB_EPB42", "various", "loss_of_membrane_surface_area_RBCs_become_spherical_trapped_in_splenic_cords", "anemia_jaundice_splenomegaly_gallstones_positive_osmotic_fragility_test", "folic_acid_splenectomy_if_severe") }
    if addr == 5 { return rbc_disease(5, "G6PD deficiency", "X_linked_recessive", "reduced_glucose-6-phosphate_dehydrogenase_activity", "G6PD", "Xq28", "inadequate_NADPH_for_glutathione_reduction_oxidative_stress_causes_Heinz_bodies_and_hemolysis", "episodic_hemolysis_triggered_by_fava_beans_drugs_sulfonamides_primaquine_infections", "avoid_triggers_transfusion_if_severe_hemolysis") }
    return rbc_disease(0, "Unknown", "", "", "", "", "", "", "")
}

fn rbc_disease_count() -> Int {
    return 5
}


// ═══════════════════════════════════════════════════════════════
// SECTION FOUR: WHITE BLOOD CELLS (LEUKOCYTES)
// ═══════════════════════════════════════════════════════════════
//
// Five types in peripheral blood. Total WBC count: 4.0-11.0 x10^9/L.
//
// Granulocytes: neutrophils, eosinophils, basophils (contain granules)
// Agranulocytes: lymphocytes, monocytes
//
// Hoffbrand 8th ed, Ch 1, pp 4-11; Ch 9, pp 96-110.
// Guyton 14th ed, Ch 34: Resistance of the Body to Infection.

struct LeukocyteType {
    address: Int,
    name: String,
    lineage: String,
    normal_count_per_L: String,
    percentage_of_wbc: String,
    diameter_um: Float,
    lifespan: String,
    nucleus_shape: String,
    granule_staining: String,
    primary_function: String,
    key_markers: String,
    clinical_significance_if_elevated: String,
    clinical_significance_if_decreased: String,
}

fn wbc(addr: Int, nm: String, lin: String, ct: String, pct: String, dia: Float, ls: String, nuc: String, gran: String, func: String, mk: String, elev: String, decr: String) -> LeukocyteType {
    return LeukocyteType { address: addr, name: nm, lineage: lin, normal_count_per_L: ct, percentage_of_wbc: pct, diameter_um: dia, lifespan: ls, nucleus_shape: nuc, granule_staining: gran, primary_function: func, key_markers: mk, clinical_significance_if_elevated: elev, clinical_significance_if_decreased: decr }
}

fn lookup_leukocyte(addr: Int) -> LeukocyteType {
    // Neutrophils: most abundant WBC. First responders to bacterial infection.
    // Kill by phagocytosis, degranulation (MPO, elastase), and NETs (neutrophil
    // extracellular traps). Multilobed nucleus (2-5 lobes). Band forms indicate
    // left shift (acute infection). Hoffbrand 8th ed, Ch 1, pp 4-6.
    if addr == 1 { return wbc(1, "Neutrophil", "myeloid_granulocyte", "2.0-7.5e9", "40-75%", 12.0, "6-10_hours_in_blood_then_1-2_days_in_tissue", "multilobed_2_to_5_lobes", "neutral_pink_granules", "phagocytosis_of_bacteria_and_fungi_degranulation_NET_formation", "CD66b_CD16_CD15", "bacterial_infection_inflammation_stress_CML_left_shift", "neutropenia_chemotherapy_aplastic_anemia_sepsis_risk") }

    // Lymphocytes: adaptive immunity. T cells (thymus-educated), B cells
    // (bone marrow), NK cells (innate lymphoid). Round nucleus, scant cytoplasm.
    // Hoffbrand 8th ed, Ch 9, pp 96-110.
    if addr == 2 { return wbc(2, "Lymphocyte", "lymphoid", "1.5-4.0e9", "20-45%", 9.0, "variable_naive_weeks_to_memory_years_to_decades", "round_dense", "agranular_or_sparse_azurophilic", "adaptive_immunity_T_cells_B_cells_plus_innate_NK_cells", "CD3_T_CD19_CD20_B_CD56_NK", "viral_infection_CLL_ALL_lymphoma", "HIV_AIDS_immunodeficiency_post_chemotherapy") }

    // Monocytes: largest circulating WBC. Migrate to tissues and become
    // macrophages (tissue) or dendritic cells (antigen presentation).
    // Hoffbrand 8th ed, Ch 1, pp 7-8.
    if addr == 3 { return wbc(3, "Monocyte", "myeloid_agranulocyte", "0.2-0.8e9", "2-10%", 16.0, "1-3_days_in_blood_then_months_as_tissue_macrophage", "kidney_or_horseshoe_shaped", "agranular_frosted_glass_cytoplasm", "phagocytosis_antigen_presentation_cytokine_production_tissue_macrophage_precursor", "CD14_CD16_CD64", "chronic_infection_TB_chronic_inflammation_CMML", "aplastic_anemia_hairy_cell_leukemia") }

    // Eosinophils: bilobed nucleus. Granules stain red-orange with eosin.
    // Defense against parasites. Major role in allergy and asthma.
    // Major basic protein (MBP) is toxic to parasites.
    // Hoffbrand 8th ed, Ch 1, p 6.
    if addr == 4 { return wbc(4, "Eosinophil", "myeloid_granulocyte", "0.04-0.4e9", "1-6%", 13.0, "8-12_hours_in_blood_then_8-12_days_in_tissue", "bilobed_spectacle_shaped", "red_orange_eosin_staining_granules", "defense_against_parasites_modulates_allergic_inflammation_releases_MBP", "CD193_CCR3_Siglec8", "parasitic_infection_allergy_asthma_eosinophilic_esophagitis_Churg_Strauss", "acute_stress_steroid_use") }

    // Basophils: rarest WBC. Bilobed nucleus obscured by dark blue granules.
    // Contain histamine and heparin. IgE receptors. Role in anaphylaxis.
    // Hoffbrand 8th ed, Ch 1, p 6.
    if addr == 5 { return wbc(5, "Basophil", "myeloid_granulocyte", "0.01-0.1e9", "0-1%", 11.0, "hours_to_days", "bilobed_obscured_by_granules", "dark_blue_basophilic_granules", "histamine_and_heparin_release_IgE_mediated_hypersensitivity_anaphylaxis", "CD123_CD203c_FcERI", "CML_basophilia_myeloproliferative_disorders_hypersensitivity", "acute_stress_thyrotoxicosis") }

    return wbc(0, "Unknown", "", "", "", 0.0, "", "", "", "", "", "", "")
}

fn leukocyte_count() -> Int {
    return 5
}


// ═══════════════════════════════════════════════════════════════
// SECTION FIVE: PLATELETS (THROMBOCYTES)
// ═══════════════════════════════════════════════════════════════
//
// Platelets are anucleate fragments of megakaryocyte cytoplasm.
// Each megakaryocyte (ploidy 16-64N) produces ~1000-3000 platelets
// by extending proplatelets into marrow sinusoids.
//
// Normal count: 150-400 x10^9/L. Lifespan 8-10 days.
//
// Hoffbrand 8th ed, Ch 25: Platelets, pp 333-347.
// Guyton 14th ed, Ch 36: Hemostasis and Blood Coagulation.

struct PlateletProfile {
    diameter_um: Float,
    volume_fl: Float,
    normal_count_per_L: String,
    lifespan_days: Int,
    parent_cell: String,
    platelets_per_megakaryocyte: String,
    nucleus: Bool,
    key_surface_receptors: String,
    granule_types: String,
    alpha_granule_contents: String,
    dense_granule_contents: String,
    primary_functions: String,
    destruction_site: String,
    key_activators: String,
}

fn normal_platelet() -> PlateletProfile {
    return PlateletProfile {
        diameter_um: 2.5,
        volume_fl: 8.0,
        normal_count_per_L: "150-400e9",
        lifespan_days: 9,
        parent_cell: "megakaryocyte_in_bone_marrow",
        platelets_per_megakaryocyte: "1000-3000",
        nucleus: false,
        key_surface_receptors: "GPIb_vWF_binding_GPIIbIIIa_fibrinogen_binding_GPVI_collagen_binding_PAR1_thrombin",
        granule_types: "alpha_granules_and_dense_granules",
        alpha_granule_contents: "fibrinogen_vWF_factor_V_PDGF_PF4_thrombospondin",
        dense_granule_contents: "ADP_ATP_serotonin_calcium_pyrophosphate",
        primary_functions: "primary_hemostasis_platelet_plug_formation_adhesion_activation_aggregation_secretion",
        destruction_site: "spleen_and_reticuloendothelial_system",
        key_activators: "thrombin_ADP_TXA2_collagen_epinephrine",
    }
}


// ═══════════════════════════════════════════════════════════════
// SECTION SIX: HEMOGLOBIN
// ═══════════════════════════════════════════════════════════════
//
// Hemoglobin is a tetramer of four globin chains, each carrying one
// heme group with a central Fe2+ ion that reversibly binds oxygen.
//
// Adult HbA: alpha2-beta2 (97% of adult Hb)
// Adult HbA2: alpha2-delta2 (2-3%, elevated in beta-thal trait)
// Fetal HbF: alpha2-gamma2 (predominant in fetus, higher O2 affinity)
//
// Cooperative binding: binding of O2 to one subunit increases affinity
// of remaining subunits (T-state to R-state transition).
// Hill coefficient n = 2.8 (perfect non-cooperativity = 1.0).
//
// Bohr effect: H+ and CO2 decrease O2 affinity (right-shift of curve),
// facilitating O2 unloading at tissues.
//
// Perutz MF. Nature 228:726-734, 1970.
// Hoffbrand 8th ed, Ch 3: Hypochromic anaemias, pp 26-39.
// Guyton 14th ed, Ch 41: Transport of Oxygen and Carbon Dioxide.

struct HemoglobinChain {
    address: Int,
    name: String,
    gene: String,
    chromosome: String,
    uniprot: String,
    residues: Int,
    heme_binding_residue: String,
    role: String,
}

fn hb_chain(addr: Int, nm: String, gn: String, chr: String, up: String, res: Int, heme: String, role: String) -> HemoglobinChain {
    return HemoglobinChain { address: addr, name: nm, gene: gn, chromosome: chr, uniprot: up, residues: res, heme_binding_residue: heme, role: role }
}

fn lookup_hemoglobin_chain(addr: Int) -> HemoglobinChain {
    // Alpha chain: two copies in HbA, HbA2, and HbF. Chromosome 16.
    // Proximal histidine F8 (His87) coordinates Fe2+.
    if addr == 1 { return hb_chain(1, "Alpha globin", "HBA1", "16p13.3", "P69905", 142, "His87_proximal_F8", "present_in_all_normal_hemoglobins_HbA_HbA2_HbF") }

    // Beta chain: two copies in HbA. Chromosome 11. Glu6Val = HbS.
    if addr == 2 { return hb_chain(2, "Beta globin", "HBB", "11p15.4", "P68871", 147, "His92_proximal_F8", "adult_hemoglobin_HbA_alpha2beta2") }

    // Gamma chain: two copies in HbF. Higher O2 affinity than beta because
    // gamma lacks the binding site for 2,3-BPG (Ser143 instead of His143).
    if addr == 3 { return hb_chain(3, "Gamma globin", "HBG1", "11p15.4", "P69891", 147, "His92_proximal_F8", "fetal_hemoglobin_HbF_alpha2gamma2_higher_O2_affinity") }

    // Delta chain: two copies in HbA2. Minor adult hemoglobin.
    // Elevated HbA2 (>3.5%) is diagnostic of beta-thalassemia trait.
    if addr == 4 { return hb_chain(4, "Delta globin", "HBD", "11p15.4", "P02042", 147, "His92_proximal_F8", "minor_adult_hemoglobin_HbA2_alpha2delta2_elevated_in_beta_thal_trait") }

    // Epsilon chain: embryonic hemoglobin (Hb Gower 1: zeta2epsilon2).
    if addr == 5 { return hb_chain(5, "Epsilon globin", "HBE1", "11p15.4", "P02100", 147, "His92_proximal_F8", "embryonic_hemoglobin_Hb_Gower_zeta2epsilon2") }

    // Zeta chain: embryonic alpha-like chain. Replaced by alpha at 8 weeks.
    if addr == 6 { return hb_chain(6, "Zeta globin", "HBZ", "16p13.3", "P02008", 142, "His87_proximal_F8", "embryonic_alpha_like_chain_replaced_by_alpha_by_8_weeks_gestation") }

    return hb_chain(0, "Unknown", "", "", "", 0, "", "")
}

fn hemoglobin_chain_count() -> Int {
    return 6
}


// ─── Hemoglobin variants ───

struct HemoglobinVariant {
    address: Int,
    name: String,
    designation: String,
    composition: String,
    mutation: String,
    pathophysiology: String,
    clinical_significance: String,
    prevalence: String,
}

fn hb_var(addr: Int, nm: String, des: String, comp: String, mut_desc: String, path: String, clin: String, prev: String) -> HemoglobinVariant {
    return HemoglobinVariant { address: addr, name: nm, designation: des, composition: comp, mutation: mut_desc, pathophysiology: path, clinical_significance: clin, prevalence: prev }
}

fn lookup_hemoglobin_variant(addr: Int) -> HemoglobinVariant {
    // HbA: normal adult hemoglobin
    if addr == 1 { return hb_var(1, "Hemoglobin A", "HbA", "alpha2_beta2", "none_wild_type", "normal_cooperative_O2_binding_P50_26.6mmHg", "normal_97_percent_of_adult_hemoglobin", "universal") }

    // HbA2: normal minor component
    if addr == 2 { return hb_var(2, "Hemoglobin A2", "HbA2", "alpha2_delta2", "none_wild_type", "slightly_higher_O2_affinity_than_HbA", "2-3_percent_of_adult_Hb_elevated_above_3.5_percent_in_beta_thal_trait", "universal") }

    // HbF: fetal hemoglobin
    if addr == 3 { return hb_var(3, "Fetal hemoglobin", "HbF", "alpha2_gamma2", "gamma_chain_Ser143_cannot_bind_2_3_BPG", "higher_O2_affinity_than_HbA_left_shifted_curve_P50_20mmHg_facilitates_placental_O2_transfer", "predominant_in_fetus_less_than_1_percent_in_adults_therapeutic_target_in_SCD", "universal_in_fetus") }

    // HbS: sickle hemoglobin
    if addr == 4 { return hb_var(4, "Sickle hemoglobin", "HbS", "alpha2_betaS2", "Glu6Val_GAG_to_GTG_in_HBB", "deoxyHbS_polymerizes_into_rigid_fibers_distorting_RBC_into_sickle_shape", "homozygous_SS_causes_sickle_cell_disease_heterozygous_AS_is_sickle_trait_with_malaria_resistance", "8_percent_of_African_Americans_carry_HbS") }

    // HbC: hemoglobin C
    if addr == 5 { return hb_var(5, "Hemoglobin C", "HbC", "alpha2_betaC2", "Glu6Lys_in_HBB", "HbC_crystallizes_in_RBCs_causing_mild_hemolysis_and_target_cells", "homozygous_CC_mild_hemolytic_anemia_SC_disease_with_HbS_is_intermediate_severity", "2-3_percent_of_West_Africans") }

    // HbE: hemoglobin E
    if addr == 6 { return hb_var(6, "Hemoglobin E", "HbE", "alpha2_betaE2", "Glu26Lys_in_HBB_also_activates_cryptic_splice_site", "mildly_unstable_reduced_beta_chain_synthesis_thalassemic_phenotype", "most_common_Hb_variant_worldwide_HbE_beta_thal_can_be_severe", "high_prevalence_Southeast_Asia_up_to_60_percent_in_some_regions") }

    // Methemoglobin: Fe3+ cannot bind O2
    if addr == 7 { return hb_var(7, "Methemoglobin", "MetHb", "alpha2_beta2_with_Fe3+", "Fe2+_oxidized_to_Fe3+_by_drugs_nitrites_dapsone_or_congenital_NADH_reductase_deficiency", "Fe3+_cannot_bind_O2_and_shifts_remaining_heme_to_high_affinity_left_shift", "cyanosis_at_MetHb_above_15_percent_lethal_above_70_percent_treat_with_methylene_blue", "acquired_common_congenital_rare") }

    // Carboxyhemoglobin: CO bound
    if addr == 8 { return hb_var(8, "Carboxyhemoglobin", "CO-Hb", "alpha2_beta2_with_CO", "CO_binds_Fe2+_with_240x_affinity_of_O2", "CO_displaces_O2_and_shifts_remaining_heme_to_high_affinity_left_shift_tissue_hypoxia", "cherry_red_skin_headache_confusion_death_above_60_percent_treat_with_100_percent_O2_or_hyperbaric", "smokers_3-10_percent_nonsmokers_less_than_1_percent") }

    return hb_var(0, "Unknown", "", "", "", "", "", "")
}

fn hemoglobin_variant_count() -> Int {
    return 8
}


// ─── Oxygen binding kinetics ───

struct OxygenBindingParams {
    p50_mmHg: Float,
    hill_coefficient: Float,
    bohr_effect_description: String,
    bpg_effect_description: String,
    temperature_effect: String,
    co2_effect: String,
}

fn normal_o2_binding() -> OxygenBindingParams {
    // P50: partial pressure of O2 at which Hb is 50% saturated.
    // Normal P50 = 26.6 mmHg for HbA at pH 7.4, 37C, normal 2,3-BPG.
    // Hill coefficient 2.8 reflects cooperative binding (1.0 = non-cooperative).
    //
    // Right shift (increased P50, decreased affinity, easier O2 unloading):
    //   increased H+, increased CO2, increased 2,3-BPG, increased temperature
    // Left shift (decreased P50, increased affinity, harder O2 unloading):
    //   decreased H+, decreased CO2, decreased 2,3-BPG, decreased temperature,
    //   HbF, MetHb, CO-Hb
    //
    // Guyton 14th ed, Ch 41, pp 531-540.
    return OxygenBindingParams {
        p50_mmHg: 26.6,
        hill_coefficient: 2.8,
        bohr_effect_description: "H+_and_CO2_bind_to_specific_residues_on_globin_stabilizing_T_state_decreasing_O2_affinity_facilitating_unloading_at_tissues",
        bpg_effect_description: "2_3_BPG_binds_central_cavity_of_deoxy_Hb_stabilizing_T_state_level_increases_in_anemia_altitude_chronic_hypoxia",
        temperature_effect: "increased_temperature_right_shifts_curve_exercising_muscle_unloads_more_O2",
        co2_effect: "CO2_forms_carbamino_compounds_with_N_terminal_amino_groups_of_globin_plus_indirect_Bohr_effect_via_H+_from_carbonic_anhydrase",
    }
}

fn fetal_o2_binding() -> OxygenBindingParams {
    // HbF P50 = ~20 mmHg. Left-shifted compared to HbA.
    // Gamma chains cannot bind 2,3-BPG (Ser143 vs His143 in beta).
    // This allows HbF to extract O2 from maternal HbA across the placenta.
    return OxygenBindingParams {
        p50_mmHg: 20.0,
        hill_coefficient: 2.8,
        bohr_effect_description: "present_but_less_pronounced_than_HbA",
        bpg_effect_description: "gamma_chains_Ser143_cannot_bind_2_3_BPG_accounting_for_higher_O2_affinity",
        temperature_effect: "same_direction_as_HbA",
        co2_effect: "present_facilitates_double_Bohr_effect_at_placenta",
    }
}

fn o2_saturation(po2: Float, p50: Float, n: Float) -> Float {
    // Hill equation: S = pO2^n / (pO2^n + P50^n)
    // where S = fractional saturation, n = Hill coefficient
    //
    // This is NOT sigmoid. This is a power-law cooperative binding curve.
    // The Hill equation naturally produces a sigmoidal SHAPE but the
    // mechanism is cooperative allosteric transition, not logistic function.
    let po2_n = pow(po2, n)
    let p50_n = pow(p50, n)
    return po2_n / (po2_n + p50_n + 0.0000001)
}


// ═══════════════════════════════════════════════════════════════
// SECTION SEVEN: COAGULATION CASCADE -- CLOTTING FACTORS
// ═══════════════════════════════════════════════════════════════
//
// The coagulation cascade is a series of serine protease activations
// that converge on thrombin generation and fibrin clot formation.
//
// Intrinsic pathway: XII -> XI -> IX -> (VIIIa cofactor) -> X
// Extrinsic pathway: TF + VII -> X
// Common pathway: Xa + Va -> prothrombin -> thrombin -> fibrinogen -> fibrin
//
// Factor XIII crosslinks fibrin (gamma-glutamyl-epsilon-lysine bonds)
// to form a stable clot resistant to fibrinolysis.
//
// Davie EW, Ratnoff OD. Science 145:1310-1312, 1964.
// Hoffbrand 8th ed, Ch 26: Coagulation disorders, pp 348-372.
// Furie B, Furie BC. N Engl J Med 359:938-949, 2008.

struct ClottingFactor {
    address: Int,
    roman_numeral: String,
    name: String,
    uniprot: String,
    gene: String,
    chromosome: String,
    factor_type: String,
    pathway: String,
    activated_by: String,
    activates: String,
    cofactor_for: String,
    vitamin_k_dependent: Bool,
    deficiency_disease: String,
    half_life_hours: Float,
}

fn cf(addr: Int, rn: String, nm: String, up: String, gn: String, chr: String, ft: String, pw: String, ab: String, act: String, cof: String, vk: Bool, dd: String, hl: Float) -> ClottingFactor {
    return ClottingFactor { address: addr, roman_numeral: rn, name: nm, uniprot: up, gene: gn, chromosome: chr, factor_type: ft, pathway: pw, activated_by: ab, activates: act, cofactor_for: cof, vitamin_k_dependent: vk, deficiency_disease: dd, half_life_hours: hl }
}

fn unknown_clotting_factor() -> ClottingFactor {
    return cf(0, "", "Unknown", "", "", "", "", "", "", "", "", false, "", 0.0)
}

fn lookup_clotting_factor(addr: Int) -> ClottingFactor {
    // Factor I: Fibrinogen. The substrate. Converted to fibrin by thrombin.
    // Three pairs of chains (Aalpha, Bbeta, gamma) linked by disulfide bonds.
    // Thrombin cleaves fibrinopeptides A and B, exposing polymerization sites.
    // Hoffbrand 8th ed, Ch 26, pp 349-350.
    if addr == 1 { return cf(1, "I", "Fibrinogen", "P02671", "FGA", "4q31.3", "substrate", "common", "constitutively_present_in_plasma_at_2-4_g/L", "polymerizes_to_fibrin_after_thrombin_cleavage", "none", false, "afibrinogenemia_rare_autosomal_recessive_severe_bleeding", 96.0) }

    // Factor II: Prothrombin. Vitamin K-dependent serine protease zymogen.
    // Activated to thrombin (IIa) by prothrombinase complex (Xa + Va + Ca2+ + PL).
    // Thrombin is THE central enzyme: cleaves fibrinogen, activates V, VIII, XI, XIII,
    // protein C. Guyton 14th ed, Ch 36, pp 483-485.
    if addr == 2 { return cf(2, "II", "Prothrombin", "P00734", "F2", "11p11.2", "serine_protease_zymogen", "common", "prothrombinase_complex_Xa_Va_Ca2+_phospholipid", "thrombin_IIa_cleaves_fibrinogen_activates_V_VIII_XI_XIII_protein_C", "none", true, "hypoprothrombinemia_rare_bleeding", 60.0) }

    // Factor III: Tissue Factor (Thromboplastin). Transmembrane glycoprotein.
    // Expressed on subendothelial cells, exposed on vascular injury.
    // Binds VIIa to form the extrinsic tenase complex.
    // Furie B, Furie BC. N Engl J Med 359:938-949, 2008.
    if addr == 3 { return cf(3, "III", "Tissue Factor", "P13726", "F3", "1p21.3", "transmembrane_cofactor", "extrinsic", "constitutively_expressed_on_subendothelial_cells_exposed_on_injury", "TF_VIIa_complex_activates_X_and_IX", "VIIa", false, "not_applicable_essential_for_life", 0.0) }

    // Factor IV: Calcium ions. Required for multiple steps.
    // Not a protein. Chelation by citrate/EDTA prevents clotting in vitro.
    if addr == 4 { return cf(4, "IV", "Calcium ions", "not_a_protein", "N/A", "N/A", "ion_cofactor", "all_pathways", "dietary_absorption_bone_stores_PTH_vitamin_D", "required_for_Gla_domain_binding_to_phospholipid_surfaces", "multiple_complexes", false, "hypocalcemia_can_impair_coagulation_but_cardiac_arrest_occurs_first", 0.0) }

    // Factor V: Labile factor. Cofactor for Xa in prothrombinase complex.
    // Activated by thrombin. Inactivated by activated protein C (APC).
    // Factor V Leiden (Arg506Gln) is resistant to APC = thrombophilia.
    // Hoffbrand 8th ed, Ch 27, p 375.
    if addr == 5 { return cf(5, "V", "Proaccelerin (Labile factor)", "P12259", "F5", "1q24.2", "cofactor", "common", "thrombin_IIa", "none_directly_cofactor_for_Xa_in_prothrombinase_complex", "Xa_in_prothrombinase", false, "parahemophilia_rare_Factor_V_Leiden_Arg506Gln_causes_APC_resistance_thrombophilia", 12.0) }

    // Factor VII: Stable factor. Vitamin K-dependent. Shortest half-life
    // of all clotting factors (~6h). First to decrease with warfarin/VitK deficiency.
    // Binds TF to form extrinsic tenase.
    if addr == 7 { return cf(7, "VII", "Proconvertin (Stable factor)", "P08709", "F7", "13q34", "serine_protease_zymogen", "extrinsic", "TF_VIIa_autoactivation_plus_Xa_IXa_XIIa_thrombin", "TF_VIIa_activates_X_and_IX", "none", true, "factor_VII_deficiency_rare_autosomal_recessive", 6.0) }

    // Factor VIII: Antihemophilic factor. Cofactor for IXa in intrinsic tenase.
    // Circulates bound to vWF (protects from degradation).
    // Deficiency = Hemophilia A (X-linked, 1 in 5000 males).
    // Hoffbrand 8th ed, Ch 26, pp 353-358.
    if addr == 8 { return cf(8, "VIII", "Antihemophilic factor", "P00451", "F8", "Xq28", "cofactor", "intrinsic", "thrombin_IIa", "none_directly_cofactor_for_IXa_in_intrinsic_tenase_complex", "IXa_in_intrinsic_tenase", false, "hemophilia_A_X_linked_recessive_1_in_5000_males", 12.0) }

    // Factor IX: Christmas factor. Vitamin K-dependent serine protease.
    // Activated by XIa or TF-VIIa. Forms intrinsic tenase with VIIIa.
    // Deficiency = Hemophilia B (Christmas disease, X-linked).
    if addr == 9 { return cf(9, "IX", "Christmas factor", "P00740", "F9", "Xq27.1", "serine_protease_zymogen", "intrinsic", "XIa_or_TF_VIIa_complex", "IXa_plus_VIIIa_activates_X_intrinsic_tenase", "none", true, "hemophilia_B_Christmas_disease_X_linked_recessive_1_in_30000_males", 24.0) }

    // Factor X: Stuart-Prower factor. Convergence point of intrinsic and extrinsic.
    // Activated to Xa by either intrinsic tenase (IXa+VIIIa) or extrinsic tenase
    // (TF+VIIa). Xa + Va = prothrombinase. Target of rivaroxaban, apixaban.
    if addr == 10 { return cf(10, "X", "Stuart-Prower factor", "P00742", "F10", "13q34", "serine_protease_zymogen", "common_convergence_point", "intrinsic_tenase_IXa_VIIIa_or_extrinsic_tenase_TF_VIIa", "Xa_plus_Va_converts_prothrombin_to_thrombin_prothrombinase", "none", true, "factor_X_deficiency_rare_autosomal_recessive", 40.0) }

    // Factor XI: Plasma thromboplastin antecedent. Activated by thrombin (feedback)
    // or XIIa. Activates IX. Deficiency = Hemophilia C (Ashkenazi Jews, 8%).
    if addr == 11 { return cf(11, "XI", "Plasma thromboplastin antecedent", "P03951", "F11", "4q35.2", "serine_protease_zymogen", "intrinsic", "thrombin_IIa_feedback_or_XIIa", "XIa_activates_IX", "none", false, "hemophilia_C_Rosenthal_syndrome_autosomal_recessive_common_in_Ashkenazi", 52.0) }

    // Factor XII: Hageman factor. Contact activation. Activated by negatively
    // charged surfaces (glass, kaolin, polyphosphate from platelets).
    // Deficiency causes prolonged aPTT but NO bleeding (not needed in vivo).
    if addr == 12 { return cf(12, "XII", "Hageman factor", "P00748", "F12", "5q35.3", "serine_protease_zymogen", "intrinsic_contact", "negatively_charged_surfaces_kaolin_glass_platelet_polyphosphate", "XIIa_activates_XI_and_prekallikrein", "none", false, "no_bleeding_despite_prolonged_aPTT_contact_activation_not_essential_in_vivo", 50.0) }

    // Factor XIII: Fibrin-stabilizing factor. Transglutaminase. Activated by
    // thrombin + Ca2+. Crosslinks fibrin (gamma-glutamyl-epsilon-lysine bonds).
    // Without XIIIa: clot dissolves easily.
    if addr == 13 { return cf(13, "XIII", "Fibrin-stabilizing factor", "P00488", "F13A1", "6p25.1", "transglutaminase", "common_final_step", "thrombin_IIa_plus_calcium", "crosslinks_fibrin_monomers_gamma_glutamyl_epsilon_lysine_bonds_stabilizes_clot", "none", false, "factor_XIII_deficiency_rare_delayed_bleeding_poor_wound_healing_umbilical_stump_bleeding", 240.0) }

    // von Willebrand Factor: not a numbered factor but essential.
    // Bridges platelet GPIb to exposed collagen (adhesion).
    // Carries and protects Factor VIII in plasma.
    // Deficiency = von Willebrand disease (most common inherited bleeding disorder, 1%).
    if addr == 14 { return cf(14, "vWF", "von Willebrand Factor", "P04275", "VWF", "12p13.31", "adhesive_glycoprotein", "primary_hemostasis_and_VIII_carrier", "constitutively_produced_by_endothelium_and_megakaryocytes_stored_in_Weibel_Palade_bodies", "bridges_platelets_GPIb_to_subendothelial_collagen_carries_factor_VIII", "none", false, "von_Willebrand_disease_most_common_inherited_bleeding_disorder_1_percent", 12.0) }

    // Prekallikrein: Fletcher factor. Contact activation system.
    if addr == 15 { return cf(15, "PK", "Prekallikrein (Fletcher factor)", "P03952", "KLKB1", "4q35.2", "serine_protease_zymogen", "intrinsic_contact", "XIIa", "kallikrein_activates_XII_feedback_and_HMWK", "none", false, "no_bleeding_prolonged_aPTT", 35.0) }

    // HMWK: High molecular weight kininogen. Fitzgerald factor. Contact cofactor.
    if addr == 16 { return cf(16, "HK", "High molecular weight kininogen (Fitzgerald factor)", "P01042", "KNG1", "3q27.3", "cofactor", "intrinsic_contact", "constitutively_present", "cofactor_for_XIIa_activation_of_XI_releases_bradykinin", "XIIa", false, "no_bleeding_prolonged_aPTT_bradykinin_pathway", 156.0) }

    return unknown_clotting_factor()
}

fn clotting_factor_count() -> Int {
    return 16
}

// ─── Lookup by Roman numeral ───

fn clotting_factor_by_numeral(rn: String) -> ClottingFactor {
    if rn == "I" { return lookup_clotting_factor(1) }
    if rn == "II" { return lookup_clotting_factor(2) }
    if rn == "III" { return lookup_clotting_factor(3) }
    if rn == "IV" { return lookup_clotting_factor(4) }
    if rn == "V" { return lookup_clotting_factor(5) }
    if rn == "VII" { return lookup_clotting_factor(7) }
    if rn == "VIII" { return lookup_clotting_factor(8) }
    if rn == "IX" { return lookup_clotting_factor(9) }
    if rn == "X" { return lookup_clotting_factor(10) }
    if rn == "XI" { return lookup_clotting_factor(11) }
    if rn == "XII" { return lookup_clotting_factor(12) }
    if rn == "XIII" { return lookup_clotting_factor(13) }
    if rn == "vWF" { return lookup_clotting_factor(14) }
    if rn == "PK" { return lookup_clotting_factor(15) }
    if rn == "HK" { return lookup_clotting_factor(16) }
    return unknown_clotting_factor()
}


// ═══════════════════════════════════════════════════════════════
// SECTION EIGHT: COAGULATION PATHWAYS
// ═══════════════════════════════════════════════════════════════
//
// The cascade operates through three pathways that converge on
// thrombin generation.
//
// INTRINSIC (measured by aPTT):
//   XII -> XIIa -> XI -> XIa -> IX -> IXa
//   IXa + VIIIa + Ca2+ + PL = intrinsic tenase -> activates X
//
// EXTRINSIC (measured by PT/INR):
//   Tissue injury exposes TF
//   TF + VIIa + Ca2+ + PL = extrinsic tenase -> activates X and IX
//
// COMMON (measured by both PT and aPTT):
//   Xa + Va + Ca2+ + PL = prothrombinase -> prothrombin -> thrombin
//   Thrombin -> fibrinogen -> fibrin monomers -> polymer
//   XIIIa crosslinks fibrin -> stable clot
//
// Davie EW, Ratnoff OD. Science 145:1310-1312, 1964.
// Hoffbrand 8th ed, Ch 26, Figure 26.5.

struct CoagulationPathway {
    name: String,
    lab_test: String,
    normal_range: String,
    initiation: String,
    cascade_steps: String,
    endpoint: String,
    clinical_prolongation: String,
}

fn lookup_coag_pathway(name: String) -> CoagulationPathway {
    if name == "intrinsic" {
        return CoagulationPathway {
            name: "Intrinsic pathway",
            lab_test: "aPTT_activated_partial_thromboplastin_time",
            normal_range: "25-35_seconds",
            initiation: "contact_activation_XIIa_by_negatively_charged_surfaces_or_thrombin_feedback_to_XI",
            cascade_steps: "XII->XIIa->XI->XIa->IX->IXa_then_IXa+VIIIa+Ca2+PL=intrinsic_tenase->X->Xa",
            endpoint: "factor_Xa_generation_feeding_common_pathway",
            clinical_prolongation: "hemophilia_A_factor_VIII_hemophilia_B_factor_IX_heparin_therapy_lupus_anticoagulant",
        }
    }
    if name == "extrinsic" {
        return CoagulationPathway {
            name: "Extrinsic pathway",
            lab_test: "PT_prothrombin_time_and_INR",
            normal_range: "11-13.5_seconds_INR_0.8-1.2_therapeutic_INR_2.0-3.0",
            initiation: "tissue_injury_exposes_tissue_factor_TF_on_subendothelial_cells",
            cascade_steps: "TF+VIIa+Ca2+PL=extrinsic_tenase->X->Xa_also_activates_IX_cross_talk",
            endpoint: "factor_Xa_generation_feeding_common_pathway",
            clinical_prolongation: "warfarin_therapy_vitamin_K_deficiency_liver_disease_factor_VII_deficiency",
        }
    }
    if name == "common" {
        return CoagulationPathway {
            name: "Common pathway",
            lab_test: "both_PT_and_aPTT_prolonged",
            normal_range: "N/A_measured_indirectly",
            initiation: "factor_Xa_generated_by_either_intrinsic_or_extrinsic_tenase",
            cascade_steps: "Xa+Va+Ca2+PL=prothrombinase->II->IIa_thrombin->fibrinogen->fibrin->XIIIa_crosslinks",
            endpoint: "stable_crosslinked_fibrin_clot",
            clinical_prolongation: "factor_X_V_II_I_deficiency_DIC_severe_liver_disease_direct_Xa_or_thrombin_inhibitors",
        }
    }
    return CoagulationPathway { name: "Unknown", lab_test: "", normal_range: "", initiation: "", cascade_steps: "", endpoint: "", clinical_prolongation: "" }
}


// ═══════════════════════════════════════════════════════════════
// SECTION NINE: NATURAL ANTICOAGULANTS
// ═══════════════════════════════════════════════════════════════
//
// The coagulation cascade requires equally powerful brakes.
// Deficiency of any natural anticoagulant = thrombophilia.
//
// Hoffbrand 8th ed, Ch 27: Thrombosis and antithrombotic therapy,
//   pp 373-390.

struct NaturalAnticoagulant {
    address: Int,
    name: String,
    uniprot: String,
    gene: String,
    mechanism: String,
    targets_inhibited: String,
    deficiency_consequence: String,
    clinical_notes: String,
}

fn nac(addr: Int, nm: String, up: String, gn: String, mech: String, tgt: String, def: String, clin: String) -> NaturalAnticoagulant {
    return NaturalAnticoagulant { address: addr, name: nm, uniprot: up, gene: gn, mechanism: mech, targets_inhibited: tgt, deficiency_consequence: def, clinical_notes: clin }
}

fn lookup_anticoagulant(addr: Int) -> NaturalAnticoagulant {
    // Antithrombin III: THE major inhibitor of thrombin and Xa.
    // Serpin (serine protease inhibitor). Heparin accelerates AT-III
    // activity 1000-fold by conformational change.
    if addr == 1 { return nac(1, "Antithrombin III", "P01008", "SERPINC1", "serpin_irreversibly_inhibits_serine_proteases_heparin_accelerates_1000_fold", "thrombin_IIa_Xa_IXa_XIa_XIIa", "heterozygous_deficiency_5-10x_increased_VTE_risk_homozygous_incompatible_with_life", "heparin_works_BY_potentiating_antithrombin_without_AT_heparin_is_useless") }

    // Protein C: vitamin K-dependent. Activated by thrombin-thrombomodulin complex
    // on endothelial surface. APC + protein S inactivates Va and VIIIa.
    // Deficiency: risk of warfarin-induced skin necrosis (protein C has short
    // half-life, drops before other VK-dependent factors on warfarin initiation).
    if addr == 2 { return nac(2, "Protein C", "P04070", "PROC", "vitamin_K_dependent_serine_protease_activated_by_thrombin_thrombomodulin_complex", "inactivates_Va_and_VIIIa_by_proteolytic_cleavage_with_protein_S_cofactor", "heterozygous_7x_VTE_risk_homozygous_neonatal_purpura_fulminans_fatal", "warfarin_skin_necrosis_risk_because_protein_C_half_life_6h_drops_before_II_VII_IX_X") }

    // Protein S: cofactor for APC. Also vitamin K-dependent.
    // Free protein S is the active form (40%). Bound to C4b-binding protein (60%).
    if addr == 3 { return nac(3, "Protein S", "P07225", "PROS1", "cofactor_for_activated_protein_C_also_direct_inhibitor_of_Xa_and_IXa", "enhances_APC_inactivation_of_Va_and_VIIIa", "heterozygous_VTE_risk_increased_homozygous_neonatal_purpura_fulminans", "only_free_protein_S_is_active_40_percent_bound_to_C4b_binding_protein_is_inactive") }

    // TFPI: tissue factor pathway inhibitor. Inhibits TF-VIIa-Xa complex.
    // The first brake on the extrinsic pathway.
    if addr == 4 { return nac(4, "Tissue Factor Pathway Inhibitor", "P10646", "TFPI", "Kunitz_type_inhibitor_binds_Xa_then_TF_VIIa_complex_two_step_inhibition", "TF_VIIa_Xa_extrinsic_tenase_complex", "no_clear_deficiency_syndrome_identified_in_humans_essential_in_mouse_knockout_lethal", "explains_why_extrinsic_pathway_alone_cannot_sustain_coagulation_needs_intrinsic_amplification") }

    return nac(0, "Unknown", "", "", "", "", "", "")
}

fn natural_anticoagulant_count() -> Int {
    return 4
}


// ═══════════════════════════════════════════════════════════════
// SECTION TEN: PHARMACOLOGIC ANTICOAGULANTS
// ═══════════════════════════════════════════════════════════════
//
// Hoffbrand 8th ed, Ch 27, pp 380-388.

struct AnticoagulantDrug {
    address: Int,
    name: String,
    drug_class: String,
    mechanism: String,
    target: String,
    route: String,
    monitoring: String,
    reversal_agent: String,
    key_side_effects: String,
}

fn acd(addr: Int, nm: String, dc: String, mech: String, tgt: String, rt: String, mon: String, rev: String, se: String) -> AnticoagulantDrug {
    return AnticoagulantDrug { address: addr, name: nm, drug_class: dc, mechanism: mech, target: tgt, route: rt, monitoring: mon, reversal_agent: rev, key_side_effects: se }
}

fn lookup_anticoagulant_drug(addr: Int) -> AnticoagulantDrug {
    // Heparin (unfractionated): potentiates antithrombin III.
    // Monitored by aPTT. Reversed by protamine sulfate.
    if addr == 1 { return acd(1, "Unfractionated heparin", "indirect_thrombin_and_Xa_inhibitor", "binds_antithrombin_III_conformational_change_accelerates_inhibition_of_thrombin_and_Xa_1000_fold", "antithrombin_III_potentiation", "IV_or_subcutaneous", "aPTT_target_1.5-2.5x_normal", "protamine_sulfate_1mg_per_100units_heparin", "bleeding_HIT_heparin_induced_thrombocytopenia_osteoporosis_long_term") }

    // LMWH: enoxaparin, dalteparin. Anti-Xa predominant.
    if addr == 2 { return acd(2, "Low molecular weight heparin (enoxaparin)", "indirect_Xa_inhibitor_predominant", "shorter_chains_potentiate_AT_inhibition_of_Xa_but_too_short_to_bridge_AT_to_thrombin", "antithrombin_III_potentiation_anti_Xa_predominant", "subcutaneous", "anti_Xa_levels_if_needed_usually_no_monitoring_required", "protamine_partially_reverses_60_percent", "bleeding_less_HIT_risk_than_UFH") }

    // Warfarin: vitamin K antagonist. Inhibits VKORC1 enzyme.
    // Blocks gamma-carboxylation of factors II, VII, IX, X and proteins C, S.
    // Monitored by PT/INR. Teratogenic.
    if addr == 3 { return acd(3, "Warfarin", "vitamin_K_antagonist", "inhibits_VKORC1_enzyme_blocking_vitamin_K_recycling_prevents_gamma_carboxylation_of_Gla_domains", "factors_II_VII_IX_X_and_proteins_C_S", "oral", "PT_INR_target_2.0-3.0_for_most_indications_2.5-3.5_mechanical_valves", "vitamin_K_IV_for_non_urgent_PCC_4_factor_for_urgent_reversal", "bleeding_teratogenic_skin_necrosis_drug_interactions_CYP2C9_VKORC1_polymorphisms") }

    // Rivaroxaban: direct oral anti-Xa inhibitor (DOAC).
    if addr == 4 { return acd(4, "Rivaroxaban", "direct_oral_Xa_inhibitor_DOAC", "directly_binds_and_inhibits_factor_Xa_active_site_no_AT_required", "factor_Xa_direct", "oral", "no_routine_monitoring_anti_Xa_calibrated_assay_if_needed", "andexanet_alfa_recombinant_modified_Xa_decoy", "bleeding_no_reliable_reversal_until_andexanet") }

    // Apixaban: direct oral anti-Xa inhibitor (DOAC).
    if addr == 5 { return acd(5, "Apixaban", "direct_oral_Xa_inhibitor_DOAC", "directly_binds_and_inhibits_factor_Xa_active_site", "factor_Xa_direct", "oral", "no_routine_monitoring", "andexanet_alfa", "bleeding_lower_bleeding_risk_than_warfarin_in_ARISTOTLE_trial") }

    // Dabigatran: direct thrombin inhibitor (DOAC).
    if addr == 6 { return acd(6, "Dabigatran", "direct_oral_thrombin_inhibitor_DOAC", "directly_binds_thrombin_active_site_competitive_reversible_inhibitor", "thrombin_IIa_direct", "oral", "no_routine_monitoring_dilute_thrombin_time_if_needed", "idarucizumab_humanized_antibody_fragment_binds_dabigatran", "bleeding_dyspepsia_renal_clearance_80_percent_contraindicated_in_severe_CKD") }

    return acd(0, "Unknown", "", "", "", "", "", "", "")
}

fn anticoagulant_drug_count() -> Int {
    return 6
}


// ═══════════════════════════════════════════════════════════════
// SECTION ELEVEN: FIBRINOLYSIS
// ═══════════════════════════════════════════════════════════════
//
// Fibrinolysis dissolves fibrin clots after vascular repair.
// Plasminogen (inactive) -> plasmin (active) by tPA or uPA.
// Plasmin cleaves fibrin into fibrin degradation products (FDPs).
// D-dimer is a specific FDP from crosslinked fibrin (diagnostic marker).
//
// Hoffbrand 8th ed, Ch 26, pp 351-352.

struct FibrinolyticComponent {
    address: Int,
    name: String,
    uniprot: String,
    gene: String,
    component_type: String,
    mechanism: String,
    clinical_significance: String,
}

fn fib(addr: Int, nm: String, up: String, gn: String, ct: String, mech: String, clin: String) -> FibrinolyticComponent {
    return FibrinolyticComponent { address: addr, name: nm, uniprot: up, gene: gn, component_type: ct, mechanism: mech, clinical_significance: clin }
}

fn lookup_fibrinolytic(addr: Int) -> FibrinolyticComponent {
    // Plasminogen: zymogen. Binds to fibrin clot via lysine-binding sites.
    // Activated to plasmin by tPA on fibrin surface (localized fibrinolysis).
    if addr == 1 { return fib(1, "Plasminogen", "P00747", "PLG", "zymogen", "circulating_zymogen_binds_fibrin_via_lysine_binding_sites_converted_to_plasmin_by_tPA_or_uPA", "deficiency_rare_ligneous_conjunctivitis_impaired_wound_healing") }

    // Plasmin: active serine protease. Cleaves fibrin at multiple sites.
    // Generates FDPs including D-dimer from crosslinked fibrin.
    if addr == 2 { return fib(2, "Plasmin", "P00747", "PLG", "active_serine_protease", "cleaves_fibrin_at_multiple_Arg_Lys_sites_generating_FDPs_and_D_dimer_from_XIIIa_crosslinked_fibrin", "excessive_plasmin_causes_hyperfibrinolysis_bleeding") }

    // tPA: tissue plasminogen activator. Released by endothelial cells.
    // tPA binds fibrin, concentrating plasminogen activation ON the clot.
    // Recombinant tPA (alteplase) is thrombolytic therapy for MI, stroke, PE.
    if addr == 3 { return fib(3, "Tissue plasminogen activator", "P00750", "PLAT", "serine_protease_activator", "released_by_endothelium_binds_fibrin_surface_activates_plasminogen_to_plasmin_fibrin_selective", "alteplase_tenecteplase_thrombolytic_therapy_for_acute_MI_ischemic_stroke_massive_PE") }

    // PAI-1: plasminogen activator inhibitor-1. Serpin. Inhibits tPA and uPA.
    // The brake on fibrinolysis. Elevated in metabolic syndrome, obesity.
    if addr == 4 { return fib(4, "Plasminogen activator inhibitor-1", "P05121", "SERPINE1", "serpin_inhibitor", "inhibits_tPA_and_uPA_major_regulator_of_fibrinolysis_released_by_endothelium_and_platelets", "elevated_PAI-1_increases_thrombotic_risk_metabolic_syndrome_obesity_complete_deficiency_causes_bleeding") }

    // Alpha-2-antiplasmin: inhibits free plasmin in circulation.
    // Plasmin bound to fibrin is partially protected from alpha-2-AP.
    if addr == 5 { return fib(5, "Alpha-2-antiplasmin", "P08697", "SERPINF2", "serpin_inhibitor", "rapidly_inhibits_free_plasmin_in_circulation_plasmin_bound_to_fibrin_is_partially_protected", "deficiency_causes_severe_bleeding_disorder_homozygous_rare") }

    // D-dimer: fibrin degradation product specific to crosslinked fibrin.
    // Generated when plasmin cleaves XIIIa-crosslinked fibrin.
    // Clinical: high negative predictive value for VTE.
    if addr == 6 { return fib(6, "D-dimer", "not_a_protein_degradation_product", "N/A", "fibrin_degradation_product", "fragment_from_plasmin_cleavage_of_crosslinked_fibrin_contains_two_D_domains_covalently_linked_by_XIIIa", "elevated_in_DVT_PE_DIC_post_surgical_normal_D_dimer_essentially_excludes_VTE_high_negative_predictive_value") }

    // uPA: urokinase plasminogen activator. Cell-surface fibrinolysis.
    if addr == 7 { return fib(7, "Urokinase plasminogen activator", "P00749", "PLAU", "serine_protease_activator", "cell_surface_bound_activates_plasminogen_important_in_tissue_remodeling_and_cell_migration", "urokinase_used_therapeutically_for_catheter_directed_thrombolysis") }

    return fib(0, "Unknown", "", "", "", "", "")
}

fn fibrinolytic_count() -> Int {
    return 7
}


// ═══════════════════════════════════════════════════════════════
// SECTION TWELVE: ABO AND RH BLOOD GROUP SYSTEMS
// ═══════════════════════════════════════════════════════════════
//
// ABO antigens are carbohydrate structures on RBC surface glycolipids
// and glycoproteins. The H antigen is the precursor; A and B transferases
// add terminal sugars. Type O has H antigen only (no A or B transferase).
//
// Naturally occurring IgM antibodies against absent antigens (isohemagglutinins)
// develop by ~6 months from exposure to environmental bacteria with similar
// carbohydrate epitopes.
//
// Rh system: D antigen is most immunogenic. Rh-negative (dd) individuals
// form anti-D IgG after exposure. Causes hemolytic disease of the fetus
// and newborn (HDFN) in subsequent Rh-positive pregnancies.
//
// Hoffbrand 8th ed, Ch 28: Blood transfusion, pp 391-405.
// Guyton 14th ed, Ch 36, pp 489-491.

struct BloodType {
    address: Int,
    abo_type: String,
    antigens_on_rbc: String,
    antibodies_in_plasma: String,
    genotypes: String,
    can_donate_rbc_to: String,
    can_receive_rbc_from: String,
    frequency_caucasian: String,
    transferase_enzyme: String,
}

fn bt(addr: Int, abo: String, ag: String, ab: String, gen: String, don: String, rec: String, freq: String, enz: String) -> BloodType {
    return BloodType { address: addr, abo_type: abo, antigens_on_rbc: ag, antibodies_in_plasma: ab, genotypes: gen, can_donate_rbc_to: don, can_receive_rbc_from: rec, frequency_caucasian: freq, transferase_enzyme: enz }
}

fn lookup_blood_type(addr: Int) -> BloodType {
    // Type A: A antigen on RBC, anti-B in plasma.
    if addr == 1 { return bt(1, "A", "A_antigen_N_acetylgalactosamine_on_H", "anti_B_IgM", "IA_IA_or_IA_i", "A_and_AB", "A_and_O", "42_percent", "alpha_1_3_N_acetylgalactosaminyltransferase") }

    // Type B: B antigen on RBC, anti-A in plasma.
    if addr == 2 { return bt(2, "B", "B_antigen_galactose_on_H", "anti_A_IgM", "IB_IB_or_IB_i", "B_and_AB", "B_and_O", "10_percent", "alpha_1_3_galactosyltransferase") }

    // Type AB: both antigens, no ABO antibodies. Universal plasma donor.
    // Universal RBC recipient (no anti-A or anti-B to hemolyze donor cells).
    if addr == 3 { return bt(3, "AB", "A_and_B_antigens", "neither_anti_A_nor_anti_B", "IA_IB", "AB_only", "A_B_AB_O_universal_recipient", "4_percent", "both_A_and_B_transferases") }

    // Type O: H antigen only, anti-A and anti-B in plasma.
    // Universal RBC donor (no A or B antigens to trigger recipient antibodies).
    if addr == 4 { return bt(4, "O", "H_antigen_only_no_A_or_B", "anti_A_and_anti_B_IgM", "ii", "A_B_AB_O_universal_donor", "O_only", "44_percent", "no_functional_transferase_H_antigen_unmodified") }

    return bt(0, "Unknown", "", "", "", "", "", "", "")
}

fn blood_type_count() -> Int {
    return 4
}

// ─── Rh system ───

struct RhSystem {
    d_antigen_present: Bool,
    rh_designation: String,
    genotype: String,
    clinical_significance: String,
    hdfn_risk: String,
    prevention: String,
}

fn rh_positive() -> RhSystem {
    return RhSystem {
        d_antigen_present: true,
        rh_designation: "Rh_positive",
        genotype: "DD_or_Dd",
        clinical_significance: "85_percent_of_population_no_anti_D_formation",
        hdfn_risk: "none_from_D_antigen",
        prevention: "not_applicable",
    }
}

fn rh_negative() -> RhSystem {
    return RhSystem {
        d_antigen_present: false,
        rh_designation: "Rh_negative",
        genotype: "dd",
        clinical_significance: "15_percent_of_Caucasians_can_form_anti_D_IgG_after_exposure_to_D_positive_blood",
        hdfn_risk: "Rh_negative_mother_with_Rh_positive_fetus_anti_D_IgG_crosses_placenta_causes_fetal_hemolysis",
        prevention: "Rho_D_immune_globulin_RhoGAM_at_28_weeks_and_within_72h_of_delivery_prevents_sensitization",
    }
}


// ═══════════════════════════════════════════════════════════════
// SECTION THIRTEEN: COMPLETE BLOOD COUNT (CBC) REFERENCE RANGES
// ═══════════════════════════════════════════════════════════════
//
// The CBC is the most commonly ordered blood test in medicine.
// Each parameter has defined normal ranges and clinical significance
// when abnormal.
//
// Hoffbrand 8th ed, Appendix: Normal values.
// Guyton 14th ed, Ch 33, Table 33-1.

struct CBCParameter {
    address: Int,
    name: String,
    abbreviation: String,
    unit: String,
    normal_range_male: String,
    normal_range_female: String,
    what_it_measures: String,
    elevated_significance: String,
    decreased_significance: String,
}

fn cbc(addr: Int, nm: String, abbr: String, unit: String, nrm: String, nrf: String, meas: String, elev: String, decr: String) -> CBCParameter {
    return CBCParameter { address: addr, name: nm, abbreviation: abbr, unit: unit, normal_range_male: nrm, normal_range_female: nrf, what_it_measures: meas, elevated_significance: elev, decreased_significance: decr }
}

fn lookup_cbc(addr: Int) -> CBCParameter {
    // WBC: white blood cell count
    if addr == 1 { return cbc(1, "White blood cell count", "WBC", "x10^9/L", "4.0-11.0", "4.0-11.0", "total_circulating_leukocytes", "leukocytosis_infection_inflammation_CML_stress_steroids_smoking", "leukopenia_bone_marrow_failure_chemotherapy_aplastic_anemia_overwhelming_sepsis") }

    // RBC: red blood cell count
    if addr == 2 { return cbc(2, "Red blood cell count", "RBC", "x10^12/L", "4.5-6.5", "3.9-5.6", "total_circulating_erythrocytes", "polycythemia_vera_dehydration_chronic_hypoxia_EPO_producing_tumors", "anemia_bleeding_hemolysis_bone_marrow_failure_nutritional_deficiency") }

    // Hemoglobin: Hgb
    if addr == 3 { return cbc(3, "Hemoglobin", "Hgb", "g/dL", "13.5-17.5", "12.0-16.0", "oxygen_carrying_capacity_of_blood", "polycythemia_dehydration_altitude", "anemia_defined_as_Hgb_below_reference_range_for_age_and_sex") }

    // Hematocrit: Hct (percentage of blood volume that is RBCs)
    if addr == 4 { return cbc(4, "Hematocrit", "Hct", "%", "40-54", "36-48", "fraction_of_blood_volume_occupied_by_RBCs", "polycythemia_dehydration", "anemia_overhydration_bleeding") }

    // MCV: mean corpuscular volume (average RBC size)
    if addr == 5 { return cbc(5, "Mean corpuscular volume", "MCV", "fL", "80-100", "80-100", "average_RBC_volume_classifies_anemia_as_microcytic_normocytic_macrocytic", "macrocytic_above_100fL_B12_folate_deficiency_MDS_liver_disease_hypothyroid_reticulocytosis", "microcytic_below_80fL_iron_deficiency_thalassemia_trait_chronic_disease_sideroblastic") }

    // MCH: mean corpuscular hemoglobin (average Hb per RBC)
    if addr == 6 { return cbc(6, "Mean corpuscular hemoglobin", "MCH", "pg", "27-33", "27-33", "average_hemoglobin_mass_per_RBC", "parallels_MCV_macrocytic_anemias", "parallels_MCV_microcytic_hypochromic_anemias_iron_deficiency_thalassemia") }

    // MCHC: mean corpuscular hemoglobin concentration
    if addr == 7 { return cbc(7, "Mean corpuscular hemoglobin concentration", "MCHC", "g/dL", "32-36", "32-36", "average_hemoglobin_concentration_per_RBC", "spherocytosis_dehydrated_cells_sickle_cell", "hypochromic_iron_deficiency_thalassemia") }

    // RDW: red cell distribution width (variation in RBC size)
    if addr == 8 { return cbc(8, "Red cell distribution width", "RDW", "%", "11.5-14.5", "11.5-14.5", "coefficient_of_variation_of_RBC_volume_anisocytosis", "iron_deficiency_high_RDW_vs_thalassemia_trait_normal_RDW_both_microcytic_key_differentiator", "low_RDW_is_normal_uniform_RBC_population") }

    // Platelet count
    if addr == 9 { return cbc(9, "Platelet count", "PLT", "x10^9/L", "150-400", "150-400", "circulating_platelet_count", "thrombocytosis_reactive_infection_inflammation_iron_deficiency_or_primary_myeloproliferative", "thrombocytopenia_ITP_TTP_HUS_DIC_bone_marrow_failure_drugs_heparin_HIT") }

    // Reticulocyte count: immature RBCs, marker of marrow erythroid activity
    if addr == 10 { return cbc(10, "Reticulocyte count", "Retic", "% or x10^9/L", "0.5-2.5% or 25-125e9", "0.5-2.5% or 25-125e9", "immature_RBCs_reflects_bone_marrow_erythropoietic_activity", "appropriate_reticulocytosis_in_hemolysis_or_bleeding_marrow_responding", "reticulocytopenia_in_anemia_suggests_marrow_failure_aplastic_B12_iron_deficiency_before_treatment") }

    return cbc(0, "Unknown", "", "", "", "", "", "", "")
}

fn cbc_parameter_count() -> Int {
    return 10
}

// ─── Lookup CBC by abbreviation ───

fn cbc_by_abbreviation(abbr: String) -> CBCParameter {
    if abbr == "WBC" { return lookup_cbc(1) }
    if abbr == "RBC" { return lookup_cbc(2) }
    if abbr == "Hgb" { return lookup_cbc(3) }
    if abbr == "Hct" { return lookup_cbc(4) }
    if abbr == "MCV" { return lookup_cbc(5) }
    if abbr == "MCH" { return lookup_cbc(6) }
    if abbr == "MCHC" { return lookup_cbc(7) }
    if abbr == "RDW" { return lookup_cbc(8) }
    if abbr == "PLT" { return lookup_cbc(9) }
    if abbr == "Retic" { return lookup_cbc(10) }
    return lookup_cbc(0)
}


// ═══════════════════════════════════════════════════════════════
// SECTION FOURTEEN: CLINICAL HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════════════

fn classify_anemia_by_mcv(mcv: Float) -> String {
    // MCV-based classification is the first step in anemia workup.
    // Hoffbrand 8th ed, Ch 2, Figure 2.8.
    if mcv < 80.0 { return "microcytic_iron_deficiency_thalassemia_chronic_disease_sideroblastic" }
    if mcv > 100.0 { return "macrocytic_B12_folate_deficiency_MDS_liver_disease_hypothyroid_drugs" }
    return "normocytic_acute_blood_loss_hemolysis_chronic_disease_renal_failure_marrow_infiltration"
}

fn is_anemic_male(hgb: Float) -> Bool {
    return hgb < 13.5
}

fn is_anemic_female(hgb: Float) -> Bool {
    return hgb < 12.0
}

fn is_thrombocytopenic(plt: Float) -> Bool {
    return plt < 150.0
}

fn is_neutropenic(anc: Float) -> Bool {
    // ANC < 1.5 x10^9/L = neutropenia.
    // ANC < 0.5 = severe neutropenia (high infection risk).
    return anc < 1.5
}

fn is_leukocytosis(wbc: Float) -> Bool {
    return wbc > 11.0
}

fn differentiate_microcytic(rdw: Float, mcv: Float) -> String {
    // Key differentiator: iron deficiency has HIGH RDW (anisocytosis)
    // while thalassemia trait has NORMAL RDW (uniform small cells).
    // Mentzer index (MCV/RBC) < 13 suggests thal trait, > 13 suggests iron deficiency.
    // Hoffbrand 8th ed, Ch 3, p 30 and Ch 7, p 79.
    if mcv >= 80.0 { return "not_microcytic" }
    if rdw > 14.5 { return "likely_iron_deficiency_high_RDW_anisocytosis" }
    return "likely_thalassemia_trait_normal_RDW_uniform_microcytes"
}

fn calculate_mentzer_index(mcv: Float, rbc_count: Float) -> Float {
    // Mentzer index = MCV / RBC count
    // Less than 13: suggests thalassemia trait
    // Greater than 13: suggests iron deficiency anemia
    // Simple screening tool, not definitive.
    if rbc_count < 0.001 { return 0.0 }
    return mcv / rbc_count
}

fn interpret_mentzer(index_val: Float) -> String {
    if index_val < 13.0 { return "suggests_thalassemia_trait" }
    return "suggests_iron_deficiency_anemia"
}


// ═══════════════════════════════════════════════════════════════
// SECTION FIFTEEN: SUMMARY COUNTS
// ═══════════════════════════════════════════════════════════════

fn hematology_total_structs() -> Int {
    return 16
}

fn hematology_total_lookup_entries() -> Int {
    // Growth factors: ten
    // Progenitors: seven
    // RBC diseases: five
    // Leukocyte types: five
    // Hemoglobin chains: six
    // Hemoglobin variants: eight
    // Clotting factors: sixteen
    // Natural anticoagulants: four
    // Anticoagulant drugs: six
    // Fibrinolytic components: seven
    // Blood types: four
    // CBC parameters: ten
    return 10 + 7 + 5 + 5 + 6 + 8 + 16 + 4 + 6 + 7 + 4 + 10
}
