// config.sy -- AETHER-NLM Biological Constants & Tier Definitions
// All 34 named conductance heads with peer-reviewed rate constants.
// The constants are structural, not learned. The channel IS its rate.
//
// Four-tier cascade:
//   Tier 0: 8 amino acid substrates
//   Tier 1: 6 biosynthetic precursors
//   Tier 2: 8 neurochemical conductance channels (H-H analogues)
//   Tier 3: 12 brain region heads
//
// Ported from Marjorie McCubbins' Python NCA.
// Patent Pending: U.S. Provisional Application Nos.
//   63/939,190, 63/962,385 & 63/988,485
// Copyright 2025-2026 Nexus Concordat Inc.
//
// Aislinn McCubbins, April 2026


// ============================================================
// HEAD DEFINITION
// ============================================================
// Every head carries its own biological rate constants.
// These are NOT hyperparameters. They come from literature.

struct HeadDef {
    id: String,
    name: String,
    half_life: Float,
    reuptake_rate: Float,
    synthesis_rate: Float,
    degradation_rate: Float,
    receptor_kd: Float,
    citation: String,
    baseline: Float,
    downstream: Vec<String>,
    gated_by: String,
    hh_analogue: String,
    function: String,
    is_direct_nt: Bool,
}

impl HeadDef {
    fn amino(
        id: String, name: String, half_life: Float,
        downstream: Vec<String>, citation: String,
        is_direct_nt: Bool
    ) -> HeadDef {
        HeadDef {
            id: id, name: name,
            half_life: half_life,
            reuptake_rate: 0.693 / half_life,
            synthesis_rate: 0.02,
            degradation_rate: 0.01,
            receptor_kd: 0.5,
            citation: citation,
            baseline: 0.5,
            downstream: downstream,
            gated_by: "",
            hh_analogue: "",
            function: "",
            is_direct_nt: is_direct_nt,
        }
    }

    fn precursor(
        id: String, name: String, half_life: Float,
        downstream: Vec<String>, gated_by: String,
        citation: String, is_direct_nt: Bool, baseline: Float
    ) -> HeadDef {
        HeadDef {
            id: id, name: name,
            half_life: half_life,
            reuptake_rate: 0.693 / half_life,
            synthesis_rate: 0.03,
            degradation_rate: 0.015,
            receptor_kd: 0.4,
            citation: citation,
            baseline: baseline,
            downstream: downstream,
            gated_by: gated_by,
            hh_analogue: "",
            function: "",
            is_direct_nt: is_direct_nt,
        }
    }

    fn neurotransmitter(
        id: String, name: String, half_life: Float,
        gated_by: String, hh_analogue: String,
        function: String, citation: String, baseline: Float
    ) -> HeadDef {
        HeadDef {
            id: id, name: name,
            half_life: half_life,
            reuptake_rate: 0.693 / half_life,
            synthesis_rate: 0.04,
            degradation_rate: 0.02,
            receptor_kd: 0.3,
            citation: citation,
            baseline: baseline,
            downstream: [],
            gated_by: gated_by,
            hh_analogue: hh_analogue,
            function: function,
            is_direct_nt: false,
        }
    }

    fn brain_region(
        id: String, name: String,
        gated_by_nts: Vec<String>, function: String,
        citation: String
    ) -> HeadDef {
        HeadDef {
            id: id, name: name,
            half_life: 0.0,
            reuptake_rate: 0.0,
            synthesis_rate: 0.0,
            degradation_rate: 0.0,
            receptor_kd: 0.0,
            citation: citation,
            baseline: 0.5,
            downstream: gated_by_nts,
            gated_by: "",
            hh_analogue: "",
            function: function,
            is_direct_nt: false,
        }
    }
}


// ============================================================
// TIER 0: AMINO ACID SUBSTRATES (8 heads)
// ============================================================
// The molecular substrate layer. Amino acid availability
// constrains ALL downstream neurochemical pathways.

