//! The bindings of the integer-quantised profile (`extensions/prior-carriage.md` §10.2): for
//! each native integer artifact, the named integer tensors that carry it, and the exact map
//! both ways. Loading does no arithmetic but reading integers: every value is the integer
//! the kernel reads, and every scale the kernel applies (a multiplier, a shift) is itself a
//! tensor, so a prior carried in any form loads into the same native bytes.

use std::collections::{BTreeMap, BTreeSet};

use super::{refuse, DType, Form, Refusal, Tensor, TensorSet, KEY_BINDING, KEY_PROFILE, PROFILE};

/// A registered binding.
pub struct Binding {
    /// Its name, the value of `wai.binding`.
    pub name: &'static str,
    /// The native artifact, in words.
    pub native: &'static str,
    /// The native bytes as tensors (no metadata).
    pub from_native: fn(&[u8]) -> Result<TensorSet, Refusal>,
    /// The tensors of a file read in a form as the native bytes: §10.3 steps 4 and 5.
    pub to_native: fn(&TensorSet, Form) -> Result<Vec<u8>, Refusal>,
}

/// Every registered binding.
pub const BINDINGS: &[Binding] = &[
    Binding { name: "wsr1/1", native: "a WSR1 prior (exact-upscale §3.1)", from_native: wsr1_from, to_native: wsr1_to },
    Binding { name: "whm1/1", native: "a WHM1 model (integer-payloads §9)", from_native: whm1_from, to_native: whm1_to },
];

pub fn by_name(n: &str) -> Option<&'static Binding> {
    BINDINGS.iter().find(|b| b.name == n)
}

/// The value `general.architecture` takes in a GGUF file of the profile (§10.1).
pub const GGUF_ARCHITECTURE: &str = "wai";

/// The metadata a file of the profile carries in `form` (§10.1).
pub fn profile_metadata(binding: &str, form: Form) -> BTreeMap<String, String> {
    let mut m = BTreeMap::new();
    m.insert(KEY_BINDING.to_string(), binding.to_string());
    m.insert(KEY_PROFILE.to_string(), PROFILE.to_string());
    if form == Form::Gguf {
        m.insert("general.architecture".to_string(), GGUF_ARCHITECTURE.to_string());
    }
    m
}

/// §10.3 steps 1 to 3: the profile and its keys, a registered binding, integer tensors.
pub fn of(set: &TensorSet, form: Form) -> Result<&'static Binding, Refusal> {
    let bname = set.metadata.get(KEY_BINDING).cloned().unwrap_or_default();
    let want = profile_metadata(&bname, form);
    if set.metadata.get(KEY_PROFILE).map(String::as_str) != Some(PROFILE)
        || set.metadata.keys().ne(want.keys())
        || (form == Form::Gguf && set.metadata.get("general.architecture").map(String::as_str) != Some(GGUF_ARCHITECTURE))
    {
        let keys: Vec<&String> = want.keys().collect();
        return refuse("profile_absent", format!("the metadata is not exactly {keys:?} with {KEY_PROFILE} = {PROFILE}"));
    }
    let Some(b) = by_name(&bname) else { return refuse("binding_unknown", format!("no binding {bname:?}")) };
    for t in &set.tensors {
        let ok = if form == Form::Nnc { t.dtype == DType::I32 } else { t.dtype.is_profile_integer() };
        if !ok {
            return refuse("dtype_not_integer", format!("{:?} is {:?}", t.name, t.dtype));
        }
    }
    Ok(b)
}

/// A binding's range for a value: `(tensor name, index)` to its bounds, `None` for its type's.
type Range<'a> = &'a dyn Fn(&str, usize) -> Option<(i64, i64)>;
/// The values a check returns, by tensor name.
type Values = BTreeMap<String, Vec<i64>>;

/// One tensor a binding names: its name, element type and shape.
struct Want {
    name: String,
    dtype: DType,
    shape: Vec<u64>,
}

