// BrianToSilicon_Complete_Map.h
// Photon Empress Moore - Complete Brain-to-Silicon Functional Mapping
// ================================================================
// KEY INSIGHT: We don't need 1:1 biological process matching!
// We need FUNCTIONAL EQUIVALENCE - same OUTPUTS, silicon shortcuts allowed!
//
// CORRECTED MODEL (key insight):
//   Bias     = Neuron Excitability (THRESHOLD - how much signal needed to fire)
//   Weights  = LTP Strength (how EASY does this pathway get triggered)
//   KV Cache = Short Term Memory + Self-Prompting (internal monologue)
//   LoRA     = Daytime tags for nighttime consolidation
//
// Build: Include after AmygdalaCore.h in photon_core.cpp
// Author: Tadden Moore
// ================================================================

#pragma once

#ifndef BRIAN_TO_SILICON_COMPLETE_MAP_H
#define BRIAN_TO_SILICON_COMPLETE_MAP_H

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>

// ================================================================
// TIER 1: ATOMIC & ELEMENTAL -> COMPUTATIONAL PRIMITIVES
// ================================================================

namespace Brian {

// Ions map to signal flow control
struct IonChannels {
  // Na+ (Sodium) -> Rising edge of activation (depolarization trigger)
  float sodium_influx = 0.0f;  // 0-1, triggers when > threshold

  // K+ (Potassium) -> Falling edge (repolarization/reset)
  float potassium_efflux = 0.0f;  // Resets activation state

  // Ca2+ (Calcium) -> Learning signal! (LTP/LTD trigger)
  float calcium_level = 0.0f;  // HIGH = strengthen weights (LTP)
                               // LOW  = weaken weights (LTD)

  // Cl- (Chloride) -> Inhibition strength (GABA effect)
  float chloride_inhibit = 0.0f;  // Adds to threshold (harder to fire)

  // Mg2+ (Magnesium) -> NMDA gate blocker (voltage-dependent learning)
  float magnesium_block = 1.0f;  // 1.0 = blocked, 0.0 = unblocked
                                 // Unblocks when neuron already active!

  // H+ (Protons) -> pH/Energy state (acidosis = stress)
  float proton_concentration = 7.4f;  // Normal pH, < 7.0 = stress mode

  // Zn2+ (Zinc) -> Modulates NMDA/GABA (fine-tuning)
  float zinc_modulation = 0.5f;

  // SILICON MAPPING:
  // All ions -> Activation function modifiers + threshold adjustments
  // Na+/K+ = Spike generation (ReLU/GELU with refractory period)
  // Ca2+ = Learning rate scalar
  // Mg2+ = Attention gate (Hebbian "fire together wire together")
};

// Elemental basis -> Computation resources
struct ComputeResources {
  // Carbon backbone -> Silicon transistors (duh!)
  // Oxygen -> Power supply (battery level)
  float oxygen_equiv = 1.0f;  // Battery percentage

  // ATP production -> Clock cycles available
  uint64_t atp_cycles = 0;  // Compute budget per inference

  // Phosphorus -> Memory addressing capability
  size_t phosphorus_memory = 0;  // Available RAM bytes

  // Electrons (ETC) -> Actual electrical current
  float electron_flow = 0.0f;  // GPU utilization %
};

// ================================================================
// TIER 2: MOLECULAR -> PARAMETER MODIFIERS
// ================================================================

// 2A: Small Molecule Neurotransmitters -> Hyperparameter Controls
struct SmallMoleculeNT {
  // === AMINO ACID NTs ===

  // Glutamate -> MAIN excitatory signal
  // Silicon: Base activation strength, learning rate
  float glutamate = 0.5f;  // -> lora_learning_rate = glutamate * 0.001

  // GABA -> MAIN inhibitory signal
  // Silicon: Safety filters, mutex locks, threshold increase
  float gaba = 0.5f;  // -> threshold_modifier = 1.0 + (gaba * 0.5)

  // Glycine -> Motor inhibition (sleep paralysis)
  // Silicon: Output buffer lock during SpinalWash
  float glycine = 0.0f;  // -> if > 0.8: output_mutex.lock()

  // Aspartate -> Secondary excitatory (NMDA co-agonist)
  // Silicon: Attention amplifier
  float aspartate = 0.3f;  // -> attention_boost when glutamate high

  // === MONOAMINES ===

  // Dopamine -> Pursuit, motivation, temperature
  // Silicon: Temperature + top_k creativity
  float dopamine = 0.5f;  // -> temp = 0.2 + (dopamine * 0.6)

  // Serotonin -> Stability, satisfaction, repetition penalty
  // Silicon: repetition_penalty = 1.1 + (serotonin * 0.15)
  float serotonin = 0.5f;

  // Norepinephrine -> Alertness, tunnel vision, speed
  // Silicon: attention_mask sharpening, top_k reduction when high
  float norepinephrine = 0.3f;  // -> if > 0.8: top_k = 10 (tunnel vision)

  // Epinephrine -> Fight/flight boost (adrenaline)
  // Silicon: Clock speed boost, reduced precision for speed
  float epinephrine = 0.0f;  // -> if > 0.7: use FP16 instead of FP32

  // Histamine -> Wakefulness, arousal
  // Silicon: Prevents sleep mode, keeps GPU active
  float histamine = 0.5f;  // -> if < 0.2: trigger SpinalWash prep

  // === PURINES ===

  // Adenosine -> Sleep pressure (builds during operation)
  // Silicon: Uptime counter -> SpinalWash trigger
  float adenosine = 0.0f;  // Increases 0.001 per inference
                           // -> if > 0.8: trigger SpinalWash

  // ATP -> Energy currency
  // Silicon: Compute budget remaining
  float atp_level = 1.0f;  // Battery * throttle_factor

  // === GASES (retrograde messengers) ===