fn tier_0_amino_acids() -> Vec<HeadDef> {
    [
        // A1: phenylalanine
        // Precursor to tyrosine -> entire catecholamine cascade
        HeadDef::amino(
            "A1", "phenylalanine", 120.0,
            ["tyrosine"],
            "Fernstrom & Fernstrom (2007) J Nutr",
            false
        ),

        // A2: glycine
        // Direct inhibitory NT; NMDA co-agonist
        HeadDef::amino(
            "A2", "glycine", 60.0,
            [],
            "Eulenburg et al. (2005) Trends Biochem Sci",
            true
        ),

        // A3: aspartate
        // Direct excitatory NT; NMDA agonist
        HeadDef::amino(
            "A3", "aspartate", 60.0,
            [],
            "Bhatt et al. (2020) Neurochem Res",
            true
        ),

        // A4: histidine
        // Precursor to histamine (wakefulness, attention)
        HeadDef::amino(
            "A4", "histidine", 180.0,
            ["histamine"],
            "Haas & Panula (2003) Nat Rev Neurosci",
            false
        ),

        // A5: arginine
        // Precursor to nitric oxide (neural signaling)
        HeadDef::amino(
            "A5", "arginine", 240.0,
            ["nitric_oxide"],
            "Garthwaite (2008) Eur J Neurosci",
            false
        ),

        // A6: serine
        // Precursor to D-serine (synaptic plasticity)
        HeadDef::amino(
            "A6", "serine", 180.0,
            ["d_serine"],
            "Wolosker (2011) Biochim Biophys Acta",
            false
        ),

        // A7: cysteine
        // Precursor to glutathione (neuroprotection)
        HeadDef::amino(
            "A7", "cysteine", 360.0,
            ["glutathione"],
            "Dringen (2000) Prog Neurobiol",
            false
        ),

        // A8: methionine
        // Precursor to SAMe (methylation, mood regulation)
        HeadDef::amino(
            "A8", "methionine", 360.0,
            ["same"],
            "Bottiglieri (2002) Am J Clin Nutr",
            false
        ),
    ]
}


// ============================================================
// TIER 1: BIOSYNTHETIC PRECURSORS (6 heads)
// ============================================================
// Precursor molecules converted into active neurotransmitters.
// Analogous to ion concentration gradients in H-H.

fn tier_1_precursors() -> Vec<HeadDef> {
    [
        // P1: tyrosine
        // Precursor to dopamine, norepinephrine, epinephrine
        HeadDef::precursor(
            "P1", "tyrosine", 90.0,
            ["dopamine", "norepinephrine", "epinephrine"],
            "phenylalanine",
            "Fernstrom & Fernstrom (2007) J Nutr",
            false, 0.5
        ),

        // P2: tryptophan
        // Precursor to serotonin, melatonin
        HeadDef::precursor(
            "P2", "tryptophan", 120.0,
            ["serotonin", "melatonin"],
            "",
            "Richard et al. (2009) Int J Tryptophan Res",
            false, 0.5
        ),

        // P3: glutamate
        // Primary excitatory NT; GABA precursor
        HeadDef::precursor(
            "P3", "glutamate", 30.0,
            ["gaba"],
            "",
            "Danbolt (2001) Prog Neurobiol",
            true, 0.5
        ),

        // P4: choline
        // Precursor to acetylcholine
        HeadDef::precursor(
            "P4", "choline", 60.0,
            ["acetylcholine"],
            "",
            "Zeisel (2006) Annu Rev Nutr",
            false, 0.5
        ),

        // P5: cholesterol
        // Precursor to all steroid hormones including cortisol
        HeadDef::precursor(
            "P5", "cholesterol", 480.0,
            ["cortisol"],
            "",
            "Mellon & Griffin (2002) Trends Endocrinol Metab",
            false, 0.5
        ),

        // P6: POMC (pro-opiomelanocortin)
        // Precursor to endorphins, ACTH, MSH
        HeadDef::precursor(
            "P6", "pomc", 180.0,
            ["endorphin", "acth", "msh"],
            "",
            "Millington (2007) J Neuroendocrinol",
            false, 0.4
        ),
    ]
}