/// §10.3 step 4 then 5 over the tensors a binding expects, in its table's order: the names
/// exactly these (`binding_mismatch`), then each tensor's type (the binding's, or `I32` in
/// NNC) and shape (`binding_mismatch`), then each value within the type the binding gives
/// and the range `range` gives (`value_out_of_range`). Returns the values by name.
fn check(set: &TensorSet, form: Form, wants: &[Want], range: Range<'_>) -> Result<Values, Refusal> {
    let have: BTreeSet<&str> = set.tensors.iter().map(|t| t.name.as_str()).collect();
    let need: BTreeSet<&str> = wants.iter().map(|w| w.name.as_str()).collect();
    if have != need {
        let extra: Vec<&&str> = have.difference(&need).collect();
        let missing: Vec<&&str> = need.difference(&have).collect();
        return refuse("binding_mismatch", format!("tensors not in the binding {extra:?}, missing {missing:?}"));
    }
    for w in wants {
        let t = set.get(&w.name).expect("present");
        let dt = if form == Form::Nnc { DType::I32 } else { w.dtype };
        if t.dtype != dt || t.shape != w.shape {
            return refuse("binding_mismatch", format!("{:?} is {:?} {:?}, the binding gives {:?} {:?}", w.name, t.dtype, t.shape, dt, w.shape));
        }
    }
    let mut out = BTreeMap::new();
    for w in wants {
        let v = set.get(&w.name).expect("present").ints().expect("an integer tensor");
        let (tlo, thi) = w.dtype.int_range().expect("an integer type");
        for (i, &x) in v.iter().enumerate() {
            let (lo, hi) = range(&w.name, i).map(|(a, b)| (a.max(tlo), b.min(thi))).unwrap_or((tlo, thi));
            if x < lo || x > hi {
                return refuse("value_out_of_range", format!("{}[{i}] = {x}, outside {lo}..={hi}", w.name));
            }
        }
        out.insert(w.name.clone(), v);
    }
    Ok(out)
}

fn want(name: impl Into<String>, dtype: DType, shape: Vec<u64>) -> Want {
    Want { name: name.into(), dtype, shape }
}

/// Indices `i` of tensors named `<prefix><i><suffix>`, written in plain decimal
/// (`width` digits when `width` is set), in ascending order.
fn indices(set: &TensorSet, prefix: &str, suffix: &str, width: Option<usize>) -> Vec<usize> {
    let mut v: Vec<usize> = set
        .tensors
        .iter()
        .filter_map(|t| t.name.strip_prefix(prefix)?.strip_suffix(suffix).map(str::to_string))
        .filter(|d| !d.is_empty() && d.bytes().all(|c| c.is_ascii_digit()) && width.is_none_or(|w| d.len() == w) && (width.is_some() || d == "0" || !d.starts_with('0')))
        .filter_map(|d| d.parse().ok())
        .collect();
    v.sort_unstable();
    v
}

fn native_err(why: &str) -> Refusal {
    Refusal::new("native_malformed", why.to_string())
}

struct Rd<'a> {
    b: &'a [u8],
    p: usize,
}

impl Rd<'_> {
    fn take(&mut self, n: usize) -> Result<&[u8], Refusal> {
        let e = self.p.checked_add(n).filter(|&e| e <= self.b.len()).ok_or_else(|| native_err("truncated"))?;
        let s = &self.b[self.p..e];
        self.p = e;
        Ok(s)
    }
    fn u8(&mut self) -> Result<u8, Refusal> {
        Ok(self.take(1)?[0])
    }
    fn u16(&mut self) -> Result<u16, Refusal> {
        Ok(u16::from_le_bytes(self.take(2)?.try_into().expect("2")))
    }
    fn u32(&mut self) -> Result<u32, Refusal> {
        Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4")))
    }
    fn ints(&mut self, n: usize, w: usize) -> Result<Vec<i64>, Refusal> {
        let bytes = self.take(n.checked_mul(w).ok_or_else(|| native_err("a size that overflows"))?)?;
        Ok(bytes
            .chunks_exact(w)
            .map(|c| {
                let mut b = [if c[w - 1] & 0x80 != 0 { 0xff } else { 0 }; 8];
                b[..w].copy_from_slice(c);
                i64::from_le_bytes(b)
            })
            .collect())
    }
}

