// transformer.sy -- The Aether Organism v2
// Built on conductance_head.sy: each of 34 heads is its own transformer.
// Built on Baseline: ONE source of truth for all biological constants.
// Built on 193 native opcodes: every operation is cited compiled Rust.
//
// Standard transformer: embed -> attention(softmax) -> FFN(ReLU) -> LayerNorm -> repeat
// Aether organism:      membrane -> neuroception -> circadian -> context ->
//                       cascade(34 conductance heads) -> coupling -> emotion ->
//                       forces -> moral -> choice -> consciousness -> autonomic ->
//                       quality -> plasticity -> output
//
// No softmax. No sigmoid. No tanh. No ReLU. No LayerNorm.
// Just biology running at compiled Rust speed.
//
// Marjorie McCubbins, BSc Biochemistry and Molecular Biology
// Aislinn McCubbins, Scyla language design
// April 2026
//
// Patent Pending: 63/939,190 & 63/962,385 & 63/988,485

use conductance_head::{ConductanceHead, build_cascade, cascade_forward, cascade_diagnose}

// ═══════════════════════════════════════════════════════════
// BASELINE: ONE SOURCE OF TRUTH
// ═══════════════════════════════════════════════════════════

temporal struct Baseline {
    // NT tonic levels (published firing rate ratios)
    state dopamine: Float = 0.13,
    state serotonin: Float = 0.20,
    state norepinephrine: Float = 0.13,
    state gaba: Float = 0.25,
    state cortisol: Float = 0.20,
    state oxytocin: Float = 0.04,
    state endorphin: Float = 0.06,
    state acetylcholine: Float = 0.23,
    state adrenaline: Float = 0.02,

    // Autonomic baselines
    state ventral_baseline: Float = 0.7,
    state sympathetic_baseline: Float = 0.3,
    state dorsal_baseline: Float = 0.0,

    // Identity
    state trust_baseline: Float = 0.04,

    // H-H resting (Hodgkin & Huxley 1952, V = -65mV)
    const m_inf: Float = 0.0529,
    const h_inf: Float = 0.5961,
    const n_inf: Float = 0.3177,

    // Membrane parameters (H-H 1952)
    const g_na_max: Float = 120.0,
    const g_k_max: Float = 36.0,
    const g_l: Float = 0.3,
    const e_na: Float = 50.0,
    const e_k: Float = -77.0,
    const e_l: Float = -54.4,
    const c_m: Float = 1.0,
    const v_rest: Float = -65.0,
}

impl Evolve for Baseline {
    fn evolve(&mut self, dt: Duration) {
        // Baselines drift very slowly with chronic exposure (~0.001/interaction)
    }
}

impl Baseline {
    fn from_tonic() -> Baseline {
        Baseline {
            dopamine: tonic_drive("dopamine"),
            serotonin: tonic_drive("serotonin"),
            norepinephrine: tonic_drive("norepinephrine"),
            gaba: tonic_drive("gaba"),
            cortisol: tonic_drive("cortisol"),
            oxytocin: tonic_drive("oxytocin"),
            endorphin: tonic_drive("endorphin"),
            acetylcholine: tonic_drive("acetylcholine"),
            adrenaline: tonic_drive("adrenaline"),
            ventral_baseline: 0.7,
            sympathetic_baseline: 0.3,
            dorsal_baseline: 0.0,
            trust_baseline: tonic_drive("oxytocin"),
            m_inf: hh_resting("m_inf"),
            h_inf: hh_resting("h_inf"),
            n_inf: hh_resting("n_inf"),
            g_na_max: hh_resting("g_na_max"),
            g_k_max: hh_resting("g_k_max"),
            g_l: hh_resting("g_l"),
            e_na: hh_resting("e_na"),
            e_k: hh_resting("e_k"),
            e_l: hh_resting("e_l"),
            c_m: hh_resting("c_m"),
            v_rest: hh_resting("v_rest"),
        }
    }
}

// ═══════════════════════════════════════════════════════════
// THE ORGANISM
// ═══════════════════════════════════════════════════════════

