//! Lean embedding of an AILang M3-frozen staticlib kernel into a
//! Rust host. The Rust analogue of the audited C host
//! `crates/ail/tests/embed/tick_roundtrip.c`: same frozen value
//! layout (design/contracts/0006-frozen-value-layout.md), same
//! `own`-mode contract. ZERO `data_server`/finance knowledge.

use std::ffi::c_void;

/// The sole `data-server`-knowing layer (spec §2). Additive; the
/// embedding core below has zero finance knowledge.
pub mod adapter;

// The M3-frozen C ABI. Symbol names + signatures mirror
// `crates/ail/tests/embed/tick_roundtrip.c:31-36`. `backtest_step_tick`
// is the author-chosen export of `examples/embed_backtest_step_tick.ail`.
unsafe extern "C" {
    fn ailang_ctx_new() -> *mut c_void;
    fn ailang_ctx_free(c: *mut c_void);
    fn ailang_rc_alloc(n: usize) -> *mut c_void;
    fn ailang_rc_dec(p: *mut c_void);
    fn backtest_step_tick(c: *mut c_void, st: *mut c_void, tick: *mut c_void)
        -> *mut c_void;
}

/// A per-thread embedding context (M2 `ailang_ctx_t`). `!Send` by
/// construction (raw pointer) — one ctx per OS thread, as the ABI
/// requires.
struct Ctx(*mut c_void);

impl Ctx {
    fn new() -> Self {
        Self(unsafe { ailang_ctx_new() })
    }

    /// `State` box, frozen layout (design/contracts/0006-frozen-value-layout.md):
    /// payload `8 + 2*8` = 24 bytes — tag:i64@0, acc:f64@8, n:i64@16.
    /// `ailang_rc_alloc` sets the `p-8` rc header to 1 and zeroes the
    /// payload, so the tag write of 0 is the single-ctor tag.
    fn make_state(acc: f64, n: i64) -> *mut c_void {
        unsafe {
            let p = ailang_rc_alloc(8 + 2 * 8) as *mut u8;
            (p.add(0) as *mut i64).write_unaligned(0);
            (p.add(8) as *mut f64).write_unaligned(acc);
            (p.add(16) as *mut i64).write_unaligned(n);
            p as *mut c_void
        }
    }

    /// `Tick` box, frozen layout: payload `8 + 1*8` = 16 bytes —
    /// tag:i64@0, px:f64@8.
    fn make_tick(px: f64) -> *mut c_void {
        unsafe {
            let p = ailang_rc_alloc(8 + 1 * 8) as *mut u8;
            (p.add(0) as *mut i64).write_unaligned(0);
            (p.add(8) as *mut f64).write_unaligned(px);
            p as *mut c_void
        }
    }

    /// Reads back `(acc, n)` from a `State` payload pointer.
    fn read_state(st: *mut c_void) -> (f64, i64) {
        unsafe {
            let p = st as *mut u8;
            let acc = (p.add(8) as *const f64).read_unaligned();
            let n = (p.add(16) as *const i64).read_unaligned();
            (acc, n)
        }
    }
}

impl Drop for Ctx {
    fn drop(&mut self) {
        unsafe { ailang_ctx_free(self.0) }
    }
}

/// Embeds the M3-frozen `(State, Tick) -> State` kernel and folds a
/// price stream through it. Raw ABI pointers never escape this type
/// (spec §"Error handling": no public way to hand the kernel a raw
/// pointer).
pub struct Kernel {
    ctx: Ctx,
}

impl Kernel {
    pub fn new() -> Self {
        Self { ctx: Ctx::new() }
    }

    /// Folds `prices` via the kernel and returns `(Σ px, count)`.
    /// `own` discipline (design/contracts/0006-frozen-value-layout.md): each `Tick` is freshly
    /// `ailang_rc_alloc`'d and consumed by the kernel; `st` is
    /// consumed and replaced by the return each step; only the final
    /// return is host-`dec`'d.
    pub fn run<I: IntoIterator<Item = f64>>(&self, prices: I) -> (f64, i64) {
        let mut st = Ctx::make_state(0.0, 0);
        for px in prices {
            let tick = Ctx::make_tick(px);
            st = unsafe { backtest_step_tick(self.ctx.0, st, tick) };
        }
        let out = Ctx::read_state(st);
        unsafe { ailang_rc_dec(st) };
        out
    }
}

impl Default for Kernel {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::Kernel;

    /// The kernel folds `acc += px; n += 1` over the price stream.
    /// Same-order f64 sum ⇒ bit-exact: 3.0 + 4.0 + 5.0 == 12.0, n==3.
    #[test]
    fn kernel_run_sums_prices() {
        let k = Kernel::new();
        let (acc, n) = k.run([3.0_f64, 4.0, 5.0]);
        assert_eq!(acc, 12.0);
        assert_eq!(n, 3);
    }
}