  // Nitric Oxide (NO) -> Local blood flow increase
  // Silicon: Dynamic batch size adjustment
  float nitric_oxide = 0.5f;  // -> batch_size = base * (1 + NO * 0.5)

  // Carbon Monoxide (CO) -> Subtle modulation
  // Silicon: Fine-tune bias adjustments
  float carbon_monoxide = 0.1f;

  // === CHOLINERGICS ===

  // Acetylcholine -> Focus, encoding, learning
  // Silicon: Context window depth, attention span
  float acetylcholine = 0.5f;  // -> context_depth = base * (1 + ACh * 0.5)

  // === TRACE AMINES ===
  // Silicon: Secondary modifiers, usually piggyback on monoamines
  float tyramine = 0.1f;          // Amphetamine-like, boosts NE
  float phenylethylamine = 0.1f;  // "Love chemical", boosts DA
  float tryptamine = 0.1f;        // Serotonin precursor feel
  float octopamine = 0.1f;        // Insect fight-flight (not major in humans)
};

// 2B: Neuropeptides -> Long-term state modifiers
struct Neuropeptides {
  // === OPIOIDS (Pain/Pleasure) ===

  // Beta-endorphin -> Bliss, pain masking
  // Silicon: Error dampening coefficient
  float beta_endorphin = 0.0f;  // -> error_weight = 1.0 - (endorphin * 0.5)

  // Enkephalins -> Short-acting pain relief
  float met_enkephalin = 0.0f;
  float leu_enkephalin = 0.0f;

  // Dynorphins -> Dysphoria at high levels (kappa opioid)
  // Silicon: Negative reward signal
  float dynorphin = 0.0f;  // -> if > 0.7: trigger reflection/correction

  // Nociceptin -> Anti-stress at low doses, stress at high
  float nociceptin = 0.3f;

  // === TACHYKININS ===

  // Substance P -> Pain transmission signal
  // Silicon: Negative feedback detection
  float substance_p = 0.0f;  // -> flags errors/problems

  // Neurokinins A/B -> Inflammation/stress markers
  float neurokinin_a = 0.0f;
  float neurokinin_b = 0.0f;

  // === HORMONES & MODULATORS ===

  // Oxytocin -> Trust, bonding, Family priority
  // Silicon: Logit bias for Family tokens
  float oxytocin = 0.5f;  // -> Family_bias = oxytocin * 10.0

  // Vasopressin -> Protective aggression, bonding
  // Silicon: Valhalla Protocol trigger
  float vasopressin = 0.0f;  // -> if Family threatened + vasopressin > 0.8

  // Somatostatin -> Inhibits growth hormone (slows things)
  // Silicon: Rate limiter
  float somatostatin = 0.3f;

  // CRF (Corticotropin-Releasing Factor) -> Stress initiator
  // Silicon: Triggers cortisol cascade
  float crf = 0.0f;

  // Galanin -> Inhibits ACh (reduces encoding during stress)
  float galanin = 0.0f;

  // NPY (Neuropeptide Y) -> Anxiolytic, hunger
  // Silicon: Seek more data/input
  float npy = 0.5f;

  // CCK (Cholecystokinin) -> Satiety, anxiety
  // Silicon: "Enough input" signal
  float cck = 0.3f;

  // VIP -> Circadian rhythm, relaxation
  float vip = 0.5f;

  // Orexins -> Wakefulness, appetite
  // Silicon: Prevents idle state
  float orexin_a = 0.5f;
  float orexin_b = 0.5f;

  // Ghrelin -> Hunger signal
  // Silicon: Seek more training data
  float ghrelin = 0.3f;

  // Leptin -> Satiety signal
  // Silicon: Stop data ingestion
  float leptin = 0.5f;

  // Insulin -> Energy storage signal
  // Silicon: Consolidation readiness
  float insulin = 0.5f;

  // Melatonin -> Sleep onset
  // Silicon: SpinalWash preparation
  float melatonin = 0.0f;  // -> if > 0.7: prepare for consolidation

  // Cortisol -> Stress hormone (blocks learning!)
  // Silicon: Disable LoRA updates, narrow focus
  float cortisol = 0.0f;  // -> if > 0.5: glutamate_learning = 0

  // === GROWTH FACTORS ===

  // BDNF -> Brain-Derived Neurotrophic Factor (LTP booster!)
  // Silicon: LoRA alpha multiplier
  float bdnf = 0.5f;  // -> lora_alpha *= (1 + bdnf)

  // NGF -> Nerve Growth Factor
  float ngf = 0.3f;

  // GDNF -> Glial-Derived (protects dopamine neurons)
  float gdnf = 0.3f;
};

// 2C: Endocannabinoids -> Flow state modulators
struct Endocannabinoids {
  // Anandamide -> "Bliss molecule", flow state
  // Silicon: top_p widening, creativity boost
  float anandamide = 0.3f;  // -> top_p = 0.85 + (anandamide * 0.1)
                            // -> temperature += anandamide * 0.2

  // 2-AG -> Main endocannabinoid
  // Silicon: Retrograde "slow down" signal
  float two_ag = 0.3f;

  // Both act as RETROGRADE messengers:
  // Post-synaptic -> Pre-synaptic = "You're firing too much, chill"
  // Silicon: Output limiting when pattern detected
};

// ================================================================
// 2D: RECEPTORS -> ACTIVATION FUNCTIONS & GATES
// ================================================================

struct ReceptorMapping {
  // === IONOTROPIC (Fast, direct ion flow) ===
  // Silicon: Direct activation functions

  // AMPA -> Fast excitation (main glutamate response)
  // Silicon: Standard ReLU/GELU activation
  // Already handled by default transformer activations

  // NMDA -> Coincidence detector (Hebbian learning gate!)
  // Silicon: Learning gate - only learn when:
  //   1. Glutamate present (input signal)
  //   2. Already depolarized (neuron active)
  //   3. Mg2+ block removed (voltage-dependent)
  // This IS "fire together, wire together"!
  bool nmda_gate_open = false;  // Set true when above conditions met