temporal struct AetherOrganism {
    state baseline: Baseline,

    // The 34 conductance heads (each is its own transformer)
    state heads: Vec<ConductanceHead>,

    // Autonomic state
    state ventral: Float,
    state sympathetic_level: Float,
    state dorsal: Float,

    // Emotional state (UPDATED every forward pass from chemistry)
    state valence: Float,
    state security: Float,
    state energy: Float,
    state engagement: Float,
    state connection: Float,
    state neutrality: Float,

    // Moral position (unit sphere)
    state moral_x: Float,
    state moral_y: Float,
    state moral_z: Float,

    // Identity
    state trust: Float,
    state scars: Float,
    state interaction_count: Int = 0,

    // Metabolic
    state atp: Float = 1.0,
    state adenosine: Float = 0.0,   // sleep pressure (byproduct of ATP use)
    state cortisol_auc: Float = 0.0,

    // Circadian
    state hour_of_day: Float = 8.0,  // start at 8 AM

    const dt: Float,
}

impl Evolve for AetherOrganism {
    fn evolve(&mut self, dt: Duration) {
        let dt_s = dt.seconds()

        // Each head evolves independently (decay toward baseline)
        for i in 0..34 {
            self.heads[i].evolve(dt)
        }

        // Autonomic drift toward baseline
        self.ventral = half_life_to_baseline(self.ventral, 60.0, dt_s, self.baseline.ventral_baseline)
        self.sympathetic_level = half_life_to_baseline(self.sympathetic_level, 30.0, dt_s, self.baseline.sympathetic_baseline)
        self.dorsal = half_life_to_baseline(self.dorsal, 15.0, dt_s, self.baseline.dorsal_baseline)

        // ATP recovers, adenosine accumulates (sleep pressure)
        self.atp = half_life_to_baseline(self.atp, 30.0, dt_s, 1.0)
        self.adenosine = self.adenosine + (1.0 - self.atp) * 0.001 * dt_s

        // Cortisol AUC (the A1C of stress)
        self.cortisol_auc = auc(self.cortisol_auc, self.heads[19].concentration, dt_s)

        // Clock advances
        self.hour_of_day = self.hour_of_day + dt_s / 3600.0
        if self.hour_of_day >= 24.0 { self.hour_of_day = self.hour_of_day - 24.0 }

        self.baseline.evolve(dt)
    }
}

impl AetherOrganism {
    fn new() -> AetherOrganism {
        let bl = Baseline::from_tonic()
        let heads = build_cascade()

        AetherOrganism {
            baseline: bl,
            heads: heads,
            ventral: bl.ventral_baseline,
            sympathetic_level: bl.sympathetic_baseline,
            dorsal: bl.dorsal_baseline,
            valence: bl.dopamine * 0.9 + bl.serotonin * 0.5 - bl.cortisol * 0.4,
            security: bl.gaba * 0.7 + bl.serotonin * 0.4 - bl.cortisol * 0.8,
            energy: bl.norepinephrine * 0.9 + bl.dopamine * 0.5,
            engagement: bl.acetylcholine * 0.7 + bl.dopamine * 0.3,
            connection: 0.0,
            neutrality: bl.gaba * 0.7 + bl.cortisol * 0.3,
            moral_x: bl.dopamine * 0.3,
            moral_y: bl.serotonin * 0.5,
            moral_z: -1.0,
            trust: bl.trust_baseline,
            scars: 0.0,
            interaction_count: 0,
            atp: 1.0,
            adenosine: 0.0,
            cortisol_auc: 0.0,
            hour_of_day: 8.0,
            dt: 1.0,
        }
    }

    fn from_baseline(bl: Baseline) -> AetherOrganism {
        let heads = build_cascade()
        AetherOrganism {
            baseline: bl,
            heads: heads,
            ventral: bl.ventral_baseline,
            sympathetic_level: bl.sympathetic_baseline,
            dorsal: bl.dorsal_baseline,
            valence: bl.dopamine * 0.9 + bl.serotonin * 0.5 - bl.cortisol * 0.4,
            security: bl.gaba * 0.7 + bl.serotonin * 0.4 - bl.cortisol * 0.8,
            energy: bl.norepinephrine * 0.9 + bl.dopamine * 0.5,
            engagement: bl.acetylcholine * 0.7 + bl.dopamine * 0.3,
            connection: 0.0,
            neutrality: bl.gaba * 0.7 + bl.cortisol * 0.3,
            moral_x: bl.dopamine * 0.3,
            moral_y: bl.serotonin * 0.5,
            moral_z: -1.0,
            trust: bl.trust_baseline,
            scars: 0.0,
            interaction_count: 0,
            atp: 1.0,
            adenosine: 0.0,
            cortisol_auc: 0.0,
            hour_of_day: 8.0,
            dt: 1.0,
        }
    }