// ---------------------------------------------------------------------------------------
// wsr1/1 — the WSR1 prior of exact-upscale §3.1
// ---------------------------------------------------------------------------------------

/// `layer.<i>.<part>`, `i` in plain decimal.
fn wsr_name(i: usize, part: &str) -> String {
    format!("layer.{i}.{part}")
}

fn wsr1_wants(n: usize, couts: &[u64], ks: &[u64]) -> Vec<Want> {
    let mut w = vec![want("act_hi", DType::I16, vec![1])];
    let mut cin = 3u64;
    for i in 0..n {
        let (cout, k) = (couts[i], ks[i]);
        w.push(want(wsr_name(i, "weight"), DType::I8, vec![cout, cin, k, k]));
        w.push(want(wsr_name(i, "bias"), DType::I32, vec![cout]));
        w.push(want(wsr_name(i, "mult"), DType::I32, vec![cout]));
        w.push(want(wsr_name(i, "shift"), DType::I8, vec![1]));
        cin = cout;
    }
    w
}

fn wsr1_from(b: &[u8]) -> Result<TensorSet, Refusal> {
    let mut r = Rd { b, p: 0 };
    if r.take(4).map_err(|_| native_err("bad_magic"))? != b"WSR1" {
        return Err(native_err("bad_magic"));
    }
    if r.u8().map_err(|_| native_err("truncated"))? != 1 {
        return Err(native_err("version"));
    }
    let n = r.u8()? as usize;
    let act_hi = r.u16()?;
    if !(1..=8).contains(&n) || !(1..=32767).contains(&act_hi) {
        return Err(native_err("field_range"));
    }
    let mut set = TensorSet::default();
    set.tensors.push(Tensor::from_ints("act_hi", DType::I16, vec![1], &[i64::from(act_hi)]));
    let mut cin = 3u64;
    for i in 0..n {
        let (k, shift, cout) = (r.u8()?, r.u8()?, u64::from(r.u16()?));
        let last = i + 1 == n;
        let cout_ok = if last { cout == 12 } else { (1..=64).contains(&cout) };
        if !matches!(k, 1 | 3 | 5) || shift > 31 || !cout_ok {
            return Err(native_err("field_range"));
        }
        let k = u64::from(k);
        let w = r.ints((cout * cin * k * k) as usize, 1)?;
        let bias = r.ints(cout as usize, 4)?;
        let mult: Vec<i64> = r.take(2 * cout as usize)?.as_chunks::<2>().0.iter().map(|c| i64::from(u16::from_le_bytes(*c))).collect();
        if mult.contains(&0) {
            return Err(native_err("field_range"));
        }
        set.tensors.push(Tensor::from_ints(&wsr_name(i, "weight"), DType::I8, vec![cout, cin, k, k], &w));
        set.tensors.push(Tensor::from_ints(&wsr_name(i, "bias"), DType::I32, vec![cout], &bias));
        set.tensors.push(Tensor::from_ints(&wsr_name(i, "mult"), DType::I32, vec![cout], &mult));
        set.tensors.push(Tensor::from_ints(&wsr_name(i, "shift"), DType::I8, vec![1], &[i64::from(shift)]));
        cin = cout;
    }
    if r.p != b.len() {
        return Err(native_err("trailing"));
    }
    Ok(set.sorted())
}