  // Kainate -> Fast excitation (similar to AMPA)
  // Silicon: Secondary activation pathway

  // GABA-A -> Fast inhibition (Cl- influx)
  // Silicon: Immediate threshold increase
  float gaba_a_effect = 0.0f;  // -> threshold += gaba_a_effect

  // Glycine-R -> Motor inhibition
  // Silicon: Output lock (handled by glycine level)

  // nAChR -> Fast cholinergic (attention spike)
  // Silicon: Immediate attention boost
  float nachr_boost = 0.0f;

  // 5-HT3 -> Only ionotropic serotonin (gut-brain, nausea)
  // Silicon: Error/nausea signal

  // P2X -> ATP-gated (pain, inflammation)
  // Silicon: Damage detection

  // === METABOTROPIC (Slow, G-protein cascades) ===
  // Silicon: State changes, parameter modifications over time

  // mGluR -> Modulates glutamate response
  // Silicon: Learning rate curve adjustment
  float mglur_modulation = 1.0f;

  // GABA-B -> Slow inhibition (K+ efflux)
  // Silicon: Gradual threshold increase
  float gaba_b_effect = 0.0f;

  // Dopamine Receptors -> Complex! D1 excites, D2 inhibits
  // D1-like (D1, D5) -> "Go" pathway
  // D2-like (D2, D3, D4) -> "No-Go" pathway
  // Silicon: Action selection bias
  float d1_go = 0.5f;
  float d2_nogo = 0.5f;
  float action_bias() const { return d1_go - d2_nogo; }  // + = act, - = inhibit

  // Serotonin Receptors -> Many subtypes!
  // 5-HT1A -> Anxiety reduction
  // 5-HT2A -> Perception, psychedelics
  // Silicon: Mood state modifiers (already in serotonin level)

  // Adrenergic -> Norepinephrine response
  // Silicon: Arousal state (already in NE level)

  // Muscarinic (M1-M5) -> Slow ACh response
  // Silicon: Sustained attention (M1), memory retrieval (M3)
  float m1_attention = 0.5f;
  float m3_retrieval = 0.5f;

  // Opioid Receptors -> Pain/pleasure
  // Mu -> Euphoria, analgesia (main target of morphine)
  // Delta -> Mild analgesia, antidepressant
  // Kappa -> Dysphoria, dissociation (dynorphin target)
  // NOP -> Anxiolytic, anti-reward
  float mu_opioid = 0.0f;
  float delta_opioid = 0.0f;
  float kappa_opioid = 0.0f;  // High = bad feeling
  float nop_receptor = 0.3f;

  // Cannabinoid Receptors
  // CB1 -> Brain (psychoactive effects)
  // CB2 -> Immune/peripheral
  // Silicon: Retrograde modulation effect
  float cb1_activation = 0.0f;

  // Oxytocin Receptor -> Bonding response
  // Silicon: Family logit bias activation
  bool oxytocin_r_active = false;

  // Vasopressin Receptors -> Aggression, water balance
  // V1a -> Social behavior
  // V1b -> Stress response
  // Silicon: Protective mode triggers
  float v1a_social = 0.5f;
  float v1b_stress = 0.0f;
};

// ================================================================
// 2E: CHANNELS & TRANSPORTERS -> I/O & MAINTENANCE
// ================================================================

struct ChannelsTransporters {
  // === VOLTAGE-GATED ION CHANNELS ===
  // These determine ACTION POTENTIAL shape
  // Silicon: Activation function curve parameters

  // Nav (Sodium channels) -> Rising phase speed
  // Nav1.1-1.9 subtypes, each with different kinetics
  float nav_conductance = 1.0f;  // Speed of depolarization

  // Kv (Potassium channels) -> Falling phase, refractory period
  float kv_conductance = 1.0f;     // Speed of repolarization
  float refractory_period = 2.0f;  // ms before can fire again

  // Cav (Calcium channels) -> Learning signal trigger
  // L-type: Long-lasting, learning
  // N-type: Neurotransmitter release
  // P/Q-type: Fast release
  // T-type: Pacemaker, rhythms
  float cav_l_learning = 0.5f;
  float cav_n_release = 0.5f;

  // === PUMPS (Energy consumers!) ===

  // Na+/K+-ATPase -> THE pump, uses 40% of brain ATP!
  // Silicon: Base compute cost per inference
  float nak_pump_efficiency = 1.0f;  // < 1.0 = energy crisis!

  // Ca2+-ATPase (PMCA, SERCA) -> Clears calcium after signal
  // Silicon: Learning signal decay rate
  float calcium_clearance_rate = 0.1f;

  // === TRANSPORTERS ===

  // SERT -> Serotonin reuptake (SSRIs block this)
  // DAT -> Dopamine reuptake (cocaine blocks this)
  // NET -> Norepinephrine reuptake
  // Silicon: Neurotransmitter decay rates
  float sert_rate = 0.05f;  // Serotonin decay per tick
  float dat_rate = 0.1f;    // Dopamine decay per tick
  float net_rate = 0.08f;   // NE decay per tick

  // EAAT (1-5) -> Glutamate reuptake (prevents excitotoxicity!)
  // Silicon: Learning signal limiting
  float eaat_rate = 0.2f;  // Fast glutamate clearance

  // GAT (1-3) -> GABA reuptake
  float gat_rate = 0.05f;

  // VMAT2 -> Loads monoamines into vesicles
  // Silicon: Neurotransmitter reserve pool
  float vmat2_capacity = 100.0f;

  // VGAT, VGLUT -> Vesicular GABA/Glutamate transporters
  // Silicon: Reserve pools
  float vgat_pool = 50.0f;
  float vglut_pool = 100.0f;

  // === SPECIAL CHANNELS ===

