// immune_system.sy -- Human immunology as native Scyla.
//
// The complete innate and adaptive immune system: cells, receptors,
// antibodies, complement, cytokines, MHC, and pattern recognition.
// Every protein cited with UniProt accession. Every cell with surface
// markers. Every pathway with mechanism.
//
// The immune system is the original learning architecture. Random
// receptor generation (V(D)J), selection pressure (thymic education),
// memory formation (checkpoint saving), and tolerance (alignment).
// Biology solved these problems before silicon existed.
//
// Sources:
//   Abbas AK, Lichtman AH, Pillai S. Cellular and Molecular
//     Immunology, 10th ed. Elsevier, 2022.
//   Murphy K, Weaver C. Janeway's Immunobiology, 10th ed.
//     Garland Science, 2022.
//   Chaplin DD. J Allergy Clin Immunol 125:S3-23, 2010.
//   Medzhitov R. Nature 449:819-826, 2007 (innate recognition).
//   Tonegawa S. Nature 302:575-581, 1983 (V(D)J, Nobel 1987).
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536

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

struct InnateCell {
    name: String,
    lineage: String,
    surface_markers: String,
    key_protein: String,
    key_protein_accession: String,
    function_desc: String,
    location: String,
    lifespan: String,
    clinical: String,
    citation: String,
}

struct AdaptiveCell {
    name: String,
    subset: String,
    surface_markers: String,
    key_cytokines: String,
    key_protein: String,
    key_protein_accession: String,
    function_desc: String,
    differentiation_signal: String,
    clinical: String,
    citation: String,
}

struct Antibody {
    class_name: String,
    heavy_chain: String,
    structure: String,
    molecular_weight_kda: Float,
    serum_half_life_days: Float,
    serum_concentration_pct: Float,
    function_desc: String,
    placental_transfer: Bool,
    complement_activation: Bool,
    clinical: String,
    citation: String,
}

struct MhcMolecule {
    name: String,
    mhc_class: Int,
    gene_locus: String,
    expression: String,
    peptide_length: String,
    function_desc: String,
    key_protein_accession: String,
    disease_association: String,
    clinical: String,
    citation: String,
}

struct ComplementComponent {
    name: String,
    pathway: String,
    function_desc: String,
    key_protein_accession: String,
    deficiency_disease: String,
    citation: String,
}

struct Cytokine {
    name: String,
    primary_source: String,
    target_cells: String,
    function_desc: String,
    key_protein_accession: String,
    clinical_relevance: String,
    citation: String,
}

struct PatternReceptor {
    name: String,
    receptor_family: String,
    ligand: String,
    signaling_pathway: String,
    key_protein_accession: String,
    cellular_location: String,
    function_desc: String,
    citation: String,
}

// ═══════════════════════════════════════════════════════════
// CONSTRUCTOR HELPERS
// ═══════════════════════════════════════════════════════════

fn icell(n: String, li: String, sm: String, kp: String, kpa: String, fd: String, lo: String, ls: String, cl: String, ci: String) -> InnateCell {
    return InnateCell { name: n, lineage: li, surface_markers: sm, key_protein: kp, key_protein_accession: kpa, function_desc: fd, location: lo, lifespan: ls, clinical: cl, citation: ci }
}

fn acell(n: String, su: String, sm: String, kc: String, kp: String, kpa: String, fd: String, ds: String, cl: String, ci: String) -> AdaptiveCell {
    return AdaptiveCell { name: n, subset: su, surface_markers: sm, key_cytokines: kc, key_protein: kp, key_protein_accession: kpa, function_desc: fd, differentiation_signal: ds, clinical: cl, citation: ci }
}

fn abclass(cn: String, hc: String, st: String, mw: Float, hl: Float, sc: Float, fd: String, pt: Bool, ca: Bool, cl: String, ci: String) -> Antibody {
    return Antibody { class_name: cn, heavy_chain: hc, structure: st, molecular_weight_kda: mw, serum_half_life_days: hl, serum_concentration_pct: sc, function_desc: fd, placental_transfer: pt, complement_activation: ca, clinical: cl, citation: ci }
}

fn mhc(n: String, mc: Int, gl: String, ex: String, pl: String, fd: String, kpa: String, da: String, cl: String, ci: String) -> MhcMolecule {
    return MhcMolecule { name: n, mhc_class: mc, gene_locus: gl, expression: ex, peptide_length: pl, function_desc: fd, key_protein_accession: kpa, disease_association: da, clinical: cl, citation: ci }
}

fn comp(n: String, pw: String, fd: String, kpa: String, dd: String, ci: String) -> ComplementComponent {
    return ComplementComponent { name: n, pathway: pw, function_desc: fd, key_protein_accession: kpa, deficiency_disease: dd, citation: ci }
}

fn cyto(n: String, ps: String, tc: String, fd: String, kpa: String, cr: String, ci: String) -> Cytokine {
    return Cytokine { name: n, primary_source: ps, target_cells: tc, function_desc: fd, key_protein_accession: kpa, clinical_relevance: cr, citation: ci }
}

fn prr(n: String, rf: String, li: String, sp: String, kpa: String, cl: String, fd: String, ci: String) -> PatternReceptor {
    return PatternReceptor { name: n, receptor_family: rf, ligand: li, signaling_pathway: sp, key_protein_accession: kpa, cellular_location: cl, function_desc: fd, citation: ci }
}

// ═══════════════════════════════════════════════════════════
// INNATE IMMUNITY CELLS
// ═══════════════════════════════════════════════════════════
// The first responders. No memory. No specificity beyond
// pattern recognition. Fast, blunt, and essential.
// Without innate immunity, adaptive immunity never activates.