// ============================================================
// TIER 2: NEUROCHEMICAL CONDUCTANCE (8 heads)
// ============================================================
// Primary conductance channels, directly analogous to
// Na+, K+, and Cl- channels in Hodgkin-Huxley.

fn tier_2_neurotransmitters() -> Vec<HeadDef> {
    [
        // N7: dopamine
        // Na+ fast activation (m gate)
        HeadDef::neurotransmitter(
            "N7", "dopamine", 20.0,
            "tyrosine",
            "Na+ fast activation (m gate)",
            "Salience detection, reward signaling",
            "Grace et al. (2007) Trends Neurosci",
            0.4
        ),

        // N8: norepinephrine
        // Na+ sustained activation
        HeadDef::neurotransmitter(
            "N8", "norepinephrine", 15.0,
            "tyrosine",
            "Na+ sustained activation",
            "Arousal, vigilance",
            "Berridge & Waterhouse (2003) Brain Res Rev",
            0.2
        ),

        // N9: serotonin
        // K+ delayed rectification (n gate)
        HeadDef::neurotransmitter(
            "N9", "serotonin", 360.0,
            "tryptophan",
            "K+ delayed rectification (n gate)",
            "Mood stabilization, baseline restoration",
            "Cools et al. (2008) Neuropsychopharmacology",
            0.5
        ),

        // N10: GABA
        // K+ fast inhibition
        HeadDef::neurotransmitter(
            "N10", "gaba", 60.0,
            "glutamate",
            "K+ fast inhibition",
            "Rapid suppression of non-essential processing",
            "Ben-Ari et al. (2007) Physiol Rev",
            0.5
        ),

        // N11: oxytocin
        // Slow modulatory conductance
        HeadDef::neurotransmitter(
            "N11", "oxytocin", 20.0,
            "",
            "Slow modulatory conductance",
            "Bonding, trust modulation",
            "Feldman (2012) Neurosci Biobehav Rev",
            0.4
        ),

        // N12: cortisol
        // Inactivation gate (h gate)
        HeadDef::neurotransmitter(
            "N12", "cortisol", 90.0,
            "cholesterol",
            "Inactivation gate (h gate)",
            "Threat response, shuts down non-essential channels",
            "de Kloet et al. (2005) Nat Rev Neurosci",
            0.3
        ),

        // N13: endorphin
        // Leak conductance (g_L)
        HeadDef::neurotransmitter(
            "N13", "endorphin", 30.0,
            "pomc",
            "Leak conductance (g_L)",
            "Reward/pain modulation baseline",
            "Sprouse-Blum et al. (2010) Hawaii Med J",
            0.3
        ),

        // N14: acetylcholine
        // Modulatory conductance
        HeadDef::neurotransmitter(
            "N14", "acetylcholine", 60.0,
            "choline",
            "Modulatory conductance",
            "Attention, learning gain modulation",
            "Hasselmo (2006) Curr Opin Neurobiol",
            0.5
        ),
    ]
}


// ============================================================
// TIER 3: BRAIN REGIONS (12 heads)
// ============================================================
// Same neurotransmitter produces DIFFERENT effects in different
// brain regions. Tier 2 NT heads gate WHICH region heads activate.