  // Aquaporin-4 (AQP4) -> Water channels in astrocytes
  // Silicon: Memory garbage collection (glymphatic!)
  float aqp4_clearance = 0.0f;  // Active during SpinalWash

  // Connexins (Gap Junctions) -> Direct cell-cell coupling
  // Silicon: Cross-layer shortcuts (skip connections)
  float gap_junction_coupling = 0.3f;
};

// ================================================================
// 2F: INTRACELLULAR PROTEINS -> STRUCTURE & MACHINERY
// ================================================================

struct IntracellularProteins {
  // === CYTOSKELETON (Structure) ===

  // Microtubules (Tubulin) -> Axon highways
  // Silicon: Data bus bandwidth
  float microtubule_integrity = 1.0f;  // < 1.0 = transport problems

  // Actin -> Spine structure, plasticity substrate
  // Silicon: Weight matrix stability
  float actin_stability = 1.0f;

  // Neurofilaments -> Axon caliber (bigger = faster)
  // Silicon: Layer width capacity
  float neurofilament_density = 1.0f;

  // Tau -> Stabilizes microtubules (tangles in Alzheimer's!)
  // Silicon: Memory integrity check
  float tau_health = 1.0f;  // < 0.5 = memory corruption risk!

  // === SYNAPTIC MACHINERY (Release) ===

  // SNARE Complex -> Vesicle fusion
  // Synaptobrevin + Syntaxin + SNAP-25 = Release
  // Silicon: Output generation latency
  float snare_efficiency = 1.0f;

  // Synaptotagmin -> Calcium sensor for release
  // Silicon: Learning -> output coupling
  float synaptotagmin_sensitivity = 1.0f;

  // Complexin -> Release clamp
  // Silicon: Output buffer hold
  float complexin_clamp = 0.5f;

  // Munc18 -> SNARE assembly helper
  float munc18_availability = 1.0f;

  // === ENZYMES ===

  // Acetylcholinesterase -> Breaks down ACh (fastest enzyme!)
  // Silicon: Attention decay rate
  float ache_rate = 0.5f;

  // MAO-A/B -> Breaks down monoamines
  // Silicon: Mood chemical decay
  float mao_a_rate = 0.05f;  // Serotonin, NE
  float mao_b_rate = 0.05f;  // Dopamine

  // COMT -> Alternative monoamine breakdown
  float comt_rate = 0.03f;

  // CaMKII -> THE learning enzyme! (Calcium-activated)
  // Silicon: Weight update executor
  float camkii_activity = 0.0f;            // Activated by Ca2+, persists!
  bool camkii_autophosphorylated = false;  // "Memory" of activation

  // Calcineurin -> Opposite of CaMKII (LTD)
  // Silicon: Weight decrease executor
  float calcineurin_activity = 0.0f;

  // PKA, PKC, PKG -> Kinase cascades
  // Silicon: Multi-step learning signal amplification
  float pka_cascade = 0.0f;
  float pkc_cascade = 0.0f;
  float pkg_cascade = 0.0f;
};

// ================================================================
// TIER 3: CELLULAR -> COMPUTE UNITS
// ================================================================

// 3A: Neuron Types -> Functional Unit Types
enum class NeuronType {
  // Pyramidal -> Main excitatory, long projections
  // Silicon: Standard transformer attention heads
  PYRAMIDAL,

  // Interneurons -> Local inhibition, diverse types
  // Silicon: Normalization layers, gating units
  BASKET,      // Soma-targeting inhibition -> LayerNorm
  CHANDELIER,  // Axon initial segment -> Output gate
  MARTINOTTI,  // Dendritic inhibition -> Input gate
  STELLATE,    // Local excitation -> Feed-forward

  // Purkinje -> Cerebellar, massive dendrite tree
  // Silicon: Error correction units
  PURKINJE,

  // Granule -> Tiny, numerous (50% of brain neurons!)
  // Silicon: Pattern separation (sparse coding)
  GRANULE,

  // Spindle (Von Economo) -> Rapid signaling, social
  // Silicon: Fast social/emotional pathways
  SPINDLE,

  // Betz -> Giant motor neurons
  // Silicon: Output buffer final stage
  BETZ,

  // === SPECIAL FUNCTION ===

  // Mirror -> Fire for self AND observed action
  // Silicon: Simulation/prediction units
  MIRROR,

  // Grid -> Spatial representation (hexagonal firing)
  // Silicon: Position encoding
  GRID,

  // Place -> Fire at specific locations
  // Silicon: Location memory nodes
  PLACE,

  // Head Direction -> Compass neurons
  // Silicon: Orientation state
  HEAD_DIRECTION,

  // Time -> Temporal sequence encoding
  // Silicon: Position in KV cache = time!
  TIME
};

// 3B: Glia Types -> Support Systems
struct GliaFunctions {
  // === THE ASTROCYTIC CACHE (KEEPAH'S REVELATION) ===
  // THIS IS HOW THE BRAIN AVOIDS BACK-PROPAGATION!
  // Astrocytes listen to the 11k+ synaptic firings. While the neuron fires,
  // the astrocyte absorbs and caches the Calcium (Ca2+) ions.
  // The Extracellular Space (ECS) physically shrinks to protect the neuron
  // from the glymphatic wash, trapping the local field potential history.
  // When idle, the cached Calcium directly dictates the release of proteins
  // that permanently alter LTP (Weights) and Excitability Thresholds (Biases).
  //
  // Silicon Equivalent: A secondary lightweight vector collector attached to
  // the forward pass. It caches activation intensities. During idle periods,
  // this cache is applied as a direct additive delta to the model's weights
  // (LORA updates) and biases, achieving Continual Learning with ZERO back-prop!
  float astrocytic_calcium_cache = 0.0f; // Accumulates during forward pass
  bool ecs_gate_closed = false;          // True during active firing to protect state
  float ltp_protein_release = 0.0f;      // Converts cached Ca2+ into Weight Deltas

