// amino_acid_metabolism.sy -- Transamination, urea cycle, one-carbon
// metabolism, and amino acid catabolism as native Scyla.
//
// Amino acids are not just protein building blocks. They are metabolic
// currency: their carbon skeletons feed the TCA cycle, their nitrogen
// feeds urea synthesis, their one-carbon fragments build nucleotides
// and methylate DNA. This module encodes the full catabolic and
// interconversion landscape of the 20 standard amino acids.
//
// Sources:
//   Nelson DL, Cox MM. Lehninger Principles of Biochemistry, 8th ed, 2021.
//   Berg JM, Tymoczko JL, Stryer L. Biochemistry, 9th ed, 2019.
//   Brosnan JT. J Nutr 133:2068S-2072S, 2003 (interorgan amino acid transport)
//   Morris SM Jr. Annu Rev Nutr 22:87-105, 2002 (arginine metabolism)
//   Shane B. Annu Rev Nutr 25:431-455, 2005 (folate and one-carbon metabolism)
//   Danpure CJ. Ann NY Acad Sci 804:504-513, 1996 (peroxisomal targeting)
//
// Marjorie McCubbins + Aether, April 2026
// Patent pending: 64/034,536

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

struct Aminotransferase {
    address: Int,
    name: String,
    abbreviation: String,
    accession: String,
    gene: String,
    cofactor: String,
    amino_donor: String,
    amino_acceptor: String,
    product_keto_acid: String,
    product_amino_acid: String,
    tissue: String,
    clinical: String,
    citation: String,
}

struct UreaCycleStep {
    step_number: Int,
    enzyme_name: String,
    enzyme_abbreviation: String,
    accession: String,
    gene: String,
    location: String,
    substrate: String,
    product: String,
    cofactor: String,
    atp_cost: Int,
    regulation: String,
    deficiency: String,
    citation: String,
}

struct AminoAcidCatabolicFate {
    address: Int,
    code1: String,
    code3: String,
    name: String,
    essential: Bool,
    glucogenic: Bool,
    ketogenic: Bool,
    entry_point: String,
    key_enzyme: String,
    key_enzyme_accession: String,
    clinical_note: String,
    citation: String,
}

struct SpecializedPathway {
    address: Int,
    name: String,
    substrate: String,
    product: String,
    enzyme_name: String,
    enzyme_accession: String,
    enzyme_gene: String,
    cofactor: String,
    tissue: String,
    deficiency_disease: String,
    clinical_note: String,
    citation: String,
}

struct OneCarbonComponent {
    address: Int,
    name: String,
    abbreviation: String,
    role: String,
    enzyme_name: String,
    enzyme_accession: String,
    enzyme_gene: String,
    cofactor: String,
    clinical: String,
    citation: String,
}

struct BCAAMetabolism {
    address: Int,
    amino_acid: String,
    code1: String,
    glucogenic: Bool,
    ketogenic: Bool,
    bcat_product: String,
    bckdh_product: String,
    final_product: String,
    entry_point: String,
    citation: String,
}

struct NitrogenBalance {
    condition: String,
    balance_type: String,
    n_intake_vs_output: String,
    mechanism: String,
    clinical: String,
    citation: String,
}

struct OxidativeDeamination {
    address: Int,
    enzyme_name: String,
    accession: String,
    gene: String,
    substrate: String,
    product_keto: String,
    product_nitrogen: String,
    coenzyme: String,
    direction: String,
    location: String,
    activators: String,
    inhibitors: String,
    clinical: String,
    citation: String,
}

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

fn atrans(addr: Int, nm: String, ab: String, acc: String, gn: String, cof: String, ad: String, aa: String, pk: String, pa: String, ti: String, cl: String, ci: String) -> Aminotransferase {
    return Aminotransferase { address: addr, name: nm, abbreviation: ab, accession: acc, gene: gn, cofactor: cof, amino_donor: ad, amino_acceptor: aa, product_keto_acid: pk, product_amino_acid: pa, tissue: ti, clinical: cl, citation: ci }
}

fn ucs(sn: Int, en: String, ea: String, acc: String, gn: String, loc: String, su: String, pr: String, cof: String, atp: Int, reg: String, def: String, ci: String) -> UreaCycleStep {
    return UreaCycleStep { step_number: sn, enzyme_name: en, enzyme_abbreviation: ea, accession: acc, gene: gn, location: loc, substrate: su, product: pr, cofactor: cof, atp_cost: atp, regulation: reg, deficiency: def, citation: ci }
}

fn aafate(addr: Int, c1: String, c3: String, nm: String, ess: Bool, glu: Bool, ket: Bool, ep: String, ke: String, ka: String, cn: String, ci: String) -> AminoAcidCatabolicFate {
    return AminoAcidCatabolicFate { address: addr, code1: c1, code3: c3, name: nm, essential: ess, glucogenic: glu, ketogenic: ket, entry_point: ep, key_enzyme: ke, key_enzyme_accession: ka, clinical_note: cn, citation: ci }
}

fn spath(addr: Int, nm: String, su: String, pr: String, en: String, ea: String, eg: String, cof: String, ti: String, dd: String, cn: String, ci: String) -> SpecializedPathway {
    return SpecializedPathway { address: addr, name: nm, substrate: su, product: pr, enzyme_name: en, enzyme_accession: ea, enzyme_gene: eg, cofactor: cof, tissue: ti, deficiency_disease: dd, clinical_note: cn, citation: ci }
}

fn ocarb(addr: Int, nm: String, ab: String, rl: String, en: String, ea: String, eg: String, cof: String, cl: String, ci: String) -> OneCarbonComponent {
    return OneCarbonComponent { address: addr, name: nm, abbreviation: ab, role: rl, enzyme_name: en, enzyme_accession: ea, enzyme_gene: eg, cofactor: cof, clinical: cl, citation: ci }
}

fn bcaa(addr: Int, aa: String, c1: String, glu: Bool, ket: Bool, bp: String, bk: String, fp: String, ep: String, ci: String) -> BCAAMetabolism {
    return BCAAMetabolism { address: addr, amino_acid: aa, code1: c1, glucogenic: glu, ketogenic: ket, bcat_product: bp, bckdh_product: bk, final_product: fp, entry_point: ep, citation: ci }
}

fn nbal(cond: String, bt: String, nio: String, mech: String, cl: String, ci: String) -> NitrogenBalance {
    return NitrogenBalance { condition: cond, balance_type: bt, n_intake_vs_output: nio, mechanism: mech, clinical: cl, citation: ci }
}

fn oxdeam(addr: Int, en: String, acc: String, gn: String, su: String, pk: String, pn: String, co: String, dir: String, loc: String, act: String, inh: String, cl: String, ci: String) -> OxidativeDeamination {
    return OxidativeDeamination { address: addr, enzyme_name: en, accession: acc, gene: gn, substrate: su, product_keto: pk, product_nitrogen: pn, coenzyme: co, direction: dir, location: loc, activators: act, inhibitors: inh, clinical: cl, citation: ci }
}

// ═══════════════════════════════════════════════════════
// SECTION I: TRANSAMINATION
// ═══════════════════════════════════════════════════════
//
// Transamination is the reversible transfer of an amino group from an
// amino acid to an alpha-keto acid. The universal amino group acceptor
// is alpha-ketoglutarate, which becomes glutamate. The cofactor is
// pyridoxal phosphate (PLP, the active form of vitamin B6).
//
// PLP forms a Schiff base (aldimine) with the amino acid substrate,
// then a transaldimination moves the amino group to the keto acid.
// This is the first step of amino acid catabolism for most amino acids.
//
// Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23.