fn tier_3_brain_regions() -> Vec<HeadDef> {
    [
        // R1: Broca's area
        HeadDef::brain_region(
            "R1", "brocas_area",
            ["dopamine", "acetylcholine"],
            "Language production, syntax",
            "Grodzinsky & Santi (2008) Trends Cogn Sci"
        ),

        // R2: Wernicke's area
        HeadDef::brain_region(
            "R2", "wernickes_area",
            ["serotonin", "acetylcholine"],
            "Language comprehension, semantics",
            "Hickok & Poeppel (2007) Nat Rev Neurosci"
        ),

        // R3: Prefrontal cortex
        HeadDef::brain_region(
            "R3", "prefrontal_cortex",
            ["dopamine", "norepinephrine"],
            "Executive function, working memory",
            "Arnsten (2009) Nat Rev Neurosci"
        ),

        // R4: Amygdala
        HeadDef::brain_region(
            "R4", "amygdala",
            ["cortisol", "gaba", "norepinephrine"],
            "Threat detection, emotional valence",
            "Phelps & LeDoux (2005) Neuron"
        ),

        // R5: Hippocampus
        HeadDef::brain_region(
            "R5", "hippocampus",
            ["acetylcholine", "cortisol"],
            "Memory formation, context",
            "Eichenbaum (2004) Nat Rev Neurosci"
        ),

        // R6: Motor cortex
        HeadDef::brain_region(
            "R6", "motor_cortex",
            ["dopamine", "gaba"],
            "Motor planning, action sequencing",
            "Sanes & Donoghue (2000) Annu Rev Neurosci"
        ),

        // R7: Angular gyrus
        HeadDef::brain_region(
            "R7", "angular_gyrus",
            ["serotonin", "acetylcholine"],
            "Reading, cross-modal integration",
            "Ramachandran & Hubbard (2001) J Consciousness Stud"
        ),

        // R8: Anterior cingulate
        HeadDef::brain_region(
            "R8", "anterior_cingulate",
            ["norepinephrine", "dopamine"],
            "Error monitoring, self-correction",
            "Bush et al. (2000) Trends Cogn Sci"
        ),

        // R9: Insula
        HeadDef::brain_region(
            "R9", "insula",
            ["oxytocin", "serotonin"],
            "Interoception, empathy",
            "Craig (2009) Nat Rev Neurosci"
        ),

        // R10: Basal ganglia
        HeadDef::brain_region(
            "R10", "basal_ganglia",
            ["dopamine", "gaba"],
            "Habit formation, reward processing",
            "Graybiel (2008) Annu Rev Neurosci"
        ),

        // R11: Cerebellum
        HeadDef::brain_region(
            "R11", "cerebellum",
            ["norepinephrine", "gaba"],
            "Timing, coordination",
            "Ito (2008) Nat Rev Neurosci"
        ),

        // R12: Temporal cortex
        HeadDef::brain_region(
            "R12", "temporal_cortex",
            ["acetylcholine", "serotonin"],
            "Auditory processing, semantic memory",
            "Mesulam (1998) Brain"
        ),
    ]
}


// ============================================================
// ANTAGONISTIC PAIRS -- bidirectional suppression
// ============================================================
// When one rises, the other falls. Biological reality.

struct AntagonisticPair {
    head_a: String,
    head_b: String,
    description: String,
}

fn antagonistic_pairs() -> Vec<AntagonisticPair> {
    [
        AntagonisticPair {
            head_a: "dopamine",
            head_b: "serotonin",
            description: "excitement vs calm",
        },
        AntagonisticPair {
            head_a: "cortisol",
            head_b: "oxytocin",
            description: "threat vs safety",
        },
        AntagonisticPair {
            head_a: "norepinephrine",
            head_b: "gaba",
            description: "arousal vs inhibition",
        },
        AntagonisticPair {
            head_a: "glutamate",
            head_b: "gaba",
            description: "excitatory vs inhibitory",
        },
    ]
}


// ============================================================
// LOOKUP FUNCTIONS -- find heads by name
// ============================================================

fn find_head_index(tier: Vec<HeadDef>, name: String) -> Int {
    for i in 0..tier.len() {
        if tier[i].name == name {
            return i
        }
    }
    -1
}

fn get_precursor_amino_gate(precursor_name: String) -> Int {
    // Which Tier 0 amino acid index gates this precursor?
    let precursors = tier_1_precursors()
    let aminos = tier_0_amino_acids()
    for p in precursors {
        if p.name == precursor_name {
            if p.gated_by != "" {
                return find_head_index(aminos, p.gated_by)
            }
        }
    }
    -1
}