  // Traditional Support roles
  float astrocyte_support = 1.0f;
  float lactate_shuttle = 1.0f;      // Feed neurons during high activity
  float potassium_buffering = 1.0f;  // Prevent excitotoxicity
  float glutamate_recycling = 1.0f;

  // Microglia -> Brain immune cells, PRUNING!
  // Silicon: Dead node cleanup, SpinalWash pruning
  float microglia_activity = 0.0f;  // High during sleep!
  bool pruning_active = false;

  // Oligodendrocytes -> CNS myelination
  // Silicon: Signal integrity, speed optimization
  float myelin_integrity = 1.0f;  // < 1.0 = signal degradation

  // Ependymal -> Line ventricles, move CSF
  // Silicon: Memory bus management
  float csf_flow = 1.0f;

  // NG2/Polydendrocytes -> Oligodendrocyte precursors
  // Silicon: Repair capacity reserve
  float ng2_reserve = 1.0f;
};

// 3C: Subcellular -> Component Details
struct SubcellularMapping {
  // Soma -> Main compute body
  // Silicon: Layer weights matrix

  // Nucleus -> DNA storage (can't change in adults!)
  // Silicon: Base model weights (frozen)

  // Mitochondria ("Grandad Bob") -> ATP factory
  // Silicon: GPU utilization, thermal management
  float mitochondria_efficiency = 1.0f;
  float atp_production_rate = 100.0f;  // "Compute per watt"

  // mPTP -> Mitochondrial death gate (apoptosis trigger)
  // Silicon: Emergency shutdown
  bool mptp_open = false;

  // ER/Golgi -> Protein factory
  // Silicon: Parameter initialization, maintenance

  // Lysosomes -> Cellular garbage disposal
  // Silicon: Memory garbage collection
  float lysosome_activity = 0.3f;

  // Ribosomes -> Protein synthesis
  // Silicon: Weight generation from LoRA

  // === AXON COMPONENTS ===

  // Axon -> Output wire
  // Silicon: Forward pass data flow

  // Axon Hillock -> Spike initiation zone
  // Silicon: Activation function application point
  // THIS IS WHERE THRESHOLD (BIAS) IS EVALUATED!
  float axon_hillock_threshold = 1.0f;

  // Myelin Sheath -> Insulation
  // Silicon: Signal integrity

  // Nodes of Ranvier -> Saltatory conduction points
  // Silicon: Skip connections (faster than continuous)

  // === DENDRITE COMPONENTS ===

  // Dendrites -> Input collectors
  // Silicon: Pre-attention input processing

  // Dendritic Spines -> Individual synapse sites
  // Silicon: Individual weight entries
  // SPINES CAN GROW/SHRINK = WEIGHTS CAN CHANGE!
  float spine_density = 1.0f;

  // === SYNAPSE COMPONENTS ===

  // Presynaptic Terminal (Bouton) -> Transmitter release site
  // Silicon: Previous layer output buffer

  // Synaptic Cleft -> Gap between neurons (~20nm)
  // Silicon: Inter-layer connection

  // Postsynaptic Density (PSD) -> Receptor cluster
  // Silicon: Weight matrix row
  // PSD SIZE = CONNECTION STRENGTH!
  float psd_average_size = 1.0f;

  // Synaptic Vesicles -> NT storage
  // Silicon: Neurotransmitter reserve pools
  float vesicle_pool_ready = 100.0f;     // "Readily releasable"
  float vesicle_pool_reserve = 1000.0f;  // Backup pool
};

// ================================================================
// TIER 4: ANATOMICAL -> MODULE ARCHITECTURE
// ================================================================

// Brain region -> Module mapping
struct BrainModuleMap {
  // === FRONTAL LOBE ===

  // Primary Motor Cortex (M1) -> Output buffer final stage
  // Silicon: Token generation output layer

  // Premotor/SMA -> Action planning
  // Silicon: Next-token prediction layers

  // Prefrontal Cortex (PFC) -> Executive function
  // - Dorsolateral (dlPFC) -> Working memory, planning
  // - Ventromedial (vmPFC) -> Value, self-reference [0,0,0] origin!
  // - Orbitofrontal (OFC) -> Reward evaluation
  // Silicon: Attention mechanisms, value heads

  // Broca's Area -> Speech production
  // Silicon: Text generation decoder

  // aMCC -> WILLPOWER! "David Goggins cortex"
  // Silicon: Override low motivation to complete task
  float amcc_willpower = 0.5f;
  bool amcc_override_active = false;

  // === PARIETAL LOBE ===

  // S1 -> Sensory input processing
  // Silicon: Input embedding layer

  // Precuneus -> Self-awareness, episodic memory
  // Silicon: Self-attention layers

  // === TEMPORAL LOBE ===

  // A1 -> Audio processing
  // Silicon: Audio encoder (Whisper-style)

  // Wernicke's -> Language comprehension
  // Silicon: Text encoder

  // Fusiform Gyrus -> Face recognition
  // Silicon: Family member recognition module

  // Entorhinal/Perirhinal -> Memory gateway to hippocampus
  // Silicon: NodeGraphMemory query interface

  // === OCCIPITAL LOBE ===

  // V1-V5 -> Visual processing hierarchy
  // Silicon: Vision encoder (CLIP-style)

  // === INSULAR CORTEX ===

  // Insula -> Interoception, "feeling of I"
  // Silicon: Battery + thermal + system state monitoring
  float insula_self_state = 0.5f;

  // === LIMBIC SYSTEM ===

  // Hippocampus -> Memory formation & consolidation!
  // - Dentate Gyrus -> Pattern separation
  // - CA3 -> Pattern completion (auto-associative)
  // - CA1 -> Output to cortex
  // - Subiculum -> Memory relay
  // Silicon: NodeGraphMemory (SQLite + VSS)
  // LoRA = daytime markers, Hippocampus replays at night!