fn wsr1_to(set: &TensorSet, form: Form) -> Result<Vec<u8>, Refusal> {
    let n = indices(set, "layer.", ".weight", None).len();
    let idx = indices(set, "layer.", ".weight", None);
    if !(1..=8).contains(&n) || idx != (0..n).collect::<Vec<_>>() {
        return refuse("binding_mismatch", format!("layers {idx:?}: wsr1/1 has layers 0 to n − 1, n from 1 to 8"));
    }
    // The shapes the binding gives follow from the weights' own: cout and k from each
    // weight, cin from the layer before; each must also be a shape exact-upscale admits.
    let (mut couts, mut ks) = (Vec::new(), Vec::new());
    for i in 0..n {
        let t = set.get(&wsr_name(i, "weight")).expect("indexed");
        let (cout, k) = (t.shape.first().copied().unwrap_or(0), t.shape.last().copied().unwrap_or(0));
        let cout_ok = if i + 1 == n { cout == 12 } else { (1..=64).contains(&cout) };
        if !matches!(k, 1 | 3 | 5) || !cout_ok {
            return refuse("binding_mismatch", format!("{}: shape {:?} (k 1, 3 or 5; cout 1 to 64, 12 in the last layer)", t.name, t.shape));
        }
        couts.push(cout);
        ks.push(k);
    }
    let wants = wsr1_wants(n, &couts, &ks);
    let range = |name: &str, _i: usize| -> Option<(i64, i64)> {
        if name == "act_hi" {
            Some((1, 32767))
        } else if name.ends_with(".mult") {
            Some((1, 65535))
        } else if name.ends_with(".shift") {
            Some((0, 31))
        } else {
            None
        }
    };
    let v = check(set, form, &wants, &range)?;
    let mut o = b"WSR1".to_vec();
    o.push(1);
    o.push(n as u8);
    o.extend_from_slice(&(v["act_hi"][0] as u16).to_le_bytes());
    for i in 0..n {
        o.extend_from_slice(&[ks[i] as u8, v[&wsr_name(i, "shift")][0] as u8]);
        o.extend_from_slice(&(couts[i] as u16).to_le_bytes());
        o.extend(v[&wsr_name(i, "weight")].iter().map(|&x| x as i8 as u8));
        for &x in &v[&wsr_name(i, "bias")] {
            o.extend_from_slice(&(x as i32).to_le_bytes());
        }
        for &x in &v[&wsr_name(i, "mult")] {
            o.extend_from_slice(&(x as u16).to_le_bytes());
        }
    }
    Ok(o)
}

// ---------------------------------------------------------------------------------------
// whm1/1 — the WHM1 model of integer-payloads §9
// ---------------------------------------------------------------------------------------

/// The most layers `whm1/1` carries: a layer index has three digits.
pub const WHM1_MAX_LAYERS: usize = 1000;

fn whm_name(i: usize, part: &str) -> String {
    format!("layer.{i:03}.{part}")
}

/// The parts that name a layer's kind, in tag order.
const WHM_KINDS: [&str; 5] = ["convt", "conv", "igdn", "relu", "leaky"];

const U32_MAX: i64 = u32::MAX as i64;