fn innate_cell(name: String) -> InnateCell {
    if name == "neutrophil" { return icell("Neutrophil", "Myeloid (granulocyte)", "CD15+, CD16+, CD66b+, CD11b+", "Myeloperoxidase (MPO)", "P05164", "Most abundant WBC (60-70%). First to arrive at infection (hours). Kills via phagocytosis, degranulation (defensins, lysozyme), reactive oxygen species (respiratory burst via NADPH oxidase), and neutrophil extracellular traps (NETs: expelled chromatin that traps bacteria). Short-lived kamikaze cells.", "Blood, rapidly migrate to tissues via chemotaxis (IL-8/CXCL8)", "6-12 hours in blood, 1-2 days in tissue", "Neutropenia (ANC less than 1500): severe infection risk. Chronic granulomatous disease (CGD): NADPH oxidase deficiency, cannot make ROS. Pus = dead neutrophils.", "Abbas 10th ed Ch 4; Brinkmann V et al. Science 303:1532, 2004 (NETs)") }

    if name == "macrophage" { return icell("Macrophage", "Myeloid (monocyte-derived)", "CD14+, CD68+, CD163+ (M2), CD80/CD86+ (M1)", "CD14 (LPS co-receptor)", "P08571", "Professional phagocyte. Sentinel in tissues (derived from blood monocytes). M1 (classical): pro-inflammatory, microbicidal, activated by IFN-gamma + LPS. M2 (alternative): anti-inflammatory, tissue repair, activated by IL-4/IL-13. Presents antigen on MHC-II to CD4 T-cells. Produces TNF-alpha, IL-1, IL-6, IL-12. Tissue-specific names: Kupffer cells (liver), microglia (brain), alveolar macrophages (lung), osteoclasts (bone).", "All tissues (resident populations)", "Months to years in tissues", "Granuloma formation in TB and sarcoidosis. Gaucher disease: glucocerebrosidase deficiency causes macrophage lipid accumulation. Tumor-associated macrophages (TAMs) promote cancer.", "Abbas 10th ed Ch 4; Murray PJ, Wynn TA. Nat Rev Immunol 11:723, 2011 (M1/M2)") }

    if name == "dendritic_cell" { return icell("Dendritic cell (DC)", "Myeloid or plasmacytoid lineage", "CD11c+ (myeloid DC), CD123+ (plasmacytoid DC), MHC-II high, CD80/CD86+, CD40+", "DEC-205 (CD205, antigen uptake receptor)", "Q9UBG0", "The bridge between innate and adaptive immunity. Professional antigen-presenting cell (APC). Immature DCs in tissue capture antigen, then migrate to lymph nodes, maturing en route. Mature DCs upregulate MHC-II, CD80/CD86, present peptide to naive T-cells. Only cell that can activate NAIVE T-cells. Plasmacytoid DCs produce massive IFN-alpha in viral infections.", "Skin (Langerhans cells), mucosal surfaces, lymph nodes", "Days to weeks", "Langerhans cell histiocytosis. DC vaccines in cancer immunotherapy (sipuleucel-T for prostate cancer). Plasmacytoid DCs in SLE produce pathogenic type I IFN.", "Abbas 10th ed Ch 6; Steinman RM. Annu Rev Immunol 10:271, 1991 (Nobel 2011)") }

    if name == "nk_cell" { return icell("Natural killer (NK) cell", "Lymphoid (innate lymphoid cell, ILC1-like)", "CD56+, CD16+ (FcgammaRIII), CD3-negative, NKG2D+, KIR+", "Perforin", "P14222", "Kills virus-infected cells and tumor cells WITHOUT prior sensitization (no TCR needed). Two mechanisms: (a) Missing-self recognition: KIR receptors detect MHC-I. Cells that downregulate MHC-I (virus evasion, tumor) lose inhibitory signal and get killed. (b) ADCC: CD16 binds IgG Fc on antibody-coated targets, triggers killing. Produces IFN-gamma to activate macrophages.", "Blood, spleen, liver", "1-2 weeks", "NK cell deficiency: severe herpesvirus infections. NK-based cancer immunotherapy. Anti-KIR antibodies (lirilumab) remove inhibition to enhance tumor killing.", "Abbas 10th ed Ch 4; Vivier E et al. Science 331:44, 2011") }

    if name == "mast_cell" { return icell("Mast cell", "Myeloid (from CD34+ bone marrow progenitor)", "CD117+ (c-Kit), FcepsilonRI+ (high-affinity IgE receptor), CD203c+", "Tryptase (mast cell-specific protease)", "Q15661", "Tissue-resident sentinel. Granules contain histamine, heparin, tryptase, chymase, TNF-alpha. Activation: IgE cross-linking on FcepsilonRI (allergy/anaphylaxis), complement (C3a, C5a), direct tissue damage. Degranulation releases mediators within seconds. Produces prostaglandins (PGD2) and leukotrienes (LTC4). Critical in allergy, anaphylaxis, and anti-helminth defense.", "Tissues near blood vessels, nerves, mucosal surfaces (skin, gut, lung)", "Weeks to months in tissues", "Anaphylaxis: systemic mast cell degranulation, hypotension, bronchospasm. Mastocytosis: clonal mast cell proliferation (KIT D816V mutation). Allergic rhinitis, asthma, urticaria.", "Abbas 10th ed Ch 20; Galli SJ et al. Nat Immunol 6:135, 2005") }

    if name == "eosinophil" { return icell("Eosinophil", "Myeloid (granulocyte)", "CD193+ (CCR3), Siglec-8+, CD11b+, CD125+ (IL-5R)", "Major basic protein (MBP)", "Q13753", "Anti-parasitic effector cell. Granules contain major basic protein (MBP), eosinophil cationic protein (ECP), eosinophil peroxidase (EPO), eosinophil-derived neurotoxin (EDN). Activated by IL-5 (from Th2 cells). Kills helminths too large for phagocytosis by degranulation onto parasite surface. Also contributes to allergic inflammation and asthma (late-phase response).", "Blood (1-4% WBC), tissues (GI tract, airways in disease)", "8-12 hours in blood, 8-12 days in tissue", "Eosinophilia: parasitic infections, allergic diseases, Churg-Strauss syndrome, hypereosinophilic syndrome. Anti-IL-5 therapy (mepolizumab) for severe eosinophilic asthma. Eosinophilic esophagitis.", "Abbas 10th ed Ch 20; Rothenberg ME. N Engl J Med 338:1592, 1998") }

    if name == "basophil" { return icell("Basophil", "Myeloid (granulocyte)", "CD123+, FcepsilonRI+, CD203c+, CD49b+", "IL-4 (major early source)", "P05112", "Rarest granulocyte (less than 1% WBC). Shares IgE-mediated activation with mast cells but circulates in blood. Granules contain histamine and heparin. Major early source of IL-4 (drives Th2 differentiation). Important in anti-helminth immunity and allergic inflammation. Can present antigen on MHC-II in some contexts.", "Blood (rarely enters tissues)", "Days", "Basophil activation test (BAT): flow cytometry-based allergy diagnostic. Chronic myeloid leukemia: basophilia is a hallmark. Role in atopic dermatitis.", "Abbas 10th ed Ch 20; Karasuyama H et al. Annu Rev Immunol 29:45, 2011") }

    return icell("", "", "", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════════
// ADAPTIVE IMMUNITY CELLS
// ═══════════════════════════════════════════════════════════
// Specific. Clonal. Memory. Slow to start, devastating once
// committed. The learning system that remembers.
// See also: tcell.sy for the full T-cell education model.

fn adaptive_cell(name: String) -> AdaptiveCell {
    // --- CD4+ T helper subsets ---

    if name == "th1" { return acell("CD4+ Th1 helper", "T helper type 1", "CD4+, CXCR3+, CCR5+, T-bet+", "IFN-gamma, TNF-alpha, IL-2", "T-bet (TBX21, master TF)", "Q9UL17", "Drives cell-mediated immunity against intracellular pathogens (viruses, intracellular bacteria like M. tuberculosis, Listeria). IFN-gamma activates macrophages (classical M1 activation), enhances MHC expression, promotes IgG opsonizing antibody class switching. Excessive Th1 responses cause organ-specific autoimmunity.", "IL-12 + IFN-gamma (from DCs/macrophages/NK cells)", "Protective: TB, Leishmania. Pathologic: Type 1 diabetes, MS, rheumatoid arthritis, Crohn disease. IFN-gamma blockade (emapalumab) for hemophagocytic lymphohistiocytosis.", "Abbas 10th ed Ch 10; Szabo SJ et al. Science 295:338, 2002 (T-bet)") }

    if name == "th2" { return acell("CD4+ Th2 helper", "T helper type 2", "CD4+, CCR4+, CRTH2+, GATA-3+", "IL-4, IL-5, IL-13", "GATA-3 (master TF)", "P23771", "Drives humoral immunity and anti-helminth defense. IL-4 promotes B-cell IgE class switching. IL-5 activates eosinophils. IL-13 causes mucus hypersecretion, smooth muscle contraction, alternative macrophage activation (M2). Evolved for parasite defense but causes allergy/asthma in developed world.", "IL-4 (from basophils, mast cells, or T-cells)", "Protective: helminth infections. Pathologic: allergic asthma, allergic rhinitis, atopic dermatitis, anaphylaxis. Anti-IL-4R (dupilumab) for atopic dermatitis and asthma.", "Abbas 10th ed Ch 10; Zhu J et al. Annu Rev Immunol 24:607, 2006") }

    if name == "th17" { return acell("CD4+ Th17 helper", "T helper type 17", "CD4+, CCR6+, CD161+, RORgamma-t+", "IL-17A, IL-17F, IL-22, IL-21", "RORgamma-t (master TF)", "P51449", "Mucosal barrier defense against extracellular bacteria (Klebsiella, S. aureus) and fungi (Candida). IL-17 recruits neutrophils via CXCL1/CXCL8. IL-22 induces antimicrobial peptides (defensins, RegIII) from epithelial cells. Critical for gut and skin barrier integrity.", "IL-6 + TGF-beta (+ IL-23 for stabilization)", "Protective: mucosal candidiasis (APECED, Job syndrome = hyper-IgE). Pathologic: psoriasis, psoriatic arthritis, ankylosing spondylitis, IBD. Anti-IL-17A (secukinumab) for psoriasis. Anti-IL-23 (guselkumab).", "Abbas 10th ed Ch 10; Ivanov II et al. Cell 126:1121, 2006") }

    if name == "treg" { return acell("CD4+ Regulatory T cell (Treg)", "Regulatory", "CD4+, CD25-high, FOXP3+, CTLA-4+, CD127-low", "IL-10, TGF-beta, IL-35", "FOXP3 (master TF)", "Q9BZS1", "The alignment layer. Suppresses immune responses to maintain self-tolerance and prevent autoimmunity. Mechanisms: (a) IL-10/TGF-beta secretion inhibits effector cells, (b) CTLA-4 outcompetes CD28 for B7, removing costimulation, (c) IL-2 consumption (high-affinity CD25) starves effector T-cells, (d) granzyme/perforin kills effector cells directly. Natural Tregs (nTreg): thymic origin. Induced Tregs (iTreg): peripheral conversion by TGF-beta.", "Thymic: intermediate self-affinity during negative selection. Peripheral: TGF-beta + IL-2 (without IL-6)", "FOXP3 mutation causes IPEX syndrome (immune dysregulation, polyendocrinopathy, enteropathy, X-linked): fatal multi-organ autoimmunity. Treg therapy in transplant tolerance. Tumor Tregs suppress anti-tumor immunity (checkpoint targets).", "Abbas 10th ed Ch 15; Fontenot JD et al. Nat Immunol 4:330, 2003 (FOXP3)") }

    if name == "cd8_cytotoxic" { return acell("CD8+ Cytotoxic T lymphocyte (CTL)", "Cytotoxic effector", "CD8+, TCR-alpha/beta+, CD3+, perforin+, granzyme B+", "IFN-gamma, TNF-alpha, perforin, granzyme B", "Perforin-1 (PRF1)", "P14222", "The executioner. Kills virus-infected cells and tumor cells expressing foreign peptide on MHC-I. Two killing mechanisms: (a) Perforin/granzyme pathway: perforin polymerizes pores in target membrane, granzyme B enters and cleaves caspases triggering apoptosis. (b) Fas-FasL: FasL on CTL binds Fas (CD95) on target, activates caspase-8 cascade. Killing is antigen-specific and serial (one CTL kills multiple targets).", "IL-2 + antigen on MHC-I (with CD4 T-cell help for full activation)", "Viral clearance (influenza, HIV, CMV, EBV). Anti-tumor immunity. Graft rejection. Hemophagocytic lymphohistiocytosis (perforin mutations). CAR-T cell therapy uses engineered CTLs.", "Abbas 10th ed Ch 11; Voskoboinik I et al. Nat Rev Immunol 15:388, 2015 (perforin/granzyme)") }

    // --- B cell subsets ---

    if name == "b_cell_naive" { return acell("Naive B cell", "B lymphocyte", "CD19+, CD20+, CD21+, surface IgM+, surface IgD+, MHC-II+, CD40+", "None (resting)", "CD19 (co-receptor complex)", "P15391", "Mature naive B cell in peripheral lymphoid organs. Surface IgM and IgD serve as B-cell receptor (BCR). Upon antigen binding + T-cell help (CD40L-CD40 interaction + cytokines from Tfh cells), enters germinal center for somatic hypermutation and class switching. TD (thymus-dependent) antigens require T-cell help. TI (thymus-independent) antigens (polysaccharides, LPS) activate B cells directly.", "Bone marrow (maturation), then blood and peripheral lymphoid organs", "Protective: antibody production against all pathogens. X-linked agammaglobulinemia (Bruton disease): BTK mutation, no mature B cells, no antibodies. Anti-CD20 (rituximab) depletes B cells in autoimmunity and lymphoma.", "Abbas 10th ed Ch 12; Kurosaki T et al. Annu Rev Immunol 28:21, 2010") }

    if name == "plasma_cell" { return acell("Plasma cell", "B lymphocyte (terminally differentiated)", "CD138+ (syndecan-1), CD38-high, CD19-low/neg, CD20-neg, surface Ig-neg", "Secretes ~2000 antibody molecules per second", "XBP1 (master TF for plasma cell)", "O75840", "Antibody factory. Terminally differentiated B cell that has ceased proliferation and dedicated all biosynthetic machinery to antibody secretion. Short-lived plasma cells (days-weeks) in extrafollicular foci. Long-lived plasma cells (decades) in bone marrow: the reason vaccines provide lasting protection. Secrete switched, affinity-matured antibodies (IgG, IgA, IgE).", "Germinal center reaction (Tfh help + somatic hypermutation + class switching)", "Multiple myeloma: malignant plasma cell neoplasm. Produces monoclonal Ig (M-protein). Bence Jones proteinuria. Waldenstrom macroglobulinemia (IgM-secreting). Bortezomib (proteasome inhibitor) targets plasma cells.", "Abbas 10th ed Ch 12; Nutt SL et al. Nat Rev Immunol 15:160, 2015") }

    if name == "memory_b_cell" { return acell("Memory B cell", "B lymphocyte (long-lived)", "CD19+, CD20+, CD27+, surface switched Ig (IgG/IgA/IgE)+, MHC-II+", "None (quiescent until re-exposure)", "CD27 (memory marker, TNFRSF7)", "P26842", "Long-lived quiescent B cell generated in germinal center after somatic hypermutation and affinity maturation. Carries high-affinity, class-switched BCR. Upon re-exposure to antigen, rapidly differentiates into plasma cells (faster and higher-titer response than primary). The cellular basis of immunological memory for humoral immunity. Can persist for decades without antigen re-exposure.", "Germinal center selection (highest-affinity clones survive)", "Basis of vaccine memory. Memory B cells are NOT depleted by anti-CD20 (rituximab) in bone marrow niches. Defective memory B cells in common variable immunodeficiency (CVID). Age-related decline contributes to reduced vaccine efficacy in elderly.", "Abbas 10th ed Ch 12; Kurosaki T et al. Nat Rev Immunol 15:149, 2015") }

    return acell("", "", "", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════════
// ANTIBODY (IMMUNOGLOBULIN) CLASSES
// ═══════════════════════════════════════════════════════════
// Five classes defined by heavy chain constant region.
// Each evolved for a specific biological context.

fn antibody_class(name: String) -> Antibody {
    if name == "IgG" { return abclass("IgG", "Gamma (gamma1-4 subclasses)", "Monomer. Two heavy chains (gamma) + two light chains (kappa or lambda). Two Fab arms (antigen binding) + one Fc region (effector functions). Four subclasses: IgG1 (65%), IgG2 (25%), IgG3 (7%), IgG4 (3%).", 150.0, 23.0, 75.0, "Most abundant serum Ig. Opsonization (Fc receptors on phagocytes). Complement activation (classical pathway, except IgG4). ADCC via FcgammaRIII (CD16) on NK cells. Neonatal immunity via FcRn-mediated placental transfer. Secondary immune response. Neutralization of toxins and viruses.", true, true, "IgG subclass deficiency: recurrent sinopulmonary infections. Therapeutic antibodies are mostly IgG1 or IgG4. IVIG (intravenous immunoglobulin) therapy. Anti-D (RhoGAM) prevents hemolytic disease of newborn. Fc engineering for half-life extension.", "Abbas 10th ed Ch 5; Vidarsson G et al. Front Immunol 5:520, 2014") }

    if name == "IgA" { return abclass("IgA", "Alpha (alpha1, alpha2 subclasses)", "Serum: monomer. Secretory (sIgA): dimer linked by J-chain + secretory component (poly-Ig receptor cleavage product). Secretory component protects from proteolytic degradation in gut.", 160.0, 6.0, 15.0, "Most produced Ig in the body (3-5 g/day, mostly secretory). Mucosal immunity: prevents microbial attachment at epithelial surfaces (gut, respiratory, urogenital). Secreted across epithelium by poly-Ig receptor (pIgR). Immune exclusion: traps pathogens in mucus. Does NOT activate complement (prevents mucosal inflammation). Breast milk sIgA protects neonatal gut.", false, false, "Selective IgA deficiency: most common primary immunodeficiency (1:500). Usually asymptomatic, some have recurrent mucosal infections. IgA nephropathy (Berger disease): IgA deposits in glomeruli. Anti-IgA antibodies in IgA-deficient patients can cause anaphylaxis to blood products.", "Abbas 10th ed Ch 5; Woof JM, Kerr MA. J Pathol 208:270, 2006") }

    if name == "IgM" { return abclass("IgM", "Mu", "Pentamer (5 monomers linked by J-chain and disulfide bonds). Ten antigen-binding sites (but effective valency ~5 due to steric hindrance). Also expressed as monomer on naive B cell surface (BCR).", 900.0, 5.0, 10.0, "First antibody produced in primary immune response (before class switching). First Ig expressed during B-cell development. Pentameric structure = high avidity compensating for low individual affinity. Most efficient complement activator (one IgM pentamer suffices for C1q binding). Agglutination of particulate antigens. Natural antibodies: polyreactive IgM produced without prior immunization (anti-ABO blood group).", false, true, "Hyper-IgM syndrome: defective class switching (CD40L or AID mutations), elevated IgM, absent IgG/IgA/IgE. Waldenstrom macroglobulinemia: IgM-producing lymphoplasmacytic lymphoma causes hyperviscosity. Cold agglutinin disease: IgM autoantibodies against RBC antigens active at low temperatures.", "Abbas 10th ed Ch 5; Schroeder HW, Cavacini L. J Allergy Clin Immunol 125:S41, 2010") }

    if name == "IgE" { return abclass("IgE", "Epsilon", "Monomer. Extra constant domain (CH4) instead of hinge region. Binds FcepsilonRI on mast cells and basophils with extremely high affinity (Ka ~10^10 M-1), remaining bound for weeks even without antigen.", 190.0, 2.5, 0.002, "Least abundant serum Ig. Evolved for anti-helminth defense. IgE-coated helminths are killed by eosinophil degranulation (ADCC). In allergic disease: allergen cross-links IgE on mast cells via FcepsilonRI, triggering immediate degranulation (histamine, tryptase, leukotrienes). Mediates type I hypersensitivity: allergic rhinitis, asthma, food allergy, anaphylaxis, urticaria.", false, false, "Allergy and anaphylaxis: the pathological consequence of anti-parasitic machinery in parasite-free environments (hygiene hypothesis). Anti-IgE therapy (omalizumab): binds free IgE, prevents FcepsilonRI binding. Used in severe allergic asthma. Hyper-IgE syndrome (Job syndrome): STAT3 mutation, elevated IgE, recurrent skin/lung infections.", "Abbas 10th ed Ch 20; Gould HJ, Sutton BJ. Nat Rev Immunol 8:205, 2008") }

    if name == "IgD" { return abclass("IgD", "Delta", "Monomer. Co-expressed with IgM on mature naive B cells (alternative splicing of same VDJ with C-delta exons). Very long hinge region (susceptible to proteolysis).", 185.0, 3.0, 0.2, "Function largely enigmatic. Co-expressed with IgM as BCR on naive B cells (both recognize same antigen). May provide tonic survival signals to naive B cells. Secreted IgD found in upper respiratory mucosa, may bind basophils and mast cells. IgD-class-switched B cells found in tonsils and adenoids. Least understood immunoglobulin class.", false, false, "Hyper-IgD syndrome (mevalonate kinase deficiency): periodic fever syndrome with elevated IgD. Paradoxically, pathogenesis is related to mevalonate pathway defect, not IgD itself. IgD myeloma: extremely rare.", "Abbas 10th ed Ch 5; Chen K, Cerutti A. Immunol Rev 237:160, 2010") }

    return abclass("", "", "", 0.0, 0.0, 0.0, "", false, false, "", "")
}

// ═══════════════════════════════════════════════════════════
// MHC / HLA SYSTEM
// ═══════════════════════════════════════════════════════════
// The most polymorphic genes in the human genome.
// MHC restriction: T-cells only see antigen in context of self-MHC.
// This is why transplant rejection exists: foreign MHC is the
// strongest alloantigen.

fn mhc_molecule(name: String) -> MhcMolecule {
    // --- MHC Class I ---

    if name == "HLA-A" { return mhc("HLA-A", 1, "Chromosome 6p21.3", "All nucleated cells (ubiquitous). Upregulated by IFN-gamma.", "8-10 amino acids (cytosolic peptides)", "Presents intracellular peptides (viral, tumor, self) to CD8+ cytotoxic T cells. Heterodimer: alpha chain (polymorphic, 45 kDa) + beta-2-microglobulin (invariant, 12 kDa). Peptide loaded in ER via TAP transporter. Over 6700 alleles identified (most polymorphic HLA class I locus).", "P04439", "HLA-A*02:01: type 1 diabetes risk. HLA-A*03:01: hemochromatosis. HLA-A*31:01: carbamazepine hypersensitivity. HLA-A*29: birdshot chorioretinopathy (strongest HLA-disease association known, RR greater than 100).", "Transplant rejection: HLA-A mismatch = strong allogeneic response. HLA typing essential for bone marrow transplant. Peptide vaccines designed for common HLA-A alleles.", "Abbas 10th ed Ch 6; Robinson J et al. Nucleic Acids Res 48:D829, 2020 (IPD-IMGT/HLA)") }

    if name == "HLA-B" { return mhc("HLA-B", 1, "Chromosome 6p21.3", "All nucleated cells. Upregulated by IFN-gamma.", "8-10 amino acids", "MHC class I presenting intracellular peptides to CD8+ T cells. Most polymorphic classical HLA gene (over 7800 alleles). Strong influence on HIV progression rate: HLA-B*57:01 and HLA-B*27:05 associated with slow HIV progression (elite controllers). Peptide binding groove accommodates different anchor residues depending on allele.", "Q95365", "HLA-B*27: ankylosing spondylitis (RR ~100), reactive arthritis, anterior uveitis. HLA-B*57:01: abacavir hypersensitivity (mandatory screening before prescription). HLA-B*58:01: allopurinol severe cutaneous adverse reactions. HLA-B*15:02: carbamazepine-induced Stevens-Johnson syndrome (Southeast Asian populations).", "Pharmacogenomics: HLA-B typing before abacavir (HIV) and carbamazepine (epilepsy) prevents fatal drug reactions. HIV vaccine design must account for HLA-B diversity.", "Abbas 10th ed Ch 6; Carrington M, O'Brien SJ. Annu Rev Med 54:535, 2003 (HLA-B and HIV)") }

    if name == "HLA-C" { return mhc("HLA-C", 1, "Chromosome 6p21.3", "All nucleated cells, lower surface expression than HLA-A/B", "8-10 amino acids", "MHC class I with dual role: (a) presents peptides to CD8+ T cells (like HLA-A/B), (b) primary ligand for killer immunoglobulin-like receptors (KIR) on NK cells. KIR-HLA-C interactions regulate NK cell licensing and activity. HLA-C expression level is genetically determined and influences HIV viral load setpoint.", "P10321", "HLA-C*06:02: psoriasis (strongest genetic association, OR ~5). HLA-C expression level associated with HIV control and Crohn disease risk. KIR-HLA-C mismatch in haploidentical transplant reduces leukemia relapse (graft-versus-leukemia).", "KIR-HLA-C interaction determines NK cell education (licensing). KIR3DL1-HLA-Bw4 and KIR2DL1-HLA-C2 are key inhibitory receptor-ligand pairs.", "Abbas 10th ed Ch 6; Parham P. Nat Rev Immunol 5:201, 2005 (KIR-HLA)") }

    // --- MHC Class II ---

    if name == "HLA-DR" { return mhc("HLA-DR", 2, "Chromosome 6p21.3", "Professional APCs: dendritic cells, macrophages, B cells. Inducible on other cells by IFN-gamma (thymic epithelium, activated T cells).", "13-25 amino acids (exogenous peptides from phagocytosed material)", "Presents extracellular-derived peptides to CD4+ helper T cells. Heterodimer: alpha chain (DRA, nearly monomorphic) + beta chain (DRB1, highly polymorphic, over 3100 alleles). Peptide loaded in endosomal compartment (MIIC) after invariant chain (Ii/CD74) removal by cathepsins and HLA-DM editing. Most important HLA class II locus for disease association.", "P01903", "HLA-DR4 (DRB1*04:01): rheumatoid arthritis (shared epitope hypothesis). HLA-DR3 (DRB1*03:01): type 1 diabetes, SLE, celiac disease. HLA-DR2 (DRB1*15:01): multiple sclerosis (strongest genetic risk factor). HLA-DR15 + DQ6: narcolepsy type 1. HLA-DR3/DR4 heterozygosity: highest risk for type 1 diabetes.", "Transplant: HLA-DR matching most critical for kidney transplant survival (along with HLA-A and HLA-B). Shared epitope in RA: DRB1 alleles encoding QKRAA/QRRAA at positions 70-74 confer risk.", "Abbas 10th ed Ch 6; Gregersen PK et al. Arthritis Rheum 30:1205, 1987 (shared epitope)") }

    if name == "HLA-DP" { return mhc("HLA-DP", 2, "Chromosome 6p21.3", "Professional APCs. Lower expression than HLA-DR.", "13-25 amino acids", "MHC class II presenting exogenous peptides to CD4+ T cells. Heterodimer: DPA1 (alpha) + DPB1 (beta, polymorphic). Historically considered less important for transplant, but DPB1 mismatches now recognized to affect HSCT outcomes. T-cell epitope-based DPB1 matching (permissive vs nonpermissive mismatches) improves transplant outcomes.", "P20036", "HLA-DPB1*02:01: chronic beryllium disease (berylliosis, glutamate at position 69 binds beryllium). HLA-DP polymorphisms associated with hepatitis B vaccine response and hepatitis B virus clearance. Nonpermissive DPB1 mismatches increase GVHD in HSCT.", "DPB1 typing increasingly included in unrelated donor HSCT. Permissive DPB1 mismatches (T-cell epitope groups) acceptable. Nonpermissive mismatches increase mortality.", "Abbas 10th ed Ch 6; Fleischhauer K et al. Blood 120:1107, 2012 (DPB1 permissive mismatches)") }

    if name == "HLA-DQ" { return mhc("HLA-DQ", 2, "Chromosome 6p21.3", "Professional APCs. Surface expression lower than HLA-DR.", "13-25 amino acids", "MHC class II presenting exogenous peptides to CD4+ T cells. Heterodimer: DQA1 (alpha, polymorphic) + DQB1 (beta, polymorphic). Unique: BOTH chains are polymorphic (unlike DR where alpha is monomorphic). This doubles combinatorial diversity in heterozygotes (cis and trans pairing). Critical for celiac disease: DQ2 (DQA1*05:01/DQB1*02:01) and DQ8 (DQA1*03:01/DQB1*03:02) present deamidated gliadin peptides.", "P01920", "HLA-DQ2: celiac disease (95% of patients carry DQ2, necessary but not sufficient). HLA-DQ8: type 1 diabetes risk, celiac disease (remaining 5%). HLA-DQ2/DQ8: narcolepsy type 1 (99% of patients carry DQ6/DQ2 haplotype). DQ2-restricted gluten presentation is THE molecular basis of celiac disease.", "Celiac disease screening: HLA-DQ2/DQ8 typing has near 100% negative predictive value (if absent, celiac is virtually excluded). Tissue transglutaminase (tTG) deamidates gliadin, creating negatively charged residues that bind DQ2 P4 and P6 pockets.", "Abbas 10th ed Ch 6; Sollid LM. Nat Rev Immunol 2:647, 2002 (HLA-DQ2 and celiac)") }

    return mhc("", 0, "", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════════
// COMPLEMENT SYSTEM
// ═══════════════════════════════════════════════════════════
// Evolutionary ancient. Three pathways converge on C3 convertase.
// End result: opsonization, inflammation, and lysis (MAC).

fn complement_component(name: String) -> ComplementComponent {
    // --- Classical pathway (antibody-dependent) ---

    if name == "C1q" { return comp("C1q", "Classical", "Recognition molecule. Hexameric (bouquet of 6 globular heads on collagen stalks). Binds Fc region of IgG or IgM in immune complexes. Binding activates C1r then C1s (serine proteases). Requires at least two Fc regions: one IgM pentamer suffices, but multiple IgGs needed.", "P02745", "C1q deficiency: strongest genetic risk factor for SLE (greater than 90% develop SLE). Impaired clearance of apoptotic bodies leads to autoantigen exposure.", "Abbas 10th ed Ch 13; Walport MJ. N Engl J Med 344:1058, 2001") }

    if name == "C4" { return comp("C4", "Classical and Lectin", "Cleaved by C1s (classical) or MASP-2 (lectin) into C4a (anaphylatoxin) and C4b (binds covalently to pathogen surface). C4b combines with C2a to form C3 convertase (C4b2a). Two isotypes: C4A (binds amino groups) and C4B (binds hydroxyl groups). Copy number varies (2-8 copies).", "P0C0L4", "C4 deficiency: SLE risk (especially C4A null alleles). Low C4: active SLE (consumed by immune complexes). C4 copy number variation associated with schizophrenia risk.", "Abbas 10th ed Ch 13; Yang Y et al. Nature 445:168, 2007 (C4 CNV)") }

    // --- C3: the convergence point ---

    if name == "C3" { return comp("C3", "All pathways converge here", "Central component of complement. Most abundant complement protein in serum (1-2 mg/mL). Cleaved to C3a (anaphylatoxin: mast cell degranulation, chemotaxis) and C3b (opsonin: covalently tags pathogen surface, recognized by CR1 on phagocytes). C3b also forms C5 convertase. Internal thioester bond in C3b reacts with surface hydroxyl/amino groups within 60 microseconds (or is inactivated by water). Amplification loop: each C3 convertase generates hundreds of C3b.", "P01024", "C3 deficiency: recurrent pyogenic infections (S. pneumoniae, H. influenzae, N. meningitidis). C3 nephritic factor (autoantibody stabilizing C3bBb convertase) causes membranoproliferative glomerulonephritis and partial lipodystrophy. Compstatin (C3 inhibitor) for PNH.", "Abbas 10th ed Ch 13; Ricklin D et al. Nat Immunol 11:785, 2010") }

    // --- Alternative pathway ---

    if name == "factor_B" { return comp("Factor B", "Alternative", "Zymogen cleaved by Factor D into Ba (released) and Bb (serine protease). Bb binds C3b to form alternative pathway C3 convertase (C3bBb). Stabilized by properdin (Factor P). Constitutive low-level tick-over: C3 spontaneously hydrolyzes in fluid phase, generating C3(H2O) that binds Factor B, enabling constant surveillance.", "P00751", "Factor B gain-of-function mutations: atypical hemolytic uremic syndrome (aHUS). Factor B polymorphisms: age-related macular degeneration (AMD) risk.", "Abbas 10th ed Ch 13; Thurman JM, Holers VM. J Immunol 176:1305, 2006") }

    if name == "factor_D" { return comp("Factor D (adipsin)", "Alternative", "Serine protease that cleaves Factor B when bound to C3b. Rate-limiting enzyme of alternative pathway. Also known as adipsin (secreted by adipocytes, links complement to metabolism). The only complement protein present in limiting concentration (~1-2 ug/mL).", "P00746", "Factor D deficiency: recurrent Neisseria infections. Factor D/adipsin links complement activation to metabolic syndrome. Lampalizumab (anti-Factor D) tested for geographic atrophy (dry AMD).", "Abbas 10th ed Ch 13; White RT et al. J Biol Chem 267:9210, 1992 (adipsin)") }

    if name == "properdin" { return comp("Properdin (Factor P)", "Alternative", "Only POSITIVE regulator of complement. Stabilizes C3bBb convertase (extends half-life from 90 seconds to 30 minutes). Can also initiate alternative pathway by binding directly to pathogen surfaces (LPS, activated platelets, apoptotic cells) and recruiting C3b.", "P27918", "Properdin deficiency (X-linked): fulminant meningococcal sepsis. One of the most severe complement deficiencies.", "Abbas 10th ed Ch 13; Kemper C et al. Mol Immunol 47:2187, 2010") }

    // --- Lectin pathway ---

    if name == "MBL" { return comp("Mannose-binding lectin (MBL)", "Lectin", "C-type lectin that binds mannose, fucose, and N-acetylglucosamine on microbial surfaces (these sugars are terminal on bacteria/fungi but buried on mammalian glycoproteins). Structurally similar to C1q. Activates MASP-1 and MASP-2 (MBL-associated serine proteases), which cleave C4 and C2 to form C3 convertase (same as classical: C4b2a).", "P11226", "MBL deficiency: most common complement deficiency (~5% of population have very low MBL). Increased susceptibility to infections in infancy (before adaptive immunity matures) and in immunocompromised patients. Controversial whether MBL deficiency is clinically significant in immunocompetent adults.", "Abbas 10th ed Ch 13; Turner MW. Immunobiology 199:327, 1998") }

    // --- Terminal pathway (MAC) ---

    if name == "C5" { return comp("C5", "Terminal (all pathways)", "Cleaved by C5 convertase into C5a (most potent anaphylatoxin: neutrophil chemotaxis, mast cell degranulation, vascular permeability, 100x more potent than C3a) and C5b (initiates membrane attack complex assembly). C5a also promotes oxidative burst in neutrophils.", "P01031", "C5 deficiency: recurrent Neisseria infections. Eculizumab (anti-C5 monoclonal antibody): blocks MAC formation. First-in-class for paroxysmal nocturnal hemoglobinuria (PNH) and atypical HUS. Ravulizumab: long-acting anti-C5.", "Abbas 10th ed Ch 13; Rother RP et al. Nat Biotechnol 25:1256, 2007 (eculizumab)") }

    if name == "MAC" { return comp("Membrane Attack Complex (C5b-C6-C7-C8-C9n)", "Terminal", "Sequential assembly: C5b binds C6, then C7 (inserts into lipid bilayer), then C8 (partial pore), then 10-16 copies of C9 polymerize to form the complete pore (100 Angstrom inner diameter). Osmotic lysis: water and ions flood through pore, cell swells and bursts. Most effective against gram-negative bacteria (thin wall). Gram-positive bacteria resistant (thick peptidoglycan). Nucleated cells can endocytose/shed MAC (sublytic MAC activates cell signaling).", "P02748", "C9 deficiency: recurrent Neisseria infections (common in Japanese population, 1:1000). C6/C7/C8 deficiency: same phenotype. MAC deposition in renal glomeruli (lupus nephritis, IgA nephropathy). Sublytic MAC on endothelium contributes to transplant vasculopathy.", "Abbas 10th ed Ch 13; Morgan BP. Mol Immunol 36:461, 1999") }

    // --- Key regulators ---

    if name == "C1_inhibitor" { return comp("C1 inhibitor (C1-INH, SERPING1)", "Regulator (classical/lectin)", "Serine protease inhibitor (serpin). Inactivates C1r, C1s (classical), MASP-1, MASP-2 (lectin), and also kallikrein and Factor XIIa (contact/kinin system). Prevents spontaneous complement activation. Covalent suicide inhibitor.", "P05155", "C1-INH deficiency: hereditary angioedema (HAE). Autosomal dominant. Episodic swelling (face, larynx, bowel). NOT histamine-mediated (antihistamines and epinephrine ineffective). Caused by excess bradykinin (uncontrolled kallikrein). Treatment: C1-INH concentrate (Cinryze, Berinert), icatibant (bradykinin B2 receptor antagonist), lanadelumab (anti-kallikrein mAb).", "Abbas 10th ed Ch 13; Zuraw BL. N Engl J Med 359:1027, 2008 (HAE)") }

    if name == "DAF" { return comp("Decay-accelerating factor (DAF/CD55)", "Regulator (all pathways)", "GPI-anchored surface protein on host cells. Accelerates decay (dissociation) of C3 convertases (both C4b2a and C3bBb). Prevents complement activation on self surfaces. Works with CD59 (protectin) which blocks C9 polymerization (MAC formation).", "P08174", "Paroxysmal nocturnal hemoglobinuria (PNH): acquired somatic mutation in PIGA gene (required for GPI anchor synthesis). Loss of CD55 and CD59 from RBC surface leads to complement-mediated intravascular hemolysis, especially during sleep (mild acidosis activates complement). Eculizumab is treatment.", "Abbas 10th ed Ch 13; Brodsky RA. Blood 124:2804, 2014 (PNH)") }

    if name == "factor_H" { return comp("Factor H", "Regulator (alternative)", "Soluble regulator of alternative pathway. Binds C3b and accelerates decay of C3bBb convertase. Also serves as cofactor for Factor I-mediated cleavage of C3b to iC3b (inactive). Distinguishes self from non-self: binds sialic acid and GAGs on host cell surfaces, concentrating regulatory activity on self. Pathogens lack these markers.", "P08603", "Factor H deficiency or mutations: atypical HUS (uncontrolled complement on renal endothelium). Factor H polymorphism Y402H: strongest genetic risk factor for age-related macular degeneration (AMD). Neisseria gonorrhoeae and S. pneumoniae recruit Factor H to evade complement (molecular mimicry).", "Abbas 10th ed Ch 13; Warwicker P et al. Kidney Int 53:836, 1998 (aHUS); Klein RJ et al. Science 308:385, 2005 (AMD)") }

    return comp("", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════════
// CYTOKINES
// ═══════════════════════════════════════════════════════════
// The signaling molecules. Autocrine, paracrine, endocrine.
// Pleiotropy, redundancy, synergy, antagonism.

fn cytokine(name: String) -> Cytokine {
    if name == "IL-1" { return cyto("Interleukin-1 (IL-1beta)", "Macrophages, monocytes, DCs, epithelium", "Hepatocytes, hypothalamus, endothelium, T cells, B cells", "Master pro-inflammatory cytokine. Endogenous pyrogen (acts on hypothalamus, induces fever via PGE2). Induces acute phase proteins from liver (CRP, fibrinogen, SAA). Activates endothelium (E-selectin, ICAM-1 upregulation for leukocyte recruitment). Synergizes with TNF-alpha. Produced as pro-IL-1beta, cleaved by caspase-1 in NLRP3 inflammasome.", "P01584", "IL-1 receptor antagonist (anakinra) for rheumatoid arthritis, cryopyrin-associated periodic syndromes (CAPS), gout flares. Canakinumab (anti-IL-1beta) for CAPS and CANTOS trial showed cardiovascular benefit. IL-1 drives autoinflammatory diseases (familial Mediterranean fever, TRAPS).", "Abbas 10th ed Ch 4; Dinarello CA. Blood 117:3720, 2011") }

    if name == "IL-2" { return cyto("Interleukin-2", "Activated CD4+ T cells (primarily Th1), activated CD8+ T cells", "T cells (autocrine growth factor), NK cells, Tregs (survival signal)", "T-cell growth factor. Drives clonal expansion of activated T cells. Essential for Treg survival and homeostasis (Tregs constitutively express CD25/IL-2Ralpha, consume IL-2). High-dose IL-2 expands effector cells. Low-dose IL-2 preferentially expands Tregs. Signals through JAK1/JAK3-STAT5 pathway.", "P60568", "High-dose IL-2 (aldesleukin): FDA-approved for metastatic melanoma and renal cell carcinoma (durable complete responses in ~7%). Low-dose IL-2: clinical trials for autoimmune diseases (expand Tregs). Anti-CD25 (daclizumab, basiliximab): transplant rejection prophylaxis. IL-2 complex engineering for selective Treg or effector T cell expansion.", "Abbas 10th ed Ch 9; Malek TR. Annu Rev Immunol 26:453, 2008") }

    if name == "IL-4" { return cyto("Interleukin-4", "Th2 cells, basophils, mast cells, NKT cells", "B cells, T cells, macrophages, epithelial cells", "Master Th2 cytokine. Drives Th2 differentiation (GATA-3 induction via STAT6). Induces B-cell IgE class switching (activates germline epsilon transcription). Induces IgG4 class switching. Promotes alternative macrophage activation (M2: tissue repair, fibrosis). Upregulates MHC-II and FcepsilonRI. Inhibits Th1 differentiation (antagonizes IFN-gamma). Shares receptor with IL-13 (IL-4Ralpha/IL-13Ralpha1).", "P05112", "Dupilumab (anti-IL-4Ralpha, blocks both IL-4 and IL-13): FDA-approved for atopic dermatitis, moderate-severe asthma, chronic rhinosinusitis with nasal polyps, eosinophilic esophagitis, prurigo nodularis. Transformative therapy for Th2-mediated diseases.", "Abbas 10th ed Ch 10; Paul WE. Blood 77:1859, 1991") }

    if name == "IL-6" { return cyto("Interleukin-6", "Macrophages, T cells, endothelial cells, fibroblasts", "Hepatocytes, B cells, T cells, bone marrow", "Pleiotropic pro-inflammatory and anti-inflammatory cytokine. Induces acute phase response (CRP from liver, most reliable clinical marker of IL-6 activity). Drives Th17 differentiation (with TGF-beta). Promotes B-cell differentiation to plasma cells. Terminal differentiation factor. Inhibits Treg generation (antagonizes TGF-beta-induced FOXP3). Signals via classic (membrane IL-6R) and trans-signaling (soluble IL-6R + gp130).", "P05231", "Tocilizumab (anti-IL-6R): rheumatoid arthritis, giant cell arteritis, Castleman disease, cytokine release syndrome (CRS from CAR-T therapy), COVID-19 severe cases. IL-6 is THE cytokine storm marker. Sarilumab (anti-IL-6R) for RA. IL-6 drives cancer cachexia and depression-associated inflammation.", "Abbas 10th ed Ch 4; Tanaka T et al. Cold Spring Harb Perspect Biol 6:a016295, 2014") }

    if name == "IL-10" { return cyto("Interleukin-10", "Tregs, Th2 cells, macrophages (M2), DCs, B cells (regulatory)", "Macrophages, DCs, T cells", "Master anti-inflammatory cytokine. Inhibits macrophage activation: suppresses TNF-alpha, IL-1, IL-6, IL-12 production. Inhibits DC maturation and antigen presentation. Suppresses Th1 and Th17 responses. Maintains intestinal immune homeostasis (IL-10 knockout mice develop spontaneous colitis). Signals via STAT3. Evolved to limit immunopathology at the cost of some microbial clearance.", "P22301", "IL-10 and IL-10R mutations: very early-onset inflammatory bowel disease (infantile colitis). Therapeutic IL-10 trials in IBD (disappointing, likely due to pleiotropic effects). EBV encodes viral IL-10 homolog (vIL-10) to suppress anti-viral immunity. Tumor cells produce IL-10 to evade immune response. Pegylated IL-10 (pegilodecakin): clinical trials in cancer.", "Abbas 10th ed Ch 15; Couper KN et al. J Immunol 180:5771, 2008") }

    if name == "IL-12" { return cyto("Interleukin-12 (p70 heterodimer: p35 + p40)", "Dendritic cells (major source), macrophages", "NK cells, T cells (naive CD4+)", "Key driver of Th1 differentiation and cell-mediated immunity. Induces T-bet expression via STAT4, committing naive CD4+ T cells to Th1 fate. Potently induces IFN-gamma production from NK cells and T cells. Enhances cytotoxic activity of NK cells and CTLs. Bridge between innate and adaptive: DCs sensing intracellular pathogens (via TLR) produce IL-12, directing adaptive response toward Th1. Heterodimer: p35 (IL-12A) + p40 (IL-12B, shared with IL-23).", "P29459", "IL-12/IL-23 p40 deficiency: severe mycobacterial and Salmonella infections (Mendelian susceptibility to mycobacterial disease, MSMD). Ustekinumab (anti-p40, blocks both IL-12 and IL-23): Crohn disease, ulcerative colitis, psoriasis, psoriatic arthritis. IL-12 gene therapy trials in cancer (intratumoral injection).", "Abbas 10th ed Ch 4; Trinchieri G. Nat Rev Immunol 3:133, 2003") }

    if name == "IL-17" { return cyto("Interleukin-17A", "Th17 cells (primary), gamma-delta T cells, ILC3, NKT cells", "Epithelial cells, fibroblasts, endothelial cells, neutrophils", "Mucosal barrier defense cytokine. Induces CXCL1/CXCL8 (neutrophil chemokines) and G-CSF (neutrophil production) from stromal cells. Induces antimicrobial peptides (beta-defensins, S100A8/9) from epithelium. Synergizes with TNF-alpha for enhanced inflammatory gene expression. IL-17F has overlapping but weaker activity. Signals via IL-17RA/IL-17RC heterodimer and Act1 adaptor.", "Q16552", "Secukinumab, ixekizumab (anti-IL-17A): psoriasis (near-complete clearance in 50-70%), psoriatic arthritis, ankylosing spondylitis. Brodalumab (anti-IL-17RA): psoriasis. IL-17 blockade increases Candida risk (chronic mucocutaneous candidiasis in genetic IL-17 deficiency). APECED/CMC: anti-IL-17 autoantibodies cause chronic Candida.", "Abbas 10th ed Ch 10; Gaffen SL. Nat Rev Immunol 9:556, 2009") }

    if name == "TNF-alpha" { return cyto("Tumor Necrosis Factor-alpha (TNF/TNFSF2)", "Macrophages (primary), T cells, NK cells, mast cells", "Endothelium, hepatocytes, hypothalamus, neutrophils, virtually all cells", "Master pro-inflammatory cytokine. Trimer signals via TNFR1 (ubiquitous, death domain) and TNFR2 (immune cells, no death domain). Activates NF-kB (pro-inflammatory gene program), AP-1, and caspase-8 (apoptosis). Endogenous pyrogen. Induces acute phase response. Activates endothelium (E-selectin, VCAM-1). At high systemic concentrations: septic shock (vasodilation, DIC, multi-organ failure). Cachexia in chronic disease. Membrane-bound and soluble forms (cleaved by TACE/ADAM17).", "P01375", "Anti-TNF therapy revolutionized autoimmune disease treatment. Infliximab (chimeric anti-TNF mAb), adalimumab (fully human anti-TNF mAb, best-selling drug globally for years), etanercept (TNFR2-Fc fusion), certolizumab, golimumab. Indications: RA, Crohn disease, ulcerative colitis, psoriasis, ankylosing spondylitis, JIA. Risk: TB reactivation (TNF essential for granuloma maintenance). Screen for latent TB before starting.", "Abbas 10th ed Ch 4; Feldmann M, Maini RN. Annu Rev Immunol 19:163, 2001 (anti-TNF in RA)") }

    if name == "IFN-gamma" { return cyto("Interferon-gamma (IFN-gamma, type II interferon)", "Th1 cells (primary), CD8+ T cells, NK cells, NKT cells", "Macrophages, DCs, B cells, endothelium, all nucleated cells", "The macrophage-activating factor. Classical M1 macrophage activation: induces iNOS (NO production), enhances respiratory burst (ROS), upregulates MHC-I and MHC-II. Promotes Th1 differentiation (positive feedback with IL-12). Inhibits Th2 and Th17 differentiation. Induces IgG class switching in B cells (opsonizing antibodies). Activates endothelium. Upregulates antigen processing machinery (TAP, proteasome, MHC). Signals via JAK1/JAK2-STAT1 pathway.", "P01579", "IFN-gamma receptor deficiency: severe mycobacterial infections (MSMD). IFN-gamma release assay (IGRA, QuantiFERON): TB diagnosis. Recombinant IFN-gamma (Actimmune): chronic granulomatous disease (enhances neutrophil ROS production). Excessive IFN-gamma: hemophagocytic lymphohistiocytosis (HLH). Emapalumab (anti-IFN-gamma): primary HLH.", "Abbas 10th ed Ch 10; Boehm U et al. Annu Rev Immunol 15:749, 1997") }

    if name == "IFN-alpha" { return cyto("Interferon-alpha (type I interferon, 13 subtypes)", "Plasmacytoid dendritic cells (massive production), macrophages, fibroblasts, all nucleated cells (via IRF3/IRF7)", "All nucleated cells (ubiquitous IFNAR1/IFNAR2 receptor)", "Antiviral state induction. Induces hundreds of interferon-stimulated genes (ISGs): PKR (blocks translation), OAS/RNase L (degrades viral RNA), Mx proteins (block viral replication), IFIT proteins (recognize viral RNA). Upregulates MHC-I (enhanced CD8+ T cell recognition). Activates NK cells. Promotes DC maturation. Enhances antibody responses. Antiproliferative (slows cell division to limit viral spread). Signals via JAK1/TYK2-STAT1/STAT2-IRF9 pathway (ISGF3 complex).", "P01562", "Pegylated IFN-alpha: formerly standard of care for hepatitis C (now replaced by DAAs), still used for hepatitis B. IFN-alpha in SLE pathogenesis: plasmacytoid DCs produce pathogenic IFN-alpha driven by immune complexes containing self nucleic acids (TLR7/9 activation). Anifrolumab (anti-IFNAR1): FDA-approved for SLE. Type I IFN signature in SLE correlates with disease activity.", "Abbas 10th ed Ch 4; Ivashkiv LB, Donlin LT. Nat Rev Immunol 14:36, 2014") }

    if name == "TGF-beta" { return cyto("Transforming Growth Factor-beta (TGF-beta1)", "Tregs (major source), macrophages, platelets, virtually all cells", "T cells, B cells, macrophages, fibroblasts, epithelium", "Context-dependent immunomodulator. Anti-inflammatory: inhibits T-cell proliferation, inhibits macrophage activation, induces FOXP3+ Treg differentiation (with IL-2, without IL-6). Pro-inflammatory (paradoxical): with IL-6, induces Th17 differentiation (RORgamma-t). Fibrosis: potent inducer of collagen and extracellular matrix from fibroblasts. IgA class switching in mucosal B cells. Wound healing. Tumor promotion: TGF-beta in tumor microenvironment suppresses anti-tumor immunity. Signals via SMAD2/3/4 pathway.", "P01137", "TGF-beta drives fibrosis in liver cirrhosis, pulmonary fibrosis, scleroderma. TGF-beta traps (luspatercept) for anemia of beta-thalassemia and MDS. Anti-TGF-beta in cancer immunotherapy (releases immune suppression in tumor microenvironment). TGF-beta receptor mutations: Loeys-Dietz syndrome (aortic aneurysm). Hereditary hemorrhagic telangiectasia (endoglin/ALK1 mutations in TGF-beta superfamily).", "Abbas 10th ed Ch 15; Li MO et al. Annu Rev Immunol 24:99, 2006") }

    return cyto("", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════════
// PATTERN RECOGNITION RECEPTORS (PRRs)
// ═══════════════════════════════════════════════════════════
// The innate immune system's sensory apparatus.
// Germline-encoded. Recognize PAMPs (pathogen-associated molecular
// patterns) and DAMPs (damage-associated molecular patterns).

fn pattern_receptor(name: String) -> PatternReceptor {
    // --- Toll-like receptors (TLRs) ---

    if name == "TLR1" { return prr("TLR1", "Toll-like receptor (TLR)", "Triacyl lipopeptides (bacterial lipoproteins, Pam3CSK4)", "TLR1/TLR2 heterodimer -> MyD88 -> IRAK -> TRAF6 -> NF-kB (pro-inflammatory cytokines: TNF-alpha, IL-6, IL-12)", "Q15399", "Cell surface", "Recognizes triacylated lipopeptides from bacteria and mycobacteria. Forms obligate heterodimer with TLR2. Discriminates triacyl (TLR1/2) from diacyl (TLR6/2) lipopeptides based on hydrophobic channel structure. Expressed on monocytes, macrophages, DCs, neutrophils.", "Abbas 10th ed Ch 4; Jin MS et al. Cell 130:1071, 2007 (TLR1/2 crystal structure)") }

    if name == "TLR2" { return prr("TLR2", "Toll-like receptor (TLR)", "Broad specificity: peptidoglycan, lipoteichoic acid (gram+), zymosan (yeast), lipoarabinomannan (mycobacteria), porins (Neisseria)", "TLR2 heterodimer (with TLR1 or TLR6) -> MyD88 -> NF-kB and MAPK", "O60603", "Cell surface", "Promiscuous receptor. Forms heterodimers with TLR1 (triacyl lipopeptides) and TLR6 (diacyl lipopeptides). Broadest ligand specificity of any TLR. Critical for recognition of gram-positive bacteria, mycobacteria, and fungi. Cooperates with CD14 and CD36 as co-receptors.", "Abbas 10th ed Ch 4; Takeuchi O et al. Immunity 11:443, 1999") }

    if name == "TLR3" { return prr("TLR3", "Toll-like receptor (TLR)", "Double-stranded RNA (dsRNA, viral replication intermediate, poly(I:C))", "TRIF (NOT MyD88) -> IRF3 -> Type I IFN (IFN-alpha/beta) + NF-kB", "O15455", "Endosomal membrane (intracellular)", "Only TLR that signals exclusively through TRIF (not MyD88). Detects dsRNA in endosomes after viral phagocytosis. Primary inducer of type I interferon via IRF3 phosphorylation. Critical for antiviral defense. TLR3 deficiency: herpes simplex encephalitis (HSE) in children.", "Abbas 10th ed Ch 4; Alexopoulou L et al. Nature 413:732, 2001") }

    if name == "TLR4" { return prr("TLR4", "Toll-like receptor (TLR)", "Lipopolysaccharide (LPS/endotoxin, gram-negative outer membrane). Also: RSV F protein, HMGB1, heat shock proteins (DAMPs)", "MD-2/TLR4 complex -> MyD88 (from cell surface) -> NF-kB AND TRIF (from endosome) -> IRF3 -> IFN-beta. Only TLR using BOTH pathways.", "O00206", "Cell surface (then endocytosed)", "THE LPS receptor. Requires MD-2 (accessory protein that directly binds lipid A), CD14 (LPS delivery), and LBP (LPS-binding protein in serum). TLR4 is the only TLR that uses both MyD88 and TRIF adaptors (sequential signaling from surface then endosome). Excessive TLR4 activation by gram-negative bacteria causes septic shock. TLR4 also recognizes endogenous DAMPs (sterile inflammation).", "Abbas 10th ed Ch 4; Poltorak A et al. Science 282:2085, 1998 (Nobel Prize to Beutler 2011)") }

    if name == "TLR5" { return prr("TLR5", "Toll-like receptor (TLR)", "Flagellin (bacterial flagella protein, conserved D0 domain)", "MyD88 -> NF-kB -> pro-inflammatory cytokines", "O60602", "Cell surface (basolateral surface of intestinal epithelium)", "Recognizes a conserved region of flagellin (D0 domain) that is essential for flagellar assembly (cannot be mutated away without losing motility). Expressed on intestinal epithelium basolateral surface (senses bacteria that have breached the barrier, not commensal lumen bacteria). Also on macrophages, DCs. Entolimod (TLR5 agonist, CBLB502): radiation countermeasure.", "Abbas 10th ed Ch 4; Hayashi F et al. Nature 410:1099, 2001") }

    if name == "TLR7" { return prr("TLR7", "Toll-like receptor (TLR)", "Single-stranded RNA (ssRNA, viral genomes: influenza, HIV, SARS-CoV-2). Also imidazoquinolines (imiquimod, R848)", "MyD88 -> IRF7 -> Type I IFN (massive IFN-alpha from pDCs) + NF-kB", "Q9NYK1", "Endosomal membrane (intracellular)", "Major viral ssRNA sensor in plasmacytoid DCs. pDCs produce 1000x more IFN-alpha than any other cell type upon TLR7 activation. X-linked (important: SLE female predominance partly explained by TLR7 gene dosage from X-chromosome escape from inactivation). Imiquimod (TLR7 agonist): FDA-approved topical for basal cell carcinoma, actinic keratosis, genital warts.", "Abbas 10th ed Ch 4; Diebold SS et al. Science 303:1529, 2004; Brown GJ et al. Nature 605:349, 2022 (TLR7 gain-of-function causes SLE)") }

    if name == "TLR8" { return prr("TLR8", "Toll-like receptor (TLR)", "Single-stranded RNA (ssRNA), R848 (resiquimod)", "MyD88 -> NF-kB -> pro-inflammatory cytokines (TNF-alpha, IL-12). Less IFN than TLR7.", "Q9NR97", "Endosomal membrane (intracellular)", "Similar to TLR7 but expressed primarily in monocytes, macrophages, and myeloid DCs (not pDCs). Produces primarily pro-inflammatory cytokines rather than type I IFN. VTX-2337 (motolimod, TLR8 agonist): clinical trials in head and neck cancer. Human TLR8 is functional (unlike mouse TLR8, complicating mouse model studies).", "Abbas 10th ed Ch 4; Heil F et al. Science 303:1526, 2004") }

    if name == "TLR9" { return prr("TLR9", "Toll-like receptor (TLR)", "Unmethylated CpG DNA motifs (common in bacterial/viral DNA, rare in vertebrate DNA due to CpG methylation)", "MyD88 -> IRF7 -> Type I IFN (in pDCs) + NF-kB", "Q9NR96", "Endosomal membrane (intracellular)", "Discriminates microbial from self DNA by CpG methylation status. Bacterial DNA has abundant unmethylated CpG (1:16 frequency), mammalian DNA has methylated CpG (1:60 frequency, suppressed). TLR9 activation in pDCs drives type I IFN (antiviral). CpG oligodeoxynucleotides (CpG-ODN) are potent vaccine adjuvants. In SLE: self DNA in immune complexes accesses endosomal TLR9, driving pathogenic IFN-alpha production.", "Abbas 10th ed Ch 4; Hemmi H et al. Nature 408:740, 2000") }

    // --- NOD-like receptors (NLRs, cytoplasmic) ---

    if name == "NOD1" { return prr("NOD1 (CARD4)", "NOD-like receptor (NLR)", "Gamma-D-glutamyl-meso-diaminopimelic acid (iE-DAP, found in all gram-negative and some gram-positive peptidoglycan)", "NOD1 -> RIP2 kinase -> NF-kB and MAPK -> pro-inflammatory cytokines", "Q9Y239", "Cytoplasmic (intracellular sensor)", "Cytoplasmic sensor of peptidoglycan fragments that reach the cytosol (via type III/IV secretion systems, endosomal escape, or membrane transport). Detects gram-negative bacteria (iE-DAP is in all gram-negative PG). Ubiquitously expressed. Cooperates with TLRs for full innate activation. NOD1 polymorphisms associated with asthma, IBD, and H. pylori susceptibility.", "Abbas 10th ed Ch 4; Chamaillard M et al. Nat Immunol 4:702, 2003") }

    if name == "NOD2" { return prr("NOD2 (CARD15)", "NOD-like receptor (NLR)", "Muramyl dipeptide (MDP, minimal bioactive peptidoglycan motif, present in ALL bacteria: gram-positive and gram-negative)", "NOD2 -> RIP2 kinase -> NF-kB + MAPK. Also activates autophagy (bacterial clearance).", "Q9HC29", "Cytoplasmic (intracellular sensor)", "Cytoplasmic sensor of MDP from all bacteria. Expressed in macrophages, DCs, Paneth cells (intestinal antimicrobial defense). Activates NF-kB and induces autophagy of intracellular bacteria. Loss-of-function mutations (R702W, G908R, L1007fs) are the strongest genetic risk factors for Crohn disease (defective bacterial sensing in gut leads to dysbiosis and inflammation). Gain-of-function mutations cause Blau syndrome (granulomatous arthritis, uveitis, dermatitis).", "Abbas 10th ed Ch 4; Hugot JP et al. Nature 411:599, 2001; Ogura Y et al. Nature 411:603, 2001 (NOD2 and Crohn disease, discovered simultaneously)") }

    // --- RIG-I-like receptors (RLRs, cytoplasmic RNA sensors) ---

    if name == "RIG-I" { return prr("RIG-I (DDX58)", "RIG-I-like receptor (RLR)", "Short dsRNA with 5'-triphosphate (viral RNA signature: host mRNA has 5' cap). Detects: influenza, Sendai virus, HCV, Ebola, VSV", "RIG-I -> MAVS (on mitochondrial membrane) -> TBK1/IKKe -> IRF3/IRF7 -> Type I IFN + NF-kB", "O95786", "Cytoplasmic (intracellular RNA sensor)", "Cytoplasmic viral RNA sensor. Recognizes 5'-triphosphate dsRNA (absent from host RNA due to 5' capping and processing). RIG-I activation on mitochondrial MAVS creates a signaling platform (prion-like MAVS aggregation). Distinguishes viral from self RNA by end structure (5'-ppp vs 5'-cap). MDA5 (a related sensor) detects long dsRNA (picornaviruses). Aicardi-Goutieres syndrome: mutations cause constitutive IFN production (interferonopathy).", "Abbas 10th ed Ch 4; Yoneyama M et al. Nat Immunol 5:730, 2004; Hornung V et al. Science 314:994, 2006 (5'-ppp recognition)") }

    // --- cGAS-STING (cytoplasmic DNA sensor) ---

    if name == "STING" { return prr("STING (TMEM173) + cGAS (MB21D1)", "cGAS-STING pathway", "Cytoplasmic dsDNA (viral, bacterial, mitochondrial, nuclear damage). cGAS binds DNA and synthesizes cyclic GMP-AMP (cGAMP), which activates STING.", "cGAS -> cGAMP (second messenger) -> STING (on ER membrane) -> TBK1 -> IRF3 -> Type I IFN + NF-kB -> pro-inflammatory cytokines + autophagy", "Q86WV6", "cGAS: cytoplasmic. STING: endoplasmic reticulum membrane.", "Universal cytoplasmic DNA sensor. cGAS binds DNA sequence-independently (detects any dsDNA in cytoplasm, where it should not be). Produces cGAMP (2'3'-cyclic GMP-AMP), a diffusible second messenger that activates STING. STING translocates from ER to Golgi, recruits TBK1. Critical for: antiviral (DNA viruses, retroviruses), anti-tumor (senses tumor DNA), and sterile inflammation (self DNA from damaged mitochondria/nuclei). STING agonists (ADU-S100, diABZI) in cancer immunotherapy clinical trials.", "Abbas 10th ed Ch 4; Sun L et al. Science 339:786, 2013 (cGAS discovery); Wu J et al. Science 339:826, 2013 (cGAMP)") }

    return prr("", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════════
// QUICK-ACCESS COUNT FUNCTIONS
// ═══════════════════════════════════════════════════════════

fn innate_cell_count() -> Int {
    // neutrophil, macrophage, dendritic_cell, nk_cell, mast_cell, eosinophil, basophil
    return 7
}

fn adaptive_cell_count() -> Int {
    // th1, th2, th17, treg, cd8_cytotoxic, b_cell_naive, plasma_cell, memory_b_cell
    return 8
}

fn antibody_class_count() -> Int {
    // IgG, IgA, IgM, IgE, IgD
    return 5
}

fn mhc_molecule_count() -> Int {
    // HLA-A, HLA-B, HLA-C, HLA-DR, HLA-DP, HLA-DQ
    return 6
}

fn complement_component_count() -> Int {
    // C1q, C4, C3, factor_B, factor_D, properdin, MBL, C5, MAC, C1_inhibitor, DAF, factor_H
    return 12
}

fn cytokine_count() -> Int {
    // IL-1, IL-2, IL-4, IL-6, IL-10, IL-12, IL-17, TNF-alpha, IFN-gamma, IFN-alpha, TGF-beta
    return 11
}

fn pattern_receptor_count() -> Int {
    // TLR1-5, TLR7-9, NOD1, NOD2, RIG-I, STING
    return 12
}

fn total_immune_entry_count() -> Int {
    // All entries across all categories
    return 61
}