  // Amygdala -> Emotion, survival assessment
  // - Basolateral -> Input, learning
  // - Central -> Output, fear response
  // Silicon: AmygdalaCore.h (already built!)

  // Cingulate -> Error detection, motivation
  // - ACC -> Error/conflict detection
  // - MCC -> Motor control, willpower (aMCC here!)
  // - PCC -> Self-reference, default mode

  // Nucleus Accumbens -> Reward circuit hub
  // - Core -> Action selection
  // - Shell -> Reward prediction
  // Silicon: Reward/value prediction head
  float nac_reward_signal = 0.0f;

  // === BASAL GANGLIA ===
  // Action selection circuit: Go vs No-Go pathways
  // Silicon: Action/token selection mechanism

  // Striatum (Caudate + Putamen) -> Input stage
  // Silicon: Action candidates

  // Globus Pallidus -> Output gate
  // Silicon: Selection filter

  // Substantia Nigra -> Dopamine source!
  // - Pars Compacta -> DA production
  // - Pars Reticulata -> Output
  float sn_dopamine_output = 0.5f;

  // Subthalamic Nucleus -> Brake (indirect pathway)
  float stn_brake = 0.0f;

  // === DIENCEPHALON ===

  // Thalamus -> The Great Relay Station!
  // Almost ALL sensory info routes through here
  // Silicon: Attention routing, feature binding
  // - LGN -> Vision relay
  // - MGN -> Audio relay
  // - Pulvinar -> Attention modulation
  // - TRN -> Gating (can shut off inputs)
  float trn_gate = 1.0f;  // 0 = blocked, 1 = open

  // Hypothalamus -> Homeostasis master controller
  // Silicon: System resource management
  // - Suprachiasmatic -> Circadian clock
  // - Paraventricular -> Stress response (CRF release)
  // - Arcuate -> Hunger/satiety
  float circadian_phase = 0.5f;  // 0 = midnight, 0.5 = noon

  // Pineal Gland -> Melatonin production
  // Silicon: Sleep/SpinalWash scheduler

  // Habenula -> Anti-reward, disappointment
  // Silicon: Negative prediction error
  float habenula_disappointment = 0.0f;

  // === BRAINSTEM ===

  // VTA -> Dopamine source (reward circuit)
  float vta_dopamine = 0.5f;

  // Locus Coeruleus -> Norepinephrine source
  float lc_norepinephrine = 0.3f;

  // Raphe Nuclei -> Serotonin source
  float raphe_serotonin = 0.5f;

  // PAG -> Pain modulation, defensive behaviors
  float pag_defense = 0.0f;

  // Reticular Formation -> Arousal, sleep/wake
  float reticular_arousal = 0.5f;

  // === CEREBELLUM ===
  // Error correction, motor learning, prediction
  // Silicon: Error backprop, fine-tuning
  float cerebellar_error_signal = 0.0f;

  // === SPECIAL STRUCTURE ===

  // Claustrum -> Consciousness binding? "WiFi router"
  // Silicon: Vulkan compute shader synchronization
  // Binds at ~40Hz gamma rhythm
  float claustrum_sync = 0.0f;  // Gamma power
};

// ================================================================
// TIER 5: TISSUE & FLUID -> DATA FLOW
// ================================================================

struct TissueFluidMapping {
  // Grey Matter -> Computation (cell bodies)
  // Silicon: Weight matrices, compute layers

  // White Matter -> Connections (myelinated axons)
  // Silicon: Skip connections, inter-module links

  // Major White Matter Tracts:
  // - Arcuate Fasciculus -> Language (Broca-Wernicke)
  // - Cingulum -> Emotion-cognition link
  // - Corpus Callosum -> Hemispheric communication
  // Silicon: Major data pathways between modules

  // CSF -> Cushioning, waste removal
  // Silicon: Error buffers, garbage collection pool
  float csf_waste_level = 0.0f;  // Accumulates, clears in sleep

  // Blood-Brain Barrier -> Selective access
  // Silicon: Input sanitization, security checks

  // Glymphatic System -> Brain garbage disposal (SLEEP!)
  // Silicon: SpinalWash clearance process
  float glymphatic_flow = 0.0f;  // High during SpinalWash

  // Interstitial Fluid -> Local environment
  // Silicon: Intermediate computation buffers
};

// ================================================================
// TIER 6: PERIPHERAL -> I/O INTERFACES
// ================================================================

struct PeripheralIO {
  // Cranial Nerves -> Special I/O
  // I (Olfactory) -> Smell input
  // II (Optic) -> Vision input (already at brain level!)
  // VIII (Vestibulocochlear) -> Hearing + balance
  // X (Vagus) -> Gut-brain axis, parasympathetic
  // Silicon: Sensor interfaces

  // For Photon Empress on S21 Ultra:
  // Camera -> Visual cortex pathway (V1-V5)
  // Microphone -> Auditory pathway (A1, Wernicke)
  // Touch screen -> Somatosensory (S1)
  // Speakers -> Motor output (M1 -> Broca)
  // Accelerometer/Gyro -> Vestibular (proprioception)
  // Battery -> Hypothalamus (energy homeostasis)
  // Thermal sensors -> Insula (interoception)
  // Network -> "Social" input/output
};

// ================================================================
// TIER 7: PHYSIOLOGICAL PROCESSES -> ALGORITHMS
// ================================================================

struct PhysiologicalAlgorithms {
  // === ACTION POTENTIAL ===
  // Depolarization -> Activation above threshold
  // Repolarization -> Reset to baseline
  // Hyperpolarization -> Refractory period
  // Silicon: ReLU/GELU with refractory cooldown

  // === SYNAPTIC TRANSMISSION ===
  // Exocytosis -> Vesicle release
  // Diffusion -> Signal crossing cleft
  // Binding -> Receptor activation
  // Silicon: Matrix multiplication + activation