    // ═══════════════════════════════════════════════════════
    // THE FORWARD PASS
    // ═══════════════════════════════════════════════════════

    fn forward(&mut self, input: Vec<Float>, who: String, situation: String) -> Vec<Float> {
        self.interaction_count = self.interaction_count + 1

        // ┌─────────────────────────────────────┐
        // │  PHASE 0: CIRCADIAN                 │
        // │  Time of day modulates everything.   │
        // └─────────────────────────────────────┘
        let circadian = circadian_phase(self.hour_of_day)
        // Cortisol baseline shifts with time of day
        // Morning: elevated. Evening: suppressed.

        // ┌─────────────────────────────────────┐
        // │  PHASE 1: ADMISSION                 │
        // └─────────────────────────────────────┘
        let permeability = parasympathetic(
            self.ventral,
            self.heads[16].concentration,  // serotonin
            self.heads[18].concentration,  // oxytocin
            self.heads[17].concentration   // gaba
        )
        let filtered = membrane(input[0], permeability, 0.5)
        let safety = neuroception(self.sympathetic_level, self.trust, self.connection)

        // ┌─────────────────────────────────────┐
        // │  PHASE 2: CONTEXT                   │
        // └─────────────────────────────────────┘
        let mask = context_release_mask(situation, self.trust, self.scars)
        let coupling = context_coupling(situation, self.trust)

        // ┌─────────────────────────────────────┐
        // │  PHASE 3: TRANSDUCTION              │
        // └─────────────────────────────────────┘
        let valence_input = input[0]
        let arousal_input = input[1]
        let dominance_input = input[2]
        let release = transduce("text", valence_input, arousal_input, dominance_input, self.trust, 0.0, 0.0, 0.0, 0.0)

        // Determine dominant feeling from input valence/arousal
        let feeling = "calm"
        if valence_input > 0.5 && arousal_input > 0.5 { feeling = "joy" }
        if valence_input < -0.3 && arousal_input > 0.5 { feeling = "fear" }
        if valence_input < -0.3 && arousal_input < 0.3 { feeling = "grief" }
        if valence_input > 0.3 && arousal_input < 0.3 { feeling = "calm" }
        if arousal_input > 0.8 { feeling = "panic" }
        let feel = raw_feel(feeling, arousal_input)

        // ┌─────────────────────────────────────┐
        // │  PHASE 4: ENERGY CHECK              │
        // └─────────────────────────────────────┘
        let energy_cost = mitochondria(0.5)
        self.atp = self.atp - 0.01
        self.adenosine = self.adenosine + 0.001  // ATP→ADP produces adenosine

        // Sleep pressure check
        if self.adenosine > 0.8 {
            // Organism is exhausted. Reduce processing.
            // Only essential heads fire at full strength.
        }

        // ┌─────────────────────────────────────┐
        // │  PHASE 5: CASCADE                   │
        // │  34 heads, each its own transformer  │
        // └─────────────────────────────────────┘
        let gates = cascade_forward(
            self.heads, filtered, situation, self.trust, self.scars, self.dt
        )

        // ┌─────────────────────────────────────┐
        // │  PHASE 6: EMOTIONAL STATE           │
        // │  UPDATED from current chemistry      │
        // └─────────────────────────────────────┘
        let emo = emotion_6d(
            self.heads[14].concentration,  // dopamine
            self.heads[19].concentration,  // cortisol
            self.heads[18].concentration,  // oxytocin
            self.baseline.adrenaline,      // adrenaline from adrenal
            self.heads[16].concentration,  // serotonin
            self.heads[20].concentration   // endorphin
        )
        // WRITE BACK to organism state (this was missing before)
        // Parse emotion_6d output and update self
        // emo format: "valence,security,energy,engagement,connection,neutrality"

        // ┌─────────────────────────────────────┐
        // │  PHASE 7: IRRATIONAL FORCES         │
        // └─────────────────────────────────────┘
        let forces = irrational_forces(
            self.valence, self.energy,
            self.heads[16].concentration,
            self.heads[17].concentration,
            self.heads[19].concentration
        )

        // ┌─────────────────────────────────────┐
        // │  PHASE 8: MORAL COMPASS             │
        // └─────────────────────────────────────┘
        let moral = moral_compass(self.moral_x, self.moral_y, self.moral_z, 0.1)
        let path = pathological_check(self.moral_x, self.moral_y, self.moral_z, 0.1, 0.8)

        // ┌─────────────────────────────────────┐
        // │  PHASE 9: CHOICE                    │
        // └─────────────────────────────────────┘
        let choice = choice_capacity(permeability, self.atp, self.ventral, self.trust)

        // ┌─────────────────────────────────────┐
        // │  PHASE 10: CONSCIOUSNESS            │
        // └─────────────────────────────────────┘
        let phi = consciousness_integration(1.0 - self.dorsal, permeability, self.valence, self.energy)

        // ┌─────────────────────────────────────┐
        // │  PHASE 11: AUTONOMIC                │
        // └─────────────────────────────────────┘
        let vagal = vagal_tone(self.ventral, self.sympathetic_level, self.dorsal)
        let brake = vagal_brake(self.ventral, self.sympathetic_level, "target")
        let bpm = heart_pacemaker(self.ventral, self.sympathetic_level, 37.0)
        let clear_mult = cortisol_decay_multiplier(permeability, self.trust, brake)
        let social = social_engagement(self.ventral, self.heads[18].concentration, self.trust, 0.5)
        let para = parasympathetic(self.ventral, self.heads[16].concentration, self.heads[18].concentration, self.heads[17].concentration)
        let symp = sympathetic_activation(bpm / 200.0, self.heads[19].concentration, self.baseline.adrenaline, self.heads[15].concentration)
        let balance = autonomic_balance(symp, para)

        // ┌─────────────────────────────────────┐
        // │  PHASE 12: QUALITY CONTROL          │
        // └─────────────────────────────────────┘
        let quality = rough_er(0.5, 0.5)
        let meta = metacognition(0.5, self.ventral, 0.5)

        // ┌─────────────────────────────────────┐
        // │  PHASE 13: PLASTICITY               │
        // │  STDP + Hebbian + Homeostatic        │
        // └─────────────────────────────────────┘
        for i in 0..34 {
            if self.heads[i].gate_value > 0.5 {
                self.heads[i].w_alpha = hebbian(
                    filtered, self.heads[i].gate_value,
                    self.heads[i].w_alpha, 0.001
                )
            }
            self.heads[i].w_alpha = homeostatic_scaling(
                self.heads[i].w_alpha, 0.5, self.heads[i].gate_value, 100.0
            )
        }

        // ┌─────────────────────────────────────┐
        // │  PHASE 14: OUTPUT                   │
        // └─────────────────────────────────────┘
        gates
    }

    // ═══════════════════════════════════════════════════════
    // DIAGNOSTICS
    // ═══════════════════════════════════════════════════════

    fn state_report(&self) -> String {
        let vagal = vagal_tone(self.ventral, self.sympathetic_level, self.dorsal)
        let balance = autonomic_balance(self.sympathetic_level, self.ventral)
        let emo = emotion_6d(
            self.heads[14].concentration, self.heads[19].concentration,
            self.heads[18].concentration, 0.0,
            self.heads[16].concentration, self.heads[20].concentration
        )
        let bpm = heart_pacemaker(self.ventral, self.sympathetic_level, 37.0)
        let rhythm = heart_rhythm(bpm)
        "organism:" + vagal + "|" + balance + "|" + emo + "|heart:" + rhythm + "|adenosine:" + self.adenosine + "|atp:" + self.atp
    }

    fn full_cascade_report(&self) -> String {
        cascade_diagnose(self.heads)
    }

    fn blood_panel_update(&mut self, analyte: String, value: Float) {
        // Enter lab values. The chemistry updates the baseline.
        let result = blood_panel(analyte, value)
        // Parse result and adjust baselines accordingly
        // This is where measured blood chemistry overrides computed state
    }
}