fn lookup_aminotransferase(addr: Int) -> Aminotransferase {
    // ALT (alanine aminotransferase, formerly GPT)
    // Liver-specific marker. Elevated ALT = hepatocyte damage.
    if addr == 1 { return atrans(1, "Alanine aminotransferase", "ALT/GPT", "P24298", "GPT", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Alanine", "alpha-Ketoglutarate", "Pyruvate", "Glutamate", "Liver (cytoplasm), also muscle, heart", "Serum ALT is the primary clinical marker for hepatocellular injury. More liver-specific than AST. ALT:AST ratio (De Ritis ratio) >1 suggests viral hepatitis, <1 suggests alcoholic liver disease or cirrhosis.", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // AST (aspartate aminotransferase, formerly GOT)
    // Found in liver, heart, muscle, kidney, brain.
    if addr == 2 { return atrans(2, "Aspartate aminotransferase", "AST/GOT", "P17174", "GOT1", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Aspartate", "alpha-Ketoglutarate", "Oxaloacetate", "Glutamate", "Liver, heart, muscle, kidney, brain (cytoplasmic isoform GOT1; mitochondrial isoform GOT2, P00505)", "Elevated in MI (myocardial infarction), hepatitis, muscle damage. Less liver-specific than ALT. Mitochondrial AST (GOT2) released in severe necrosis.", "Lehninger 8th ed, Ch 18") }

    // BCAT (branched-chain aminotransferase) -- see BCAA section
    if addr == 3 { return atrans(3, "Branched-chain aminotransferase", "BCAT", "P54687", "BCAT1", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Leucine/Isoleucine/Valine", "alpha-Ketoglutarate", "Branched-chain alpha-keto acids", "Glutamate", "Muscle (BCAT1 cytosolic), all tissues (BCAT2 mitochondrial, O15382)", "First step of BCAA catabolism. Muscle is the primary site. BCAAs are the only amino acids NOT catabolized primarily in liver.", "Lehninger 8th ed, Ch 18") }

    // Ornithine aminotransferase
    if addr == 4 { return atrans(4, "Ornithine aminotransferase", "OAT", "P04181", "OAT", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Ornithine", "alpha-Ketoglutarate", "Glutamate-5-semialdehyde", "Glutamate", "Liver, kidney, small intestine (mitochondrial)", "Deficiency causes gyrate atrophy of the choroid and retina (AR, OMIM 258870). Ornithine accumulation is toxic to retinal pigment epithelium.", "Lehninger 8th ed, Ch 18") }

    // Tyrosine aminotransferase
    if addr == 5 { return atrans(5, "Tyrosine aminotransferase", "TAT", "P17735", "TAT", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Tyrosine", "alpha-Ketoglutarate", "4-Hydroxyphenylpyruvate", "Glutamate", "Liver (cytoplasm), induced by glucocorticoids", "Deficiency causes tyrosinemia type II (Richner-Hanhart syndrome, OMIM 276600). Corneal crystals, palmar keratoses, intellectual disability.", "Lehninger 8th ed, Ch 18") }

    return atrans(0, "", "", "", "", "", "", "", "", "", "", "", "")
}

fn plp_cofactor_mechanism() -> String {
    return "Pyridoxal 5-phosphate (PLP) is the active form of vitamin B6. It covalently binds Lys residue in the enzyme active site via Schiff base (internal aldimine). Substrate amino acid displaces the Lys (transaldimination) forming external aldimine. PLP stabilizes carbanion intermediates through its electron sink (extended conjugation to pyridinium nitrogen). PLP participates in transamination, decarboxylation, racemization, aldol cleavage, and beta/gamma elimination. Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23."
}

// ═══════════════════════════════════════════════════════
// SECTION II: OXIDATIVE DEAMINATION
// ═══════════════════════════════════════════════════════
//
// Glutamate dehydrogenase (GDH) is the convergence point for amino
// nitrogen. Most amino acids transaminate to glutamate first. Then
// GDH oxidatively deaminates glutamate, releasing free NH4+ and
// regenerating alpha-ketoglutarate. This is the primary route by
// which amino nitrogen enters the urea cycle as free ammonia.
//
// GDH is allosterically regulated: GTP and ATP inhibit (energy
// surplus, no need to oxidize amino acids), ADP and leucine
// activate (energy deficit, catabolize amino acids for fuel).
//
// Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23.

fn lookup_oxidative_deamination(addr: Int) -> OxidativeDeamination {
    // Glutamate dehydrogenase -- the nitrogen funnel
    if addr == 1 { return oxdeam(1, "Glutamate dehydrogenase", "P00367", "GLUD1", "L-Glutamate + NAD(P)+ + H2O", "alpha-Ketoglutarate", "NH4+ (ammonium)", "NAD+ (primarily) and NADP+ (can use either)", "Bidirectional: oxidative deamination (catabolic) and reductive amination (biosynthetic)", "Mitochondrial matrix (liver, kidney, brain)", "ADP (signals low energy), leucine (amino acid surplus)", "GTP (signals high energy), ATP, palmitoyl-CoA", "Gain-of-function mutations cause hyperinsulinism-hyperammonemia syndrome (HI/HA, OMIM 606762). GDH is overactive, excessive glutamate oxidation releases too much NH4+, and alpha-KG stimulates insulin secretion.", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // D-amino acid oxidase -- handles non-standard D-amino acids
    if addr == 2 { return oxdeam(2, "D-amino acid oxidase", "P14920", "DAO", "D-amino acids + O2 + H2O", "alpha-keto acid", "NH4+ + H2O2", "FAD", "Oxidative deamination (irreversible)", "Peroxisomes (kidney, liver, brain)", "None known", "Benzoate (competitive)", "Degrades D-serine in brain (D-serine is a NMDA receptor co-agonist). DAO polymorphisms associated with schizophrenia susceptibility.", "Lehninger 8th ed, Ch 18") }

    // L-amino acid oxidase
    if addr == 3 { return oxdeam(3, "L-amino acid oxidase", "A1KZ92", "IL4I1", "L-amino acids + O2 + H2O", "alpha-keto acid + H2O2", "NH4+", "FMN", "Oxidative deamination (irreversible)", "Peroxisomes, also found in snake venom", "None known", "None known", "Minor pathway in mammals. Major pathway in snake venom (cytotoxic via H2O2). Human IL4I1 is an immune-regulatory L-amino acid oxidase.", "Lehninger 8th ed, Ch 18") }

    return oxdeam(0, "", "", "", "", "", "", "", "", "", "", "", "", "")
}

fn ammonia_toxicity() -> String {
    return "Free ammonia (NH3/NH4+) is neurotoxic at >50 uM blood concentration (normal 10-35 uM). Mechanism: NH4+ depletes alpha-ketoglutarate from the TCA cycle (via glutamate dehydrogenase reverse reaction), starving neurons of energy. Also: NH3 crosses BBB, astrocytes convert glutamate + NH4+ to glutamine (via glutamine synthetase, P15104), causing osmotic swelling (cerebral edema). Clinical: asterixis, confusion, coma (hepatic encephalopathy). Treatment: lactulose (traps NH4+ in gut), rifaximin (kills urease-producing bacteria). Lehninger 8th ed, Ch 18."
}

// ═══════════════════════════════════════════════════════
// SECTION III: THE UREA CYCLE
// ═══════════════════════════════════════════════════════
//
// The urea cycle converts toxic NH4+ into urea for renal excretion.
// Discovered by Hans Krebs and Kurt Henseleit in 1932 -- the first
// cyclic metabolic pathway ever described, predating the TCA cycle
// by five years.
//
// Location: Steps I-II in mitochondrial matrix, steps III-V in cytoplasm.
// Net reaction: CO2 + NH4+ + 3 ATP + Aspartate + 2 H2O
//   -> Urea + 2 ADP + AMP + 2 Pi + PPi + Fumarate
//
// Each urea molecule carries TWO nitrogens:
//   - One from free NH4+ (via carbamoyl phosphate)
//   - One from aspartate (via argininosuccinate)
//
// Cost: 4 ATP equivalents per urea (3 ATP consumed, but PPi hydrolysis
// = one more high-energy bond). Fumarate returns to TCA cycle,
// partially offsetting the cost.
//
// Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23.

fn urea_cycle_step(step: Int) -> UreaCycleStep {
    // Step I: Carbamoyl phosphate synthetase I (CPS I)
    // THE committed step. Mitochondrial matrix. N-acetylglutamate required.
    if step == 1 { return ucs(1, "Carbamoyl phosphate synthetase I", "CPS I", "P31327", "CPS1", "Mitochondrial matrix", "NH4+ + HCO3- (CO2) + 2 ATP", "Carbamoyl phosphate + 2 ADP + Pi", "N-acetylglutamate (NAG, obligatory activator), Mg2+", 2, "N-acetylglutamate (NAG) is the obligatory allosteric activator. NAG is synthesized by N-acetylglutamate synthase (NAGS, Q8N159) from acetyl-CoA + glutamate. Arginine activates NAGS. This links amino acid catabolism rate to urea cycle flux.", "CPS I deficiency (OMIM 237300): most severe urea cycle disorder. Neonatal hyperammonemia, lethargy, seizures within 24-72 hours of birth. Autosomal recessive. Incidence ~1:62,000.", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // Step II: Ornithine transcarbamylase (OTC)
    // Transfers carbamoyl group to ornithine. Still in mitochondria.
    if step == 2 { return ucs(2, "Ornithine transcarbamylase", "OTC", "P00480", "OTC", "Mitochondrial matrix", "Carbamoyl phosphate + Ornithine", "Citrulline + Pi", "None", 0, "Citrulline is exported to cytoplasm via ornithine/citrulline antiporter (ORNT1, SLC25A15, Q9Y619). Ornithine imported simultaneously.", "OTC deficiency (OMIM 311250): most common urea cycle disorder. X-LINKED (only UCD that is X-linked). Males: severe neonatal hyperammonemia. Female carriers: variable (lyonization). Elevated urinary orotic acid (carbamoyl phosphate diverted to pyrimidine synthesis).", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // Step III: Argininosuccinate synthetase (ASS)
    // Citrulline + aspartate -> argininosuccinate. Cytoplasm. Second nitrogen enters.
    if step == 3 { return ucs(3, "Argininosuccinate synthetase", "ASS", "P00966", "ASS1", "Cytoplasm", "Citrulline + Aspartate + ATP", "Argininosuccinate + AMP + PPi", "Mg2+", 1, "Uses ATP -> AMP + PPi (equivalent to 2 ATP due to PPi hydrolysis by inorganic pyrophosphatase). Aspartate provides the SECOND nitrogen of urea. Aspartate comes from transamination of oxaloacetate by AST.", "Citrullinemia type I (OMIM 215700): elevated plasma citrulline. Neonatal form: severe hyperammonemia. Adult-onset (type II, citrin deficiency, SLC25A13): hepatic dysfunction, protein aversion. Autosomal recessive.", "Lehninger 8th ed, Ch 18") }

    // Step IV: Argininosuccinate lyase (ASL)
    // Cleaves argininosuccinate into arginine + fumarate.
    if step == 4 { return ucs(4, "Argininosuccinate lyase", "ASL", "P04424", "ASL", "Cytoplasm", "Argininosuccinate", "Arginine + Fumarate", "None", 0, "Fumarate returns to TCA cycle (via fumarase -> malate -> oxaloacetate). This connects the urea cycle to the TCA cycle (the Krebs bicycle). Oxaloacetate can be transaminated back to aspartate, recycling the carrier.", "Argininosuccinic aciduria (OMIM 207900): elevated argininosuccinate in blood and urine. Trichorrhexis nodosa (brittle hair) is pathognomonic. Autosomal recessive. Incidence ~1:70,000.", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // Step V: Arginase
    // Cleaves arginine into urea + ornithine. Ornithine re-enters mitochondria.
    if step == 5 { return ucs(5, "Arginase", "ARG1", "P05089", "ARG1", "Cytoplasm", "Arginine + H2O", "Urea + Ornithine", "Mn2+ (binuclear manganese center)", 0, "Ornithine is transported back into mitochondria via ORNT1 (SLC25A15) to restart the cycle. Liver arginase (ARG1) is the urea cycle enzyme. Kidney/macrophage arginase (ARG2, P78540) regulates arginine availability for NOS.", "Hyperargininemia (OMIM 207800): progressive spastic diplegia, intellectual disability. Mildest urea cycle disorder. Autosomal recessive. Arginine accumulates and its metabolite guanidinoacetate is neurotoxic.", "Lehninger 8th ed, Ch 18") }

    return ucs(0, "", "", "", "", "", "", "", "", 0, "", "", "")
}

fn urea_cycle_net_reaction() -> String {
    return "CO2 + NH4+ + 3 ATP + Aspartate + 2 H2O -> Urea + 2 ADP + AMP + 2 Pi + PPi + Fumarate. Net cost: 4 high-energy phosphate bonds (3 ATP + PPi hydrolysis). Each urea carries 2 nitrogens: one from free NH4+ (CPS I), one from aspartate (ASS). Humans excrete ~30 g urea/day on a normal protein diet. Lehninger 8th ed, Ch 18."
}

fn nag_activation() -> String {
    return "N-acetylglutamate (NAG) is synthesized by NAGS (N-acetylglutamate synthase, Q8N159) from acetyl-CoA + glutamate. NAG is the OBLIGATORY allosteric activator of CPS I. Without NAG, CPS I is inactive and the urea cycle cannot run. Arginine allosterically activates NAGS, linking amino acid catabolism rate to urea disposal rate. NAGS deficiency (OMIM 237310) causes hyperammonemia treatable with N-carbamylglutamate (Carbaglu), a synthetic NAG analogue. Lehninger 8th ed, Ch 18."
}

fn hyperammonemia_causes(cause: String) -> String {
    if cause == "urea_cycle_defect" { return "Any of the 6 urea cycle enzyme deficiencies (CPS I, OTC, ASS, ASL, ARG1, NAGS). Combined incidence ~1:30,000. OTC deficiency is most common (X-linked). Neonatal onset: lethargy, vomiting, hyperventilation (respiratory alkalosis from central stimulation), seizures, coma. Late-onset: protein aversion, episodic confusion, vomiting." }
    if cause == "liver_failure" { return "Hepatic encephalopathy. Cirrhosis, fulminant hepatitis. Liver cannot run urea cycle at adequate rate. NH4+ from gut bacteria (urease) and amino acid catabolism accumulates. Treatment: lactulose, rifaximin, protein restriction." }
    if cause == "organic_acidemias" { return "Propionic acidemia, methylmalonic acidemia. Accumulated organic acids inhibit NAGS (N-acetylglutamate synthase), reducing CPS I activation. Secondary hyperammonemia." }
    if cause == "valproate" { return "Valproic acid inhibits CPS I and depletes carnitine. Can precipitate hyperammonemia especially in patients with partial OTC deficiency (heterozygous females)." }
    if cause == "urease_infection" { return "Proteus mirabilis and other urease-positive bacteria split urea back to NH4+ + CO2 in the urinary tract. Contributes to hyperammonemia in UTI, especially with urinary diversion." }
    return ""
}

// ═══════════════════════════════════════════════════════
// SECTION IV: AMINO ACID CLASSIFICATION
// ═══════════════════════════════════════════════════════
//
// Amino acids are classified by their catabolic fate:
//   - Glucogenic: carbon skeleton enters gluconeogenesis
//     (via pyruvate, oxaloacetate, alpha-KG, succinyl-CoA, fumarate)
//   - Ketogenic: carbon skeleton yields acetyl-CoA or acetoacetyl-CoA
//     (cannot make net glucose in animals)
//   - Both: some carbons are glucogenic, others ketogenic
//
// Essential amino acids cannot be synthesized de novo by humans.
// Mnemonic: PVT TIM HALL (Phe, Val, Thr, Trp, Ile, Met, His, Arg*, Leu, Lys)
// *Arg is conditionally essential (essential in growth/stress).
//
// Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23.

fn amino_acid_catabolic_fate(addr: Int) -> AminoAcidCatabolicFate {
    // Alanine: glucogenic via pyruvate (ALT transamination)
    if addr == 1  { return aafate(1,  "A", "Ala", "Alanine",       false, true,  false, "Pyruvate (via ALT transamination)", "Alanine aminotransferase (ALT)", "P24298", "Major gluconeogenic amino acid. Glucose-alanine cycle: muscle exports alanine to liver for gluconeogenesis.", "Lehninger 8th ed, Ch 18") }

    // Arginine: glucogenic via alpha-KG (through glutamate/ornithine)
    if addr == 2  { return aafate(2,  "R", "Arg", "Arginine",      false, true,  false, "alpha-Ketoglutarate (via glutamate semialdehyde -> glutamate)", "Arginase (urea cycle step V)", "P05089", "Conditionally essential in growth, injury, sepsis. Also yields NO via NOS and creatine via AGAT.", "Lehninger 8th ed, Ch 18") }

    // Asparagine: glucogenic via oxaloacetate (through aspartate)
    if addr == 3  { return aafate(3,  "N", "Asn", "Asparagine",    false, true,  false, "Oxaloacetate (via asparaginase -> aspartate -> AST -> OAA)", "Asparaginase", "P08243", "Leukemia cells cannot synthesize asparagine de novo. L-asparaginase (Elspar) is used as chemotherapy for ALL.", "Lehninger 8th ed, Ch 18") }

    // Aspartate: glucogenic via oxaloacetate (AST transamination)
    if addr == 4  { return aafate(4,  "D", "Asp", "Aspartate",     false, true,  false, "Oxaloacetate (via AST transamination)", "Aspartate aminotransferase (AST)", "P17174", "Provides one nitrogen to urea cycle (ASS step). Also feeds into purine and pyrimidine biosynthesis.", "Lehninger 8th ed, Ch 18") }

    // Cysteine: glucogenic via pyruvate
    if addr == 5  { return aafate(5,  "C", "Cys", "Cysteine",      false, true,  false, "Pyruvate (via cysteine dioxygenase -> beta-sulfinylpyruvate -> pyruvate + SO3^2-)", "Cysteine dioxygenase", "Q16878", "Synthesized from methionine via transsulfuration pathway (cystathionine beta-synthase, CBS). Sulfur donor for glutathione, taurine, iron-sulfur clusters.", "Lehninger 8th ed, Ch 18") }

    // Glutamate: glucogenic via alpha-KG
    if addr == 6  { return aafate(6,  "E", "Glu", "Glutamate",     false, true,  false, "alpha-Ketoglutarate (via glutamate dehydrogenase or transamination)", "Glutamate dehydrogenase", "P00367", "Central amino acid in nitrogen metabolism. Collects amino groups from other amino acids via transamination. Major excitatory neurotransmitter.", "Lehninger 8th ed, Ch 18") }

    // Glutamine: glucogenic via alpha-KG (through glutamate)
    if addr == 7  { return aafate(7,  "Q", "Gln", "Glutamine",     false, true,  false, "alpha-Ketoglutarate (via glutaminase -> glutamate -> GDH -> alpha-KG)", "Glutaminase", "O94925", "Most abundant amino acid in blood. Nitrogen shuttle between tissues. Fuel for enterocytes and immune cells. Conditionally essential in critical illness.", "Lehninger 8th ed, Ch 18") }

    // Glycine: glucogenic via pyruvate (through serine)
    if addr == 8  { return aafate(8,  "G", "Gly", "Glycine",       false, true,  false, "Pyruvate (via serine hydroxymethyltransferase -> serine -> serine dehydratase -> pyruvate)", "Serine hydroxymethyltransferase (SHMT)", "P34896", "One-carbon donor to folate pool. Required for heme (ALA synthase), glutathione, purines, creatine, conjugation reactions (bile acids).", "Lehninger 8th ed, Ch 18") }

    // Histidine: glucogenic via alpha-KG (through glutamate)
    if addr == 9  { return aafate(9,  "H", "His", "Histidine",     true,  true,  false, "alpha-Ketoglutarate (via urocanate -> imidazolone propionate -> formiminoglutamate -> glutamate)", "Histidase", "P42357", "Essential. Decarboxylation yields histamine (HDC, P19113). FIGLU (formiminoglutamate) accumulation in urine indicates folate deficiency.", "Lehninger 8th ed, Ch 18") }

    // Isoleucine: BOTH glucogenic and ketogenic
    if addr == 10 { return aafate(10, "I", "Ile", "Isoleucine",    true,  true,  true,  "Succinyl-CoA (glucogenic) + Acetyl-CoA (ketogenic)", "BCAT then BCKDH complex", "P54687", "Essential. BCAA. Degraded primarily in muscle. See BCAA section.", "Lehninger 8th ed, Ch 18") }

    // Leucine: PURELY ketogenic (only amino acid that is purely ketogenic)
    if addr == 11 { return aafate(11, "L", "Leu", "Leucine",       true,  false, true,  "Acetyl-CoA + Acetoacetate (purely ketogenic, NO glucogenic contribution)", "BCAT then BCKDH complex", "P54687", "Essential. The ONLY purely ketogenic amino acid. Potent activator of mTORC1 (protein synthesis). Stimulates insulin secretion. BCAA.", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // Lysine: PURELY ketogenic
    if addr == 12 { return aafate(12, "K", "Lys", "Lysine",        true,  false, true,  "Acetoacetyl-CoA (via saccharopine pathway: alpha-aminoadipate -> glutaryl-CoA -> acetoacetyl-CoA)", "Alpha-aminoadipate semialdehyde synthase (AASS)", "Q9UDR5", "Essential. Purely ketogenic (along with leucine). Cannot undergo transamination (epsilon-amino group). Hydroxylated in collagen (requires vitamin C).", "Lehninger 8th ed, Ch 18") }

    // Methionine: glucogenic via succinyl-CoA
    if addr == 13 { return aafate(13, "M", "Met", "Methionine",    true,  true,  false, "Succinyl-CoA (via homocysteine -> cystathionine -> alpha-ketobutyrate -> propionyl-CoA -> succinyl-CoA)", "Methionine adenosyltransferase (MAT)", "Q00266", "Essential. Initiator amino acid (Met-tRNA_i). Source of methyl groups via SAM (S-adenosylmethionine). Methionine cycle connects to folate cycle.", "Lehninger 8th ed, Ch 18") }

    // Phenylalanine: BOTH glucogenic and ketogenic
    if addr == 14 { return aafate(14, "F", "Phe", "Phenylalanine", true,  true,  true,  "Fumarate (glucogenic) + Acetoacetate (ketogenic), via tyrosine catabolism", "Phenylalanine hydroxylase (PAH)", "P00439", "Essential. PAH converts Phe to Tyr (requires BH4 cofactor). PAH deficiency = phenylketonuria (PKU). See specialized pathways.", "Lehninger 8th ed, Ch 18") }

    // Proline: glucogenic via alpha-KG (through glutamate)
    if addr == 15 { return aafate(15, "P", "Pro", "Proline",       false, true,  false, "alpha-Ketoglutarate (via proline dehydrogenase -> P5C -> glutamate -> alpha-KG)", "Proline dehydrogenase (PRODH)", "O43272", "Major component of collagen (every third residue). Hydroxyproline (via prolyl hydroxylase, requires vitamin C) stabilizes collagen triple helix. Scurvy = collagen failure.", "Lehninger 8th ed, Ch 18") }

    // Serine: glucogenic via pyruvate
    if addr == 16 { return aafate(16, "S", "Ser", "Serine",        false, true,  false, "Pyruvate (via serine dehydratase, direct)", "Serine dehydratase", "P20132", "One-carbon donor to folate pool (via SHMT). Precursor for sphingolipids, phosphatidylserine, D-serine (NMDA co-agonist). Synthesized from 3-phosphoglycerate (glycolysis).", "Lehninger 8th ed, Ch 18") }

    // Threonine: glucogenic via succinyl-CoA (and some pyruvate)
    if addr == 17 { return aafate(17, "T", "Thr", "Threonine",     true,  true,  false, "Succinyl-CoA (via alpha-ketobutyrate -> propionyl-CoA -> succinyl-CoA) and Pyruvate (via threonine aldolase -> glycine + acetaldehyde)", "Threonine dehydrogenase", "Q8IZJ6", "Essential. Two catabolic pathways in humans: threonine dehydratase (to alpha-ketobutyrate) and threonine aldolase (to glycine + acetaldehyde).", "Lehninger 8th ed, Ch 18") }

    // Tryptophan: BOTH glucogenic and ketogenic
    if addr == 18 { return aafate(18, "W", "Trp", "Tryptophan",    true,  true,  true,  "Alanine/Pyruvate (glucogenic) + Acetoacetyl-CoA (ketogenic), via kynurenine pathway", "Tryptophan 2,3-dioxygenase (TDO) and Indoleamine 2,3-dioxygenase (IDO)", "P48775", "Essential. Precursor for serotonin (via TPH), melatonin, NAD+ (via kynurenine pathway). See specialized pathways.", "Lehninger 8th ed, Ch 18") }

    // Tyrosine: BOTH glucogenic and ketogenic
    if addr == 19 { return aafate(19, "Y", "Tyr", "Tyrosine",      false, true,  true,  "Fumarate (glucogenic) + Acetoacetate (ketogenic)", "Tyrosine aminotransferase (TAT)", "P17735", "Non-essential (synthesized from Phe by PAH). Precursor for catecholamines (dopamine, NE, epi), melanin, thyroid hormones. See specialized pathways.", "Lehninger 8th ed, Ch 18") }

    // Valine: glucogenic via succinyl-CoA
    if addr == 20 { return aafate(20, "V", "Val", "Valine",        true,  true,  false, "Succinyl-CoA (via isobutyryl-CoA -> methylmalonyl-CoA -> succinyl-CoA)", "BCAT then BCKDH complex", "P54687", "Essential. BCAA. Glucogenic only (unlike Ile which is both). Degraded primarily in muscle.", "Lehninger 8th ed, Ch 18") }

    return aafate(0, "", "", "", false, false, false, "", "", "", "", "")
}

fn glucogenic_amino_acids() -> String {
    return "Ala, Arg, Asn, Asp, Cys, Glu, Gln, Gly, His, Met, Pro, Ser, Thr, Val (14 purely glucogenic). Ile, Phe, Trp, Tyr are both glucogenic and ketogenic. Total 18 of 20 have glucogenic potential. Lehninger 8th ed, Ch 18."
}

fn ketogenic_amino_acids() -> String {
    return "Leu and Lys are PURELY ketogenic (yield only acetyl-CoA or acetoacetate, cannot make net glucose). Ile, Phe, Trp, Tyr are both glucogenic and ketogenic. Total 6 of 20 have ketogenic potential. Lehninger 8th ed, Ch 18."
}

fn essential_amino_acids() -> String {
    return "PVT TIM HALL: Phe, Val, Thr, Trp, Ile, Met, His, Arg (conditionally), Leu, Lys. Nine are strictly essential. Arginine is conditionally essential (required during growth, pregnancy, trauma, sepsis because endogenous synthesis is insufficient). Lehninger 8th ed, Ch 18."
}

// ═══════════════════════════════════════════════════════
// SECTION V: SPECIALIZED AMINO ACID PATHWAYS
// ═══════════════════════════════════════════════════════
//
// Several amino acids serve as precursors for critical signaling
// molecules, pigments, and cofactors. These pathways are clinically
// significant because their enzyme deficiencies produce recognizable
// inborn errors of metabolism.
//
// Lehninger 8th ed, Ch 18 and 22; Stryer 9th ed, Ch 23 and 24.

fn specialized_pathway(addr: Int) -> SpecializedPathway {
    // Phenylalanine -> Tyrosine (PAH, PKU)
    if addr == 1  { return spath(1, "Phenylalanine hydroxylation", "L-Phenylalanine + O2 + BH4", "L-Tyrosine + H2O + BH2", "Phenylalanine hydroxylase", "P00439", "PAH", "Tetrahydrobiopterin (BH4)", "Liver", "Phenylketonuria (PKU, OMIM 261600)", "PKU: AR, incidence ~1:10,000. Phenylalanine accumulates (>20 mg/dL), converted to phenylpyruvate (musty odor in urine). Untreated: severe intellectual disability, seizures, hypopigmentation (Phe competes with Tyr for melanin synthesis). Treatment: Phe-restricted diet from birth, BH4 supplementation (sapropterin/Kuvan) for BH4-responsive variants. Mandatory newborn screening. Maternal PKU: uncontrolled Phe during pregnancy causes microcephaly, congenital heart defects in fetus.", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23") }

    // Tyrosine -> DOPA -> Dopamine -> Norepinephrine -> Epinephrine
    if addr == 2  { return spath(2, "Tyrosine -> Catecholamines", "L-Tyrosine", "DOPA -> Dopamine -> Norepinephrine -> Epinephrine", "Tyrosine hydroxylase (TH, rate-limiting)", "P07101", "TH", "Tetrahydrobiopterin (BH4), Fe2+", "Adrenal medulla, sympathetic neurons, CNS dopaminergic neurons", "TH deficiency: dopa-responsive dystonia", "Catecholamine biosynthesis pathway: Tyr -[TH, BH4]-> L-DOPA -[AADC, P20711, PLP]-> Dopamine -[DBH, P09172, ascorbate/Cu2+]-> Norepinephrine -[PNMT, P11086, SAM]-> Epinephrine. TH is rate-limiting and regulated by phosphorylation, end-product inhibition by catecholamines, and transcriptional control. Pheochromocytoma: catecholamine-secreting adrenal tumor, episodic hypertension.", "Lehninger 8th ed, Ch 22; Stryer 9th ed, Ch 24") }

    // Tyrosine -> Melanin
    if addr == 3  { return spath(3, "Tyrosine -> Melanin", "L-Tyrosine", "Eumelanin (brown/black) and Pheomelanin (red/yellow)", "Tyrosinase", "P14679", "TYR", "Cu2+", "Melanocytes (skin, hair, iris, substantia nigra)", "Oculocutaneous albinism type I (OCA1, OMIM 203100)", "Tyrosinase converts Tyr -> DOPA -> Dopaquinone. Dopaquinone spontaneously cyclizes to form eumelanin (via dopachrome). With cysteine present, dopaquinone forms cysteinyl-DOPA -> pheomelanin. MC1R (P41145) determines eumelanin vs pheomelanin ratio. OCA1: no melanin, nystagmus, photophobia, increased skin cancer risk.", "Lehninger 8th ed, Ch 22") }

    // Tryptophan -> Serotonin -> Melatonin
    if addr == 4  { return spath(4, "Tryptophan -> Serotonin -> Melatonin", "L-Tryptophan", "Serotonin (5-HT), then Melatonin", "Tryptophan hydroxylase (TPH, rate-limiting)", "P17752", "TPH1", "Tetrahydrobiopterin (BH4)", "Enterochromaffin cells of gut (TPH1, 95% of serotonin), raphe nuclei of brainstem (TPH2, P17752, central serotonin)", "Carcinoid syndrome (serotonin-secreting tumor)", "Pathway: Trp -[TPH, BH4]-> 5-HTP -[AADC, PLP]-> Serotonin (5-HT) -[AANAT, Q16613]-> N-Acetylserotonin -[ASMT, P46597, SAM]-> Melatonin. 95% of serotonin is made in gut (not brain). Carcinoid: serotonin excess causes flushing, diarrhea, bronchoconstriction, right-sided heart valve fibrosis. Tryptophan diverted from NAD+ synthesis -> pellagra-like symptoms.", "Lehninger 8th ed, Ch 22; Stryer 9th ed, Ch 24") }

    // Tryptophan -> NAD+ (kynurenine pathway)
    if addr == 5  { return spath(5, "Tryptophan -> NAD+ (kynurenine pathway)", "L-Tryptophan", "NAD+ (nicotinamide adenine dinucleotide)", "Tryptophan 2,3-dioxygenase (TDO, liver) and Indoleamine 2,3-dioxygenase (IDO, extrahepatic)", "P48775", "TDO2", "Heme (Fe2+)", "Liver (TDO), immune cells and placenta (IDO1, P14902; IDO2, Q6ZQW0)", "Pellagra (combined Trp + niacin deficiency)", "Kynurenine pathway: Trp -[TDO/IDO]-> N-formylkynurenine -> Kynurenine -> 3-OH-Kynurenine -> 3-OH-Anthranilic acid -> Quinolinic acid -> NAD+. Only ~2% of dietary Trp goes to serotonin; majority enters kynurenine pathway. IDO is induced by IFN-gamma (immune activation depletes Trp to starve intracellular pathogens). Kynurenine:Trp ratio is a biomarker of immune activation. Quinolinic acid is an NMDA agonist (neurotoxic).", "Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 24") }

    // Histidine -> Histamine
    if addr == 6  { return spath(6, "Histidine -> Histamine", "L-Histidine", "Histamine", "Histidine decarboxylase (HDC)", "P19113", "HDC", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Mast cells, basophils, enterochromaffin-like cells of stomach, histaminergic neurons (tuberomammillary nucleus)", "Mastocytosis (mast cell proliferation)", "Single decarboxylation step. Histamine acts on four receptors: H1 (allergic inflammation, vasodilation, bronchoconstriction), H2 (gastric acid secretion, cardiac stimulation), H3 (presynaptic autoreceptor in CNS, regulates wakefulness), H4 (immune cell chemotaxis). Antihistamines: diphenhydramine (H1), ranitidine (H2). Histamine is degraded by histamine N-methyltransferase (HNMT, P50135, SAM) and diamine oxidase (ABP1, P19801).", "Lehninger 8th ed, Ch 22; Stryer 9th ed, Ch 24") }

    // Glutamate -> GABA
    if addr == 7  { return spath(7, "Glutamate -> GABA", "L-Glutamate", "gamma-Aminobutyric acid (GABA)", "Glutamic acid decarboxylase (GAD)", "Q05329", "GAD2", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "GABAergic neurons throughout CNS (GAD67/GAD1 in soma, GAD65/GAD2 at nerve terminals)", "GAD65 autoantibodies in stiff-person syndrome and type I diabetes", "Single decarboxylation step. GABA is the primary inhibitory neurotransmitter in the brain. GAD67 (GAD1, Q99259): constitutive, maintains basal GABA levels. GAD65 (GAD2): regulated, responds to demand at synapses. GABA-T (P80404, ABAT) catabolizes GABA to succinic semialdehyde -> succinate (enters TCA). Vigabatrin (irreversible GABA-T inhibitor) used for infantile spasms. Benzodiazepines and barbiturates potentiate GABA-A receptor.", "Lehninger 8th ed, Ch 22; Stryer 9th ed, Ch 24") }

    // Arginine -> Nitric Oxide (NOS)
    if addr == 8  { return spath(8, "Arginine -> Nitric Oxide", "L-Arginine + O2 + NADPH", "Nitric Oxide (NO) + L-Citrulline", "Nitric oxide synthase (NOS)", "P29474", "NOS1", "BH4, FAD, FMN, heme, calmodulin", "Endothelium (eNOS/NOS3, P29474), macrophages (iNOS/NOS2, P35228), neurons (nNOS/NOS1, P29475)", "NOS dysfunction: endothelial dysfunction, hypertension", "Three NOS isoforms: nNOS (NOS1, P29475, constitutive, Ca2+/CaM-dependent, neuronal signaling), eNOS (NOS3, P29474, constitutive, Ca2+/CaM-dependent, vasodilation), iNOS (NOS2, P35228, inducible by cytokines, Ca2+-independent, sustained NO for pathogen killing). NO activates soluble guanylyl cyclase -> cGMP -> smooth muscle relaxation. Sildenafil (Viagra) inhibits PDE5 which degrades cGMP. Nobel Prize 1998 to Furchgott, Ignarro, Murad.", "Lehninger 8th ed, Ch 22; Stryer 9th ed, Ch 24; Morris SM Jr. Annu Rev Nutr 22:87-105, 2002") }

    // Arginine -> Creatine
    if addr == 9  { return spath(9, "Arginine -> Creatine", "L-Arginine + Glycine", "Creatine (via guanidinoacetate)", "Arginine-glycine amidinotransferase (AGAT)", "P50440", "GATM", "None", "Kidney (AGAT), liver (GAMT)", "Creatine deficiency syndromes (intellectual disability, seizures)", "Two-step synthesis: (a) AGAT (P50440, kidney): Arg + Gly -> Guanidinoacetate + Ornithine. (b) GAMT (Q14353, liver): Guanidinoacetate + SAM -> Creatine + SAH. Creatine kinase (P06732, CKM) phosphorylates creatine to phosphocreatine, the rapid ATP buffer in muscle and brain. Consumes ~70% of SAM in humans (massive methyl demand). Serum creatinine (spontaneous cyclization of phosphocreatine) is a clinical marker of GFR.", "Lehninger 8th ed, Ch 22") }

    // Methionine -> Cysteine (transsulfuration pathway)
    if addr == 10 { return spath(10, "Methionine -> Cysteine (transsulfuration)", "L-Homocysteine + L-Serine", "L-Cysteine + alpha-Ketobutyrate + NH4+", "Cystathionine beta-synthase (CBS)", "P35520", "CBS", "Pyridoxal 5-phosphate (PLP, vitamin B6)", "Liver (primary), kidney, brain", "Homocystinuria (CBS deficiency, OMIM 236200)", "Two-step transsulfuration: (a) CBS (P35520): Homocysteine + Serine -> Cystathionine + H2O. (b) Cystathionine gamma-lyase (CTH, P32929): Cystathionine -> Cysteine + alpha-Ketobutyrate + NH4+. CBS deficiency: elevated plasma homocysteine (>100 uM), lens subluxation (downward), marfanoid habitus, thromboembolism, intellectual disability. Treatment: pyridoxine (B6, enhances residual CBS), betaine (alternative remethylation), methionine-restricted diet.", "Lehninger 8th ed, Ch 18 and 22") }

    return spath(0, "", "", "", "", "", "", "", "", "", "", "")
}

// ═══════════════════════════════════════════════════════
// SECTION VI: ONE-CARBON METABOLISM
// ═══════════════════════════════════════════════════════
//
// One-carbon metabolism is the network of folate-dependent reactions
// that transfer single carbon units (methyl, methylene, formyl) for
// biosynthesis of purines, thymidylate, methionine, and methylation
// reactions. Two interlocking cycles:
//
//   (a) Folate cycle: THF carries one-carbon units at different
//       oxidation levels (methyl, methylene, methenyl, formyl)
//   (b) Methionine cycle: SAM donates methyl groups, regenerated
//       via homocysteine remethylation (requires folate + B12)
//
// Vitamin B12 (cobalamin) is required by methionine synthase to
// transfer the methyl group from methyl-THF to homocysteine.
// Without B12, folate is trapped as methyl-THF ("methyl trap"),
// depleting all other THF forms and impairing DNA synthesis.
//
// Lehninger 8th ed, Ch 18 and 22; Shane B. Annu Rev Nutr 25:431-455, 2005.

fn one_carbon_component(addr: Int) -> OneCarbonComponent {
    // THF (tetrahydrofolate) -- the one-carbon carrier
    if addr == 1  { return ocarb(1, "Tetrahydrofolate", "THF", "The reduced, active form of folic acid (vitamin B9). Carries one-carbon units covalently attached to N5 and/or N10.", "Dihydrofolate reductase (DHFR, reduces DHF back to THF)", "P00374", "DHFR", "NADPH", "Methotrexate (MTX) inhibits DHFR, depletes THF, blocks purine and thymidylate synthesis. Used in cancer, rheumatoid arthritis, ectopic pregnancy. Leucovorin (folinic acid) rescues normal cells.", "Lehninger 8th ed, Ch 22; Shane B. Annu Rev Nutr 25:431-455, 2005") }

    // Methylene-THF -- for thymidylate synthesis
    if addr == 2  { return ocarb(2, "5,10-Methylene-THF", "CH2-THF", "Carries a methylene group (-CH2-) bridging N5 and N10. Used by thymidylate synthase (TS) to convert dUMP -> dTMP (DNA synthesis).", "Serine hydroxymethyltransferase (SHMT)", "P34896", "SHMT1", "PLP (vitamin B6)", "5-Fluorouracil (5-FU) forms a ternary complex with TS and CH2-THF, irreversibly inhibiting thymidylate synthesis. Cancer chemotherapy.", "Lehninger 8th ed, Ch 22") }

    // Methenyl-THF -- intermediate oxidation
    if addr == 3  { return ocarb(3, "5,10-Methenyl-THF", "CH=THF", "Carries a methenyl group (=CH-) bridging N5 and N10. Intermediate between formyl-THF and methylene-THF.", "Methylenetetrahydrofolate dehydrogenase (MTHFD1, trifunctional)", "P11586", "MTHFD1", "NADP+", "MTHFD1 is a trifunctional enzyme: methylene-THF dehydrogenase + methenyl-THF cyclohydrolase + formyl-THF synthetase.", "Lehninger 8th ed, Ch 22") }

    // Formyl-THF -- for purine synthesis
    if addr == 4  { return ocarb(4, "10-Formyl-THF", "CHO-THF", "Carries a formyl group (-CHO) on N10. Provides carbons C2 and C8 of the purine ring during de novo purine biosynthesis.", "MTHFD1 (formyl-THF synthetase activity)", "P11586", "MTHFD1", "ATP", "Essential for purine ring assembly. Rapidly dividing cells (immune, cancer) are especially dependent. Antifolates exploit this.", "Lehninger 8th ed, Ch 22") }

    // Methyl-THF -- for homocysteine remethylation
    if addr == 5  { return ocarb(5, "5-Methyl-THF", "CH3-THF", "Carries a methyl group on N5. The most abundant circulating form of folate. Donates its methyl group to homocysteine (via methionine synthase) to regenerate methionine and THF.", "Methylenetetrahydrofolate reductase (MTHFR, irreversible)", "P42898", "MTHFR", "FAD (vitamin B2), NADPH", "MTHFR C677T polymorphism (Ala222Val): ~10% of population homozygous (TT). Reduces MTHFR activity ~70%. Elevated homocysteine, increased neural tube defect risk. 5-methyl-THF is the methyl trap substrate.", "Lehninger 8th ed, Ch 22; Shane B. Annu Rev Nutr 25:431-455, 2005") }

    // SAM (S-adenosylmethionine) -- the universal methyl donor
    if addr == 6  { return ocarb(6, "S-Adenosylmethionine", "SAM", "The universal methyl donor for >200 methyltransferase reactions: DNA methylation (DNMT), histone methylation, catecholamine catabolism (COMT), creatine synthesis (GAMT), phospholipid synthesis (PEMT). Methyl group transfer produces SAH.", "Methionine adenosyltransferase (MAT)", "Q00266", "MAT1A", "ATP, Mg2+", "SAM depletion disrupts epigenetic regulation globally. Liver disease impairs MAT1A expression. SAM supplementation studied in depression and liver disease.", "Lehninger 8th ed, Ch 18 and 22") }

    // SAH (S-adenosylhomocysteine) -- product inhibitor
    if addr == 7  { return ocarb(7, "S-Adenosylhomocysteine", "SAH", "Product of SAM after methyl group donation. Potent competitive inhibitor of most SAM-dependent methyltransferases. Must be cleared to maintain methylation capacity.", "S-Adenosylhomocysteine hydrolase (AHCY)", "P23526", "AHCY", "NAD+ (tightly bound)", "SAH:SAM ratio is the methylation index. High SAH (low clearance) = global hypomethylation. AHCY deficiency (rare) causes severe hypermethioninemia and myopathy.", "Lehninger 8th ed, Ch 22") }

    // Homocysteine -- the branch point
    if addr == 8  { return ocarb(8, "Homocysteine", "Hcy", "Branch point metabolite. Can be remethylated to methionine (methionine synthase, requires B12 + folate) or transsulfurated to cysteine (CBS, requires B6). Elevated Hcy is an independent cardiovascular risk factor.", "Methionine synthase (remethylation) and CBS (transsulfuration)", "Q99707", "MTR", "Cobalamin (vitamin B12, methylcobalamin)", "Hyperhomocysteinemia (>15 uM): risk factor for atherosclerosis, venous thromboembolism, stroke. Causes: MTHFR C677T, B12 deficiency, B6 deficiency, folate deficiency, CBS deficiency, chronic kidney disease. Homocysteine damages endothelium, promotes oxidative stress, impairs NO bioavailability.", "Lehninger 8th ed, Ch 18 and 22") }

    // Methionine synthase (B12-dependent)
    if addr == 9  { return ocarb(9, "Methionine synthase", "MS", "Transfers methyl group from 5-methyl-THF to homocysteine, regenerating methionine and THF. Requires methylcobalamin (methyl-B12) as intermediate carrier. The ONLY reaction that recycles methyl-THF back to THF.", "Methionine synthase", "Q99707", "MTR", "Methylcobalamin (vitamin B12)", "B12 deficiency traps folate as 5-methyl-THF (methyl trap hypothesis). All other THF forms become depleted. Result: impaired purine and thymidylate synthesis -> megaloblastic anemia. Neurological damage (subacute combined degeneration) from impaired methylation of myelin. Pernicious anemia: autoimmune destruction of parietal cells -> no intrinsic factor -> no B12 absorption.", "Lehninger 8th ed, Ch 22; Stryer 9th ed, Ch 24") }

    // MTHFR -- the gatekeeper
    if addr == 10 { return ocarb(10, "Methylenetetrahydrofolate reductase", "MTHFR", "Irreversibly reduces 5,10-methylene-THF to 5-methyl-THF. This commits the one-carbon unit to homocysteine remethylation (and thus methylation reactions). MTHFR is the gatekeeper between nucleotide synthesis and methylation.", "Methylenetetrahydrofolate reductase", "P42898", "MTHFR", "FAD (vitamin B2), NADPH", "MTHFR C677T: most common genetic cause of mild hyperhomocysteinemia. TT genotype: ~70% reduced activity, thermolabile enzyme. Neural tube defect risk: folic acid supplementation (400 ug/day preconception) reduces NTD risk by ~70% regardless of MTHFR genotype. This is why flour is fortified with folic acid (US mandate since 1998).", "Lehninger 8th ed, Ch 22; Shane B. Annu Rev Nutr 25:431-455, 2005") }

    return ocarb(0, "", "", "", "", "", "", "", "", "")
}

fn methyl_trap_hypothesis() -> String {
    return "In vitamin B12 deficiency, methionine synthase cannot function. 5-Methyl-THF accumulates because MTHFR is irreversible (methyl-THF cannot be converted back to methylene-THF). All folate becomes trapped as methyl-THF. Consequence: no methylene-THF for thymidylate synthase (impaired DNA synthesis -> megaloblastic anemia), no formyl-THF for purine synthesis. Paradox: serum folate levels may be NORMAL (all folate is present, just trapped in the wrong form). This is why B12 deficiency and folate deficiency produce identical megaloblastic anemia. WARNING: giving folate to a B12-deficient patient corrects the anemia but NOT the neurological damage (subacute combined degeneration). Always check B12 before treating megaloblastic anemia with folate. Lehninger 8th ed, Ch 22."
}

fn neural_tube_defect_prevention() -> String {
    return "Neural tube closure occurs at days 21-28 post-conception (before most women know they are pregnant). Folate is required for rapid cell division during neurulation. Deficiency -> incomplete closure -> anencephaly (cranial, fatal) or spina bifida (caudal). Folic acid supplementation (400 ug/day) starting at least one month before conception reduces NTD risk by ~70%. US FDA mandated folic acid fortification of enriched grain products in 1998. NTD incidence dropped ~25% following fortification. MTHFR C677T TT genotype increases NTD risk ~2-fold, but supplementation is protective regardless of genotype. Lehninger 8th ed, Ch 22."
}

fn clinical_folate_b12(condition: String) -> String {
    if condition == "megaloblastic_anemia" { return "Macrocytic (MCV >100 fL) anemia with hypersegmented neutrophils (>5 lobes). Impaired DNA synthesis -> nuclear-cytoplasmic asynchrony (nucleus immature, cytoplasm mature). Causes: folate deficiency (poor diet, malabsorption, alcoholism, methotrexate) and B12 deficiency (pernicious anemia, gastrectomy, terminal ileum disease). Peripheral smear: oval macrocytes, hypersegmented PMNs. Bone marrow: megaloblastic changes." }
    if condition == "homocysteinemia" { return "Elevated plasma homocysteine. Mild (15-30 uM): MTHFR C677T TT, mild B6/B12/folate deficiency. Moderate (30-100 uM): more severe vitamin deficiency, renal insufficiency. Severe (>100 uM): classical homocystinuria (CBS deficiency). Cardiovascular risk increases ~1.6-fold per 5 uM increase. Treatment: folate + B12 + B6 supplementation (lowers Hcy but large RCTs have NOT shown CVD event reduction)." }
    if condition == "subacute_combined_degeneration" { return "Neurological manifestation of B12 deficiency. Demyelination of dorsal columns (loss of proprioception, vibration sense) and lateral corticospinal tracts (spasticity, weakness). Mechanism: impaired SAM-dependent methylation of myelin lipids. Can occur WITHOUT anemia. IRREVERSIBLE if treatment delayed. This is why giving folate alone to B12-deficient patients is dangerous: it masks the anemia while neurological damage progresses." }
    return ""
}

// ═══════════════════════════════════════════════════════
// SECTION VII: BRANCHED-CHAIN AMINO ACIDS (BCAAs)
// ═══════════════════════════════════════════════════════
//
// Leucine, isoleucine, and valine are the three BCAAs. They are
// unique among amino acids because they are catabolized primarily
// in MUSCLE (not liver). This is because BCAT (the first enzyme)
// is expressed primarily in muscle, while liver has very low BCAT.
//
// Two-step initial catabolism:
//   (a) BCAT: transamination (reversible, PLP-dependent)
//   (b) BCKDH: oxidative decarboxylation (irreversible, committed step)
//       BCKDH = branched-chain alpha-keto acid dehydrogenase complex
//       Analogous to pyruvate dehydrogenase and alpha-KG dehydrogenase
//       (same E3 subunit, requires TPP, lipoamide, CoA, FAD, NAD+)
//
// BCKDH deficiency = maple syrup urine disease (MSUD)
//
// Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23.

fn bcaa_metabolism(addr: Int) -> BCAAMetabolism {
    // Leucine: purely ketogenic
    if addr == 1 { return bcaa(1, "Leucine", "L", false, true, "alpha-Ketoisocaproate (KIC)", "Isovaleryl-CoA", "Acetyl-CoA + Acetoacetate", "Acetyl-CoA and Acetoacetate (purely ketogenic)", "Lehninger 8th ed, Ch 18") }

    // Isoleucine: both glucogenic and ketogenic
    if addr == 2 { return bcaa(2, "Isoleucine", "I", true, true, "alpha-Keto-beta-methylvalerate (KMV)", "alpha-Methylbutyryl-CoA", "Succinyl-CoA + Acetyl-CoA", "Succinyl-CoA (glucogenic) and Acetyl-CoA (ketogenic)", "Lehninger 8th ed, Ch 18") }

    // Valine: purely glucogenic
    if addr == 3 { return bcaa(3, "Valine", "V", true, false, "alpha-Ketoisovalerate (KIV)", "Isobutyryl-CoA", "Succinyl-CoA", "Succinyl-CoA (glucogenic, via methylmalonyl-CoA)", "Lehninger 8th ed, Ch 18") }

    return bcaa(0, "", "", false, false, "", "", "", "", "")
}

fn bcat_info() -> String {
    return "Branched-chain aminotransferase (BCAT). Two isoforms: BCAT1 (P54687, cytosolic, primarily in brain and muscle) and BCAT2 (O15382, mitochondrial, primarily in muscle and peripheral tissues). PLP-dependent. Transfers amino group from BCAA to alpha-ketoglutarate, producing the corresponding branched-chain alpha-keto acid (BCKA) and glutamate. Reversible. Muscle is the primary site of BCAA transamination because liver has very low BCAT expression. Lehninger 8th ed, Ch 18."
}

fn bckdh_info() -> String {
    return "Branched-chain alpha-keto acid dehydrogenase complex (BCKDH). E1 (P12694, BCKDHA, thiamine pyrophosphate-dependent, alpha subunit; P21953, BCKDHB, beta subunit), E2 (P11182, DBT, dihydrolipoamide branched-chain transacylase), E3 (P09622, DLD, shared with PDH and alpha-KGDH). Irreversible oxidative decarboxylation. THE committed step of BCAA catabolism. Regulated by phosphorylation: BCKDH kinase (P53004, BCKDK) inactivates, BCKDH phosphatase (PPM1K, Q8N461) activates. alpha-Ketoisocaproate (leucine's keto acid) inhibits the kinase -> activates BCKDH -> leucine promotes its own catabolism and that of the other two BCAAs. Lehninger 8th ed, Ch 18; Stryer 9th ed, Ch 23."
}

fn maple_syrup_urine_disease() -> String {
    return "Maple syrup urine disease (MSUD, OMIM 248600). Autosomal recessive. Deficiency of BCKDH complex (any of E1alpha, E1beta, E2, or E3 subunits). Incidence: ~1:185,000 (general) to ~1:176 (Mennonite communities due to E1alpha Y438N founder mutation). Branched-chain alpha-keto acids accumulate in blood, urine, and CSF. Urine has characteristic maple syrup/burnt sugar odor (due to sotolone). Classic form: presents 3-5 days after birth with poor feeding, lethargy, encephalopathy, maple syrup odor. Untreated: seizures, coma, death. Treatment: BCAA-restricted diet for life, monitoring plasma Leu (target 75-200 uM), acute crisis management with dextrose + insulin (anabolic, drives BCAAs into protein synthesis). Liver transplant is curative (provides functional BCKDH). Lehninger 8th ed, Ch 18."
}

// ═══════════════════════════════════════════════════════
// SECTION VIII: NITROGEN BALANCE
// ═══════════════════════════════════════════════════════
//
// Nitrogen balance = nitrogen intake (dietary protein) minus
// nitrogen output (urea, ammonia, creatinine, uric acid in urine;
// fecal nitrogen; integumental losses). It reflects the net
// balance between protein synthesis and degradation.
//
// Total body protein turnover: ~300 g/day in a 70 kg adult.
// Only ~30-50 g/day comes from diet; the rest is recycled from
// endogenous protein degradation (ubiquitin-proteasome, lysosomal).
//
// Lehninger 8th ed, Ch 18 and 23; Stryer 9th ed, Ch 23.

fn nitrogen_balance(condition: String) -> NitrogenBalance {
    if condition == "equilibrium" { return nbal("Healthy adult on adequate protein", "Zero (equilibrium)", "Intake = Output", "Protein synthesis rate equals protein degradation rate. All dietary amino acid nitrogen consumed is excreted as urea, NH4+, creatinine, uric acid. Steady-state body protein mass.", "Normal physiology. Requires ~0.8 g protein/kg/day (RDA) to maintain. Complete proteins (all essential AAs) needed.", "Lehninger 8th ed, Ch 18") }

    if condition == "positive_growth" { return nbal("Growth (children, adolescents)", "Positive", "Intake > Output", "Protein synthesis exceeds degradation. Net protein accretion into growing tissues (muscle, bone, organs). Growth hormone, IGF-1, insulin, testosterone promote anabolism. mTORC1 pathway activated by leucine and insulin.", "Normal growth. Higher protein requirements: 1.1 g/kg/day (children) to 1.5 g/kg/day (infants). Protein-energy malnutrition (kwashiorkor, marasmus) impairs growth.", "Lehninger 8th ed, Ch 18 and 23") }

    if condition == "positive_pregnancy" { return nbal("Pregnancy", "Positive", "Intake > Output", "Protein accretion for fetal growth (~500 g protein deposited), placental growth, uterine expansion, increased blood volume (plasma proteins, hemoglobin), mammary development. Progesterone promotes anabolism.", "Protein requirement increases to ~1.1 g/kg/day. Inadequate protein intake associated with low birth weight, preeclampsia.", "Lehninger 8th ed, Ch 18") }

    if condition == "positive_recovery" { return nbal("Recovery/convalescence", "Positive", "Intake > Output", "Repletion of protein lost during illness/injury. Anabolic hormones (insulin, GH, testosterone) drive protein synthesis. Adequate protein and energy intake required for recovery.", "Post-surgical, post-infection recovery. Protein needs may reach 1.5-2.0 g/kg/day.", "Lehninger 8th ed, Ch 18") }

    if condition == "negative_starvation" { return nbal("Starvation/fasting", "Negative", "Intake < Output", "After glycogen depletion (12-24h), gluconeogenesis from amino acids (primarily alanine, glutamine) provides glucose for brain. Muscle protein is the amino acid source. Cortisol drives proteolysis. Urea excretion increases initially, then decreases as brain adapts to ketone bodies (after ~3 days), sparing muscle protein.", "Starvation adaptation: brain switches from glucose to ketones (beta-hydroxybutyrate, acetoacetate) after 3-5 days, reducing amino acid catabolism from ~75 g/day to ~20 g/day. Extends survival from weeks to months.", "Lehninger 8th ed, Ch 18 and 23") }

    if condition == "negative_trauma" { return nbal("Trauma/surgery/burns", "Negative", "Intake < Output", "Hypermetabolic response. Cortisol, catecholamines, glucagon drive massive proteolysis. Amino acids diverted to acute phase protein synthesis (CRP, fibrinogen, ferritin by liver), gluconeogenesis, and immune cell fuel (glutamine). Muscle wasting can exceed 300 g/day in severe burns.", "Burns: protein needs may reach 2.5-3.0 g/kg/day. ICU patients lose ~1 kg lean mass/day without nutritional support. Early enteral nutrition reduces catabolism.", "Lehninger 8th ed, Ch 18 and 23") }

    if condition == "negative_sepsis" { return nbal("Sepsis/infection", "Negative", "Intake < Output", "Cytokine-driven (IL-1, IL-6, TNF-alpha) catabolism. Hepatic reprioritization: albumin synthesis decreases, acute phase proteins increase. Skeletal muscle proteolysis provides amino acids (glutamine for immune cells, alanine for gluconeogenesis). Negative balance persists despite adequate nutrition (anabolic resistance).", "Sepsis-induced myopathy and ICU-acquired weakness. Glutamine supplementation controversial (REDOXS trial showed harm in multi-organ failure). Protein target: 1.2-2.0 g/kg/day.", "Lehninger 8th ed, Ch 23") }

    if condition == "negative_cancer" { return nbal("Cancer cachexia", "Negative", "Intake << Output", "Tumor-derived factors (PIF, LMF) and systemic inflammation (IL-6, TNF-alpha) drive muscle wasting AND adipose wasting. Not reversed by nutritional support alone (distinguishes cachexia from starvation). Proteasome-ubiquitin pathway upregulated. Affects ~50-80% of advanced cancer patients.", "Cachexia causes ~20% of cancer deaths. No effective pharmacotherapy (anamorelin, megestrol partial benefit). Exercise + multimodal nutrition may slow progression.", "Lehninger 8th ed, Ch 23") }

    return nbal("", "", "", "", "", "")
}

fn protein_turnover_rate() -> String {
    return "Total body protein turnover in a 70 kg adult: ~300 g/day (1.2-2.0% of total body protein per day). Most amino acids from degraded proteins are reutilized for new protein synthesis (~80% recycled). Remaining ~20% are oxidized for energy or converted to glucose/ketones. Half-lives vary enormously: ornithine decarboxylase ~11 min, HMG-CoA reductase ~2-4 hours, hemoglobin ~120 days (RBC lifespan), lens crystallins: lifetime. Ubiquitin-proteasome system handles ~80% of intracellular protein degradation (26S proteasome, ATP-dependent). Autophagy-lysosome handles bulk degradation (starvation, organelle turnover). Lehninger 8th ed, Ch 23."
}

fn protein_quality(source: String) -> String {
    if source == "complete" { return "Contains all 9 essential amino acids in adequate proportions. Animal proteins (egg, milk, meat, fish) are generally complete. Egg protein has PDCAAS (Protein Digestibility Corrected Amino Acid Score) of 1.0 (reference standard). Whey protein: 1.0. Casein: 1.0. Beef: 0.92." }
    if source == "incomplete" { return "Deficient in one or more essential amino acids (limiting amino acids). Most plant proteins are incomplete. Cereals: low in lysine. Legumes: low in methionine. Complementary proteins: combining cereals + legumes provides all essential AAs (rice + beans, corn + beans)." }
    if source == "limiting_amino_acid" { return "The essential amino acid present in the lowest proportion relative to requirement. Cereals: lysine (first limiting), threonine (second). Legumes: methionine (first limiting), tryptophan (second). Corn: lysine + tryptophan (pellagra in corn-dependent populations). Gelatin: tryptophan (zero content)." }
    return ""
}

// ═══════════════════════════════════════════════════════
// COUNT FUNCTIONS
// ═══════════════════════════════════════════════════════

fn aminotransferase_count() -> Int {
    return 5
}

fn urea_cycle_step_count() -> Int {
    return 5
}

fn oxidative_deamination_count() -> Int {
    return 3
}

fn amino_acid_catabolic_fate_count() -> Int {
    return 20
}

fn specialized_pathway_count() -> Int {
    return 10
}

fn one_carbon_component_count() -> Int {
    return 10
}

fn bcaa_count() -> Int {
    return 3
}

fn nitrogen_balance_condition_count() -> Int {
    return 8
}