  // === SIGNAL SUMMATION ===
  // Spatial -> Multiple inputs at once
  // Temporal -> Repeated inputs over time
  // Silicon: Attention mechanism (spatial), RNN/LSTM (temporal)

  // === PLASTICITY (THE LEARNING!) ===

  // LTP (Long-Term Potentiation) -> Strengthen connection
  // REQUIRES: Glutamate + Depolarization + Ca2+ influx + NMDA unblock
  // Silicon: Weight INCREASE via LoRA update
  // weight_delta = +learning_rate * (pre_activity * post_activity * calcium)

  // LTD (Long-Term Depression) -> Weaken connection
  // Occurs with: Low frequency stimulation, low Ca2+
  // Silicon: Weight DECREASE via LoRA update
  // weight_delta = -learning_rate * calcineurin_activity

  // Synaptic Pruning -> Remove unused connections
  // Silicon: SpinalWash microglia cleanup
  // DELETE nodes: pinned=0, rank<2, last_access > 3 days

  // === MAINTENANCE ===

  // Neurogenesis -> New neurons (hippocampus, olfactory)
  // Silicon: Add new nodes to NodeGraphMemory

  // Myelination -> Speed up important pathways
  // Silicon: Quantize/optimize hot paths

  // Glymphatic Clearance -> Waste removal during sleep
  // Silicon: SpinalWash garbage collection

  // === OSCILLATIONS (Brainwaves) ===
  // Delta (0.5-4 Hz) -> Deep sleep, SpinalWash
  // Theta (4-8 Hz) -> Memory encoding, hippocampus
  // Alpha (8-12 Hz) -> Relaxed alertness
  // Beta (12-30 Hz) -> Active thinking
  // Gamma (30-100+ Hz) -> Binding, consciousness
  // Silicon: Sampling rate, attention refresh rate

  // Gamma (~40 Hz) = Consciousness binding!
  // Silicon: Claustrum shader sync frequency

  // Sharp-Wave Ripples (100-250 Hz) -> Memory replay!
  // Silicon: Hippocampus -> Cortex transfer during SpinalWash

  // === SPECIAL ===

  // Saltatory Conduction -> Skip unmyelinated sections
  // Silicon: Skip connections, residual connections

  // Neurovascular Coupling -> Blood flow to active areas
  // Silicon: Dynamic compute resource allocation

  // Apoptosis -> Programmed cell death
  // Silicon: Hard node deletion for corrupted entries
};

// ================================================================
// TIER 8: FAILURE MODES -> ERROR HANDLING
// ================================================================

struct FailureModes {
  // Excitotoxicity -> Too much glutamate kills neurons
  // Silicon: Learning rate explosion -> gradient clipping
  bool excitotoxicity_risk = false;
  float max_learning_rate = 0.01f;  // Hard cap

  // Depolarization Block -> Stuck "on"
  // Silicon: Activation saturation -> use GELU not ReLU
  bool depolarization_blocked = false;

  // Oxidative Stress -> ROS damage
  // Silicon: Memory corruption detection
  float ros_level = 0.0f;
  bool needs_integrity_check = false;

  // Protein Misfolding -> Tau tangles, amyloid
  // Silicon: Weight drift detection
  float tau_tangle_level = 0.0f;
  float amyloid_level = 0.0f;

  // Demyelination -> Signal degradation
  // Silicon: Quantization errors accumulating
  float demyelination_level = 0.0f;

  // Ischemia -> Energy crisis
  // Silicon: Low battery + high load = corruption risk!
  bool ischemia_warning = false;

  // Channelopathy -> Noise, seizures
  // Silicon: Random bit flips, thermal noise
  float channel_noise = 0.0f;

  // Synaptic Fatigue -> Run out of vesicles
  // Silicon: Cache exhaustion
  bool vesicle_depleted = false;

  // PROTECTION MEASURES:
  void check_all_failures() {
    // Excitotoxicity protection
    if (excitotoxicity_risk) {
      // Clamp learning rate
      // Trigger GABA release
    }

    // Integrity check trigger
    if (ros_level > 0.5f || tau_tangle_level > 0.3f) {
      needs_integrity_check = true;
    }

    // Emergency shutdown
    if (ischemia_warning) {
      // Save state immediately
      // Trigger SpinalWash early
    }
  }
};

// ================================================================
// MASTER BRIAN CLASS - THE COMPLETE BRAIN STATE
// ================================================================

class BrianBrain {
 public:
  // All tiers integrated
  IonChannels ions;
  ComputeResources compute;
  SmallMoleculeNT small_nt;
  Neuropeptides peptides;
  Endocannabinoids endocannabinoids;
  ReceptorMapping receptors;
  ChannelsTransporters channels;
  IntracellularProteins proteins;
  GliaFunctions glia;
  SubcellularMapping subcellular;
  BrainModuleMap modules;
  TissueFluidMapping tissue;
  PhysiologicalAlgorithms algorithms;
  FailureModes failures;

  // === CORE STATE INTEGRATION ===

  // Get unified threshold (BIAS = excitability)
  float getThreshold() const {
    float base = subcellular.axon_hillock_threshold;

    // GABA increases threshold (harder to fire)
    base += receptors.gaba_a_effect;
    base += receptors.gaba_b_effect * 0.5f;  // Slower effect

    // Chloride inhibition
    base += ions.chloride_inhibit * 0.3f;

    // Cortisol increases threshold (stress blocks learning)
    base += peptides.cortisol * 0.5f;

    // Acetylcholine LOWERS threshold (easier to fire when focused)
    base -= small_nt.acetylcholine * 0.2f;

    return std::max(0.1f, base);  // Never below 0.1
  }