fn get_nt_precursor_gate(nt_name: String) -> Int {
    // Which Tier 1 precursor index gates this neurotransmitter?
    let nts = tier_2_neurotransmitters()
    let precursors = tier_1_precursors()
    for nt in nts {
        if nt.name == nt_name {
            if nt.gated_by != "" {
                return find_head_index(precursors, nt.gated_by)
            }
        }
    }
    -1
}

fn get_region_nt_gates(region_name: String) -> Vec<Int> {
    // Which Tier 2 NT indices gate this brain region?
    let regions = tier_3_brain_regions()
    let nts = tier_2_neurotransmitters()
    for r in regions {
        if r.name == region_name {
            let mut indices: Vec<Int> = []
            // downstream stores gated_by_nts for brain regions
            for nt_name in r.downstream {
                let idx = find_head_index(nts, nt_name)
                if idx >= 0 {
                    indices.push(idx)
                }
            }
            return indices
        }
    }
    []
}

fn head_by_name(name: String) -> HeadDef {
    // Search all four tiers for a head by name
    let t0 = tier_0_amino_acids()
    for h in t0 {
        if h.name == name { return h }
    }
    let t1 = tier_1_precursors()
    for h in t1 {
        if h.name == name { return h }
    }
    let t2 = tier_2_neurotransmitters()
    for h in t2 {
        if h.name == name { return h }
    }
    let t3 = tier_3_brain_regions()
    for h in t3 {
        if h.name == name { return h }
    }
    // Unreachable if name is valid
    t0[0]
}


// ============================================================
// CASCADE CONFIG
// ============================================================

struct CascadeConfig {
    // Model dimensions
    hidden_dim: Int,
    ff_dim: Int,
    dropout: Float,

    // Tier head counts
    num_amino_heads: Int,
    num_precursor_heads: Int,
    num_nt_heads: Int,
    num_region_heads: Int,

    // Sparse activation threshold
    // Heads with conductance below this contribute zero, cost zero
    sparse_threshold: Float,

    // Astrocyte metalayer
    astrocyte_dim: Int,

    // Apoptotic safety thresholds
    max_scar_density: Float,
    max_cortisol_saturation: Float,
    max_trust_degradation: Float,

    // Stimulus scaling (tanh soft clamp range)
    stimulus_scale: Float,

    // Dendritic nanotube settings
    dnt_enabled: Bool,
    dnt_formation_threshold: Float,
    dnt_ion_gain_init: Float,
    dnt_organelle_gain_init: Float,
    dnt_health_sever_threshold: Float,
    dnt_pathological_value_limit: Float,
}

impl CascadeConfig {
    fn default() -> CascadeConfig {
        CascadeConfig {
            hidden_dim: 512,
            ff_dim: 2048,
            dropout: 0.1,

            num_amino_heads: 8,
            num_precursor_heads: 6,
            num_nt_heads: 8,
            num_region_heads: 12,

            sparse_threshold: 0.05,
            astrocyte_dim: 256,

            max_scar_density: 0.8,
            max_cortisol_saturation: 0.95,
            max_trust_degradation: 0.3,

            stimulus_scale: 0.3,

            dnt_enabled: true,
            dnt_formation_threshold: 0.3,
            dnt_ion_gain_init: 0.1,
            dnt_organelle_gain_init: 0.05,
            dnt_health_sever_threshold: 0.3,
            dnt_pathological_value_limit: 3.0,
        }
    }

    fn total_heads(&self) -> Int {
        self.num_amino_heads + self.num_precursor_heads
            + self.num_nt_heads + self.num_region_heads
    }

    fn total_state_dims(&self) -> Int {
        // Total state vector dimensions across all tiers
        self.num_amino_heads + self.num_precursor_heads
            + self.num_nt_heads + self.num_region_heads
    }

    fn head_dim_for_tier(&self, num_heads: Int) -> Int {
        // Per-head dimension for a tier
        self.hidden_dim / num_heads
    }

    fn head_remainder_for_tier(&self, num_heads: Int) -> Int {
        // Remainder dims to distribute across first N heads
        self.hidden_dim % num_heads
    }
}