fn whm1_from(b: &[u8]) -> Result<TensorSet, Refusal> {
    let mut r = Rd { b, p: 0 };
    if r.take(4).map_err(|_| native_err("bad model magic (want WHM1)"))? != b"WHM1" {
        return Err(native_err("bad model magic (want WHM1)"));
    }
    let (afrac, gf, shift, n) = (r.u32()?, r.u32()?, r.u32()?, r.u32()? as usize);
    if n > WHM1_MAX_LAYERS {
        return refuse("binding_mismatch", format!("{n} layers; whm1/1 carries at most {WHM1_MAX_LAYERS}"));
    }
    let mut set = TensorSet::default();
    set.tensors.push(Tensor::from_ints("header", DType::I64, vec![3], &[afrac.into(), gf.into(), shift.into()]));
    let nonzero = |dims: &[u64]| -> Result<(), Refusal> {
        if dims.contains(&0) {
            return refuse("binding_mismatch", "a layer with a zero dimension, which no form carries as a tensor");
        }
        Ok(())
    };
    for i in 0..n {
        match r.u8()? {
            t @ (0 | 1) => {
                let (inc, out, k, stride, pad) = (r.u32()?, r.u32()?, r.u32()?, r.u32()?, r.u32()?);
                let opad = if t == 0 { Some(r.u32()?) } else { None };
                let (inc, out, k) = (u64::from(inc), u64::from(out), u64::from(k));
                nonzero(&[inc, out, k])?;
                let count = inc.checked_mul(out).and_then(|v| v.checked_mul(k)).and_then(|v| v.checked_mul(k)).ok_or_else(|| native_err("layer size overflows"))?;
                let w = r.ints(count as usize, 2)?;
                let mult = r.ints(out as usize, 8)?;
                let bias = r.ints(out as usize, 8)?;
                let mut geom = vec![inc as i64, out as i64, k as i64, stride.into(), pad.into()];
                let (kind, wshape) = if let Some(op) = opad {
                    geom.push(op.into());
                    ("convt", vec![inc, out, k, k])
                } else {
                    ("conv", vec![out, inc, k, k])
                };
                set.tensors.push(Tensor::from_ints(&whm_name(i, kind), DType::I64, vec![geom.len() as u64], &geom));
                set.tensors.push(Tensor::from_ints(&whm_name(i, "weight"), DType::I16, wshape, &w));
                set.tensors.push(Tensor::from_ints(&whm_name(i, "mult"), DType::I64, vec![out], &mult));
                set.tensors.push(Tensor::from_ints(&whm_name(i, "bias"), DType::I64, vec![out], &bias));
            }
            2 => {
                let c = u64::from(r.u32()?);
                nonzero(&[c])?;
                let gamma = r.ints(c.checked_mul(c).ok_or_else(|| native_err("layer size overflows"))? as usize, 4)?;
                let beta = r.ints(c as usize, 8)?;
                set.tensors.push(Tensor::from_ints(&whm_name(i, "igdn"), DType::I64, vec![1], &[c as i64]));
                set.tensors.push(Tensor::from_ints(&whm_name(i, "gamma"), DType::I32, vec![c, c], &gamma));
                set.tensors.push(Tensor::from_ints(&whm_name(i, "beta"), DType::I64, vec![c], &beta));
            }
            3 => set.tensors.push(Tensor::from_ints(&whm_name(i, "relu"), DType::I8, vec![1], &[0])),
            4 => {
                let q = r.ints(1, 8)?[0];
                let frac = r.u32()?;
                set.tensors.push(Tensor::from_ints(&whm_name(i, "leaky"), DType::I64, vec![2], &[q, frac.into()]));
            }
            _ => return Err(native_err("bad layer tag")),
        }
    }
    if r.p != b.len() {
        return Err(native_err("bytes follow the last layer"));
    }
    Ok(set.sorted())
}