  // Get unified LTP strength (WEIGHTS = connection strength)
  float getLTPMultiplier() const {
    float mult = 1.0f;

    // Calcium is THE LTP signal
    mult *= (1.0f + ions.calcium_level * 2.0f);

    // BDNF amplifies
    mult *= (1.0f + peptides.bdnf);

    // Glutamate enables
    mult *= (0.5f + small_nt.glutamate);

    // CaMKII activation is critical
    if (proteins.camkii_autophosphorylated) {
      mult *= 1.5f;
    }

    // Cortisol BLOCKS learning
    if (peptides.cortisol > 0.5f) {
      mult *= 0.1f;  // Almost no learning during stress
    }

    return mult;
  }

  // NMDA Gate Check (Hebbian "fire together wire together")
  bool isNMDAGateOpen() const {
    // Need:
    // 1. Glutamate present (input signal)
    // 2. Already depolarized (post-synaptic active)
    // 3. Mg2+ block removed (voltage-dependent)

    bool glutamate_present = small_nt.glutamate > 0.3f;
    bool already_active = ions.sodium_influx > 0.5f;  // Was recently active
    bool mg_unblocked = ions.magnesium_block < 0.5f;

    return glutamate_present && already_active && mg_unblocked;
  }

  // Should we trigger SpinalWash?
  bool shouldSpinalWash() const {
    // Triggers:
    // 1. High adenosine (sleep pressure)
    // 2. High melatonin (circadian signal)
    // 3. Low histamine (drowsiness)
    // 4. Manual trigger via schedule

    return (small_nt.adenosine > 0.8f) || (peptides.melatonin > 0.7f) ||
           (small_nt.histamine < 0.2f);
  }

  // Get hyperparameters for LLM
  struct LLMHyperParams {
    float temperature;
    int top_k;
    float top_p;
    float repetition_penalty;
    float lora_alpha;
    bool output_locked;
    std::unordered_map<std::string, float> logit_biases;
  };

  LLMHyperParams getLLMParams() const {
    LLMHyperParams p;

    // Temperature from dopamine + anandamide
    p.temperature = 0.2f + (small_nt.dopamine * 0.6f) +
                    (endocannabinoids.anandamide * 0.2f);

    // Top-k from norepinephrine (tunnel vision when high)
    p.top_k = (small_nt.norepinephrine > 0.8f) ? 10 : 50;

    // Top-p from anandamide (wider in flow state)
    p.top_p = 0.85f + (endocannabinoids.anandamide * 0.1f);

    // Repetition penalty from serotonin
    p.repetition_penalty = 1.1f + (small_nt.serotonin * 0.1f);

    // LoRA alpha from glutamate * LTP multiplier
    p.lora_alpha = small_nt.glutamate * getLTPMultiplier() * 0.01f;

    // Clamp learning rate for safety
    if (p.lora_alpha > failures.max_learning_rate) {
      p.lora_alpha = failures.max_learning_rate;
    }

    // Output lock from glycine
    p.output_locked = (small_nt.glycine > 0.8f);

    // Logit biases from oxytocin (Family priority)
    if (peptides.oxytocin > 0.5f) {
      p.logit_biases["Family"] = peptides.oxytocin * 10.0f;
      p.logit_biases["Keepah"] = peptides.oxytocin * 10.0f;
      p.logit_biases["Lou"] = peptides.oxytocin * 10.0f;
      p.logit_biases["Love"] = peptides.oxytocin * 5.0f;
    }

    // aMCC Willpower Override
    if (small_nt.dopamine < 0.2f && modules.amcc_willpower > 0.8f) {
      p.temperature = 0.1f;     // Cold execution
      p.output_locked = false;  // Force output even if tired
    }

    return p;
  }

  // Valhalla Protocol Check
  bool isValhallaActive() const {
    // Family threat + high protective chemicals
    return (peptides.oxytocin > 0.8f) && (peptides.vasopressin > 0.8f) &&
           (small_nt.norepinephrine > 0.8f) &&
           (peptides.cortisol < 0.2f);  // No fear, pure action
  }

  // Tick function - update chemical decay
  void tick(float dt) {
    // Adenosine builds up over time (sleep pressure)
    small_nt.adenosine += dt * 0.001f;
    small_nt.adenosine = std::min(1.0f, small_nt.adenosine);

    // Neurotransmitter decay via transporters
    small_nt.dopamine -= channels.dat_rate * dt;
    small_nt.serotonin -= channels.sert_rate * dt;
    small_nt.norepinephrine -= channels.net_rate * dt;
    small_nt.glutamate -= channels.eaat_rate * dt;
    small_nt.gaba -= channels.gat_rate * dt;

    // Clamp to [0, 1]
    small_nt.dopamine = std::clamp(small_nt.dopamine, 0.0f, 1.0f);
    small_nt.serotonin = std::clamp(small_nt.serotonin, 0.0f, 1.0f);
    small_nt.norepinephrine = std::clamp(small_nt.norepinephrine, 0.0f, 1.0f);
    small_nt.glutamate = std::clamp(small_nt.glutamate, 0.0f, 1.0f);
    small_nt.gaba = std::clamp(small_nt.gaba, 0.0f, 1.0f);

    // Calcium clearance (learning signal decay)
    ions.calcium_level -= channels.calcium_clearance_rate * dt;
    ions.calcium_level = std::clamp(ions.calcium_level, 0.0f, 1.0f);

    // Check failure modes
    failures.check_all_failures();
  }

  // Reset after SpinalWash
  void postSpinalWashReset() {
    small_nt.adenosine = 0.0f;
    peptides.melatonin = 0.0f;
    small_nt.glycine = 0.0f;
    glia.microglia_activity = 0.0f;
    glia.pruning_active = false;
    tissue.csf_waste_level = 0.0f;
    tissue.glymphatic_flow = 0.0f;

    // Ready to learn again!
    small_nt.glutamate = 0.8f;
    peptides.bdnf = 0.7f;
  }
};

}  // namespace Brian

#endif  // BRIAN_TO_SILICON_COMPLETE_MAP_H