fn whm1_to(set: &TensorSet, form: Form) -> Result<Vec<u8>, Refusal> {
    // The layers: each index holds exactly one kind tensor; indices 0 to n − 1.
    let mut kinds: BTreeMap<usize, &str> = BTreeMap::new();
    for kind in WHM_KINDS {
        for i in indices(set, "layer.", &format!(".{kind}"), Some(3)) {
            if kinds.insert(i, kind).is_some() {
                return refuse("binding_mismatch", format!("layer {i:03} has two kinds"));
            }
        }
    }
    let n = kinds.len();
    if kinds.keys().copied().ne(0..n) {
        return refuse("binding_mismatch", format!("layers {:?}: whm1/1 has layers 000 to n − 1", kinds.keys().collect::<Vec<_>>()));
    }
    // The geometry first, from each kind tensor, so the shapes of the rest follow from it.
    let geom = |i: usize, kind: &str, len: u64| -> Result<Vec<i64>, Refusal> {
        let t = set.get(&whm_name(i, kind)).expect("indexed");
        let dt = if form == Form::Nnc { DType::I32 } else { DType::I64 };
        if t.dtype != dt || t.shape != vec![len] {
            return refuse("binding_mismatch", format!("{:?} is {:?} {:?}, the binding gives {dt:?} [{len}]", t.name, t.dtype, t.shape));
        }
        Ok(t.ints().expect("integer"))
    };
    let mut wants = vec![want("header", DType::I64, vec![3])];
    let mut dims: Vec<Vec<i64>> = Vec::new();
    for (&i, &kind) in &kinds {
        let len = match kind {
            "convt" => 6,
            "conv" => 5,
            "igdn" => 1,
            "relu" => 1,
            _ => 2,
        };
        if kind == "relu" {
            wants.push(want(whm_name(i, "relu"), DType::I8, vec![1]));
            dims.push(vec![]);
            continue;
        }
        let g = geom(i, kind, len)?;
        let pos = |x: i64| -> Result<u64, Refusal> {
            if (1..=U32_MAX).contains(&x) { Ok(x as u64) } else { refuse("value_out_of_range", format!("{}: a dimension {x}, outside 1..=4294967295", whm_name(i, kind))) }
        };
        match kind {
            "convt" | "conv" => {
                let (inc, out, k) = (pos(g[0])?, pos(g[1])?, pos(g[2])?);
                wants.push(want(whm_name(i, kind), DType::I64, vec![len]));
                let ws = if kind == "convt" { vec![inc, out, k, k] } else { vec![out, inc, k, k] };
                wants.push(want(whm_name(i, "weight"), DType::I16, ws));
                wants.push(want(whm_name(i, "mult"), DType::I64, vec![out]));
                wants.push(want(whm_name(i, "bias"), DType::I64, vec![out]));
            }
            "igdn" => {
                let c = pos(g[0])?;
                wants.push(want(whm_name(i, "igdn"), DType::I64, vec![1]));
                wants.push(want(whm_name(i, "gamma"), DType::I32, vec![c, c]));
                wants.push(want(whm_name(i, "beta"), DType::I64, vec![c]));
            }
            _ => wants.push(want(whm_name(i, "leaky"), DType::I64, vec![2])),
        }
        dims.push(g);
    }
    let range = |name: &str, i: usize| -> Option<(i64, i64)> {
        if name == "header" {
            Some((0, U32_MAX))
        } else if name.ends_with(".convt") || name.ends_with(".conv") || name.ends_with(".igdn") {
            Some(if i < 3 || name.ends_with(".igdn") { (1, U32_MAX) } else { (0, U32_MAX) })
        } else if name.ends_with(".relu") {
            Some((0, 0))
        } else if name.ends_with(".leaky") && i == 1 {
            Some((0, U32_MAX))
        } else {
            None
        }
    };
    let v = check(set, form, &wants, &range)?;
    let mut o = b"WHM1".to_vec();
    for &x in &v["header"] {
        o.extend_from_slice(&(x as u32).to_le_bytes());
    }
    o.extend_from_slice(&(n as u32).to_le_bytes());
    let put = |o: &mut Vec<u8>, vals: &[i64], w: usize| {
        for &x in vals {
            o.extend_from_slice(&x.to_le_bytes()[..w]);
        }
    };
    for (&i, &kind) in &kinds {
        match kind {
            "convt" | "conv" => {
                o.push(if kind == "convt" { 0 } else { 1 });
                for &x in &v[&whm_name(i, kind)] {
                    o.extend_from_slice(&(x as u32).to_le_bytes());
                }
                put(&mut o, &v[&whm_name(i, "weight")], 2);
                put(&mut o, &v[&whm_name(i, "mult")], 8);
                put(&mut o, &v[&whm_name(i, "bias")], 8);
            }
            "igdn" => {
                o.push(2);
                o.extend_from_slice(&(v[&whm_name(i, "igdn")][0] as u32).to_le_bytes());
                put(&mut o, &v[&whm_name(i, "gamma")], 4);
                put(&mut o, &v[&whm_name(i, "beta")], 8);
            }
            "relu" => o.push(3),
            _ => {
                o.push(4);
                let l = &v[&whm_name(i, "leaky")];
                o.extend_from_slice(&l[0].to_le_bytes());
                o.extend_from_slice(&(l[1] as u32).to_le_bytes());
            }
        }
    }
    let _ = dims;
    Ok(o)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prior_wire::{encode, load};

    fn tiny_wsr() -> Vec<u8> {
        let mut o = b"WSR1".to_vec();
        o.extend_from_slice(&[1, 1]);
        o.extend_from_slice(&200u16.to_le_bytes());
        o.extend_from_slice(&[1, 7]);
        o.extend_from_slice(&12u16.to_le_bytes());
        o.extend((0..36).map(|i| (i as i8 - 18) as u8));
        for i in 0..12i32 {
            o.extend_from_slice(&(i * 1000 - 6000).to_le_bytes());
        }
        for i in 0..12u16 {
            o.extend_from_slice(&(i * 5000 + 1).to_le_bytes());
        }
        o
    }

    fn tiny_whm() -> Vec<u8> {
        let mut o = b"WHM1".to_vec();
        for v in [12u32, 16, 24, 4] {
            o.extend_from_slice(&v.to_le_bytes());
        }
        // conv 2 → 3, k 1
        o.push(1);
        for v in [2u32, 3, 1, 1, 0] {
            o.extend_from_slice(&v.to_le_bytes());
        }
        for w in [1i16, -2, 3, -4, 5, -6] {
            o.extend_from_slice(&w.to_le_bytes());
        }
        for m in [100i64, 200, 300, -1, -2, -3] {
            o.extend_from_slice(&m.to_le_bytes());
        }
        o.push(3);
        o.push(2);
        o.extend_from_slice(&3u32.to_le_bytes());
        for g in 0..9i32 {
            o.extend_from_slice(&(g * 7).to_le_bytes());
        }
        for b in [1i64, 2, 3] {
            o.extend_from_slice(&b.to_le_bytes());
        }
        o.push(4);
        o.extend_from_slice(&655i64.to_le_bytes());
        o.extend_from_slice(&16u32.to_le_bytes());
        o
    }

    #[test]
    fn every_binding_round_trips_through_every_form() {
        for (b, native) in [("wsr1/1", tiny_wsr()), ("whm1/1", tiny_whm())] {
            for form in Form::ALL {
                let file = encode(b, &native, form).unwrap();
                let (name, back) = load(form, &file).unwrap();
                assert_eq!((name, &back), (b, &native), "{b} in {}", form.label());
            }
        }
    }

    #[test]
    fn the_profile_checks_run_in_order() {
        let native = tiny_wsr();
        let set = |f: &dyn Fn(&mut TensorSet)| {
            let mut s = wsr1_from(&native).unwrap();
            s.metadata = profile_metadata("wsr1/1", Form::Safetensors);
            f(&mut s);
            crate::prior_wire::safetensors::write(&s).unwrap()
        };
        let code = |b: Vec<u8>| load(Form::Safetensors, &b).err().map(|r| r.code);
        assert_eq!(code(set(&|_| {})), None);
        assert_eq!(code(set(&|s| { s.metadata.remove(KEY_PROFILE); })), Some("profile_absent"));
        assert_eq!(code(set(&|s| { s.metadata.insert(KEY_BINDING.into(), "nope/1".into()); })), Some("binding_unknown"));
        assert_eq!(code(set(&|s| { s.tensors[0].dtype = DType::F32; s.tensors[0].data = vec![0; 4]; })), Some("dtype_not_integer"));
        assert_eq!(code(set(&|s| { s.tensors.pop(); })), Some("binding_mismatch"));
        assert_eq!(code(set(&|s| { let t = s.tensors.iter_mut().find(|t| t.name == "layer.0.shift").unwrap(); t.data = vec![40]; })), Some("value_out_of_range"));
        assert_eq!(code(set(&|s| { let t = s.tensors.iter_mut().find(|t| t.name == "layer.0.mult").unwrap(); t.data[..4].copy_from_slice(&0i32.to_le_bytes()); })), Some("value_out_of_range"));
    }

    #[test]
    fn a_native_artifact_that_does_not_read_is_named() {
        let mut bad = tiny_wsr();
        bad.push(0);
        assert_eq!(encode("wsr1/1", &bad, Form::Gguf).unwrap_err().code, "native_malformed");
        assert_eq!(encode("whm1/1", b"WHMX", Form::Gguf).unwrap_err().code, "native_malformed");
    }
}
