// ===== encode:EtfTerm → ETF 字节流(带 VERSION_MAGIC)=====
// 规范形输出:atom→'w'(SMALL_ATOM_UTF8,OTP26 主形);float→'F';list→108+106;
// 整数→97(<256)/98;pid→'X';ref→'Z'(creation u32)。

///|
pub fn encode(t : EtfTerm) -> Bytes raise EtfError {
  let out : Array[Byte] = [VERSION_MAGIC.to_byte()]
  encode_term(t, out)
  Bytes::from_array(out)
}

///|
/// 段内编码(无 magic):组合用
pub fn encode_term(t : EtfTerm, out : Array[Byte]) -> Unit raise EtfError {
  match t {
    EtfTerm::EExport(m, f, a) => {
      out.push(TAG_EXPORT_EXT.to_byte())
      encode_term(EtfTerm::EAtom(m), out)
      encode_term(EtfTerm::EAtom(f), out)
      out.push((97).to_byte())
      out.push(a.to_byte())
    }
    EtfTerm::EOther(kind) =>
      raise EtfError::Malformed(
        "EOther(\{kind}) 不可编码——跳段直通仅 decode 侧",
      )
    EtfTerm::EAtom(s) => encode_atom(s, out)
    EtfTerm::EInt(v) =>
      if v >= 0 && v < 256 {
        out.push(TAG_SMALL_INTEGER.to_byte())
        out.push((v & 255).to_byte())
      } else if v >= 0 {
        out.push(TAG_INTEGER.to_byte())
        put_u32(out, v)
      } else {
        // 负值=110 SMALL_BIG(sign=1+绝对值最小字节 LE)——真 Erlang 形
        // (金罐铁证:term_to_binary(-7)=131,110,1,1,7——nbytes=最小非零字节;
        //  98 补码形退役——encode/decode 对称残修复 2026-11-11;
        //  min_int32 的 abs 在 Int64 域算——不溢出)
        let mag64 = -v.to_int64()
        out.push(TAG_SMALL_BIG.to_byte())
        let mut nbytes = 0
        let mut probe = mag64
        while probe > 0L {
          nbytes += 1
          probe = probe >> 8
        }
        out.push(nbytes.to_byte())
        out.push((1).to_byte()) // sign=1
        for i in 0..> (8 * i)) & 0xFFL).to_int().to_byte())
        }
      }
    EtfTerm::EInt64(w) => {
      // sign=1=负(OTP 铁证同款)——负值=sign 1+绝对值 LE(Int64 域
      // min_int64 边界诚实拒——绝对值溢出域)
      let mag = if w < 0L {
        let m = -w
        if m < 0L {
          raise EtfError::Malformed("EInt64 min 边界 encode 候")
        }
        m
      } else {
        w
      }
      out.push(TAG_SMALL_BIG.to_byte())
      out.push((8).to_byte())
      out.push(if w < 0L { (1).to_byte() } else { (0).to_byte() })
      for i in 0..<8 {
        out.push(((mag >> (8 * i)) & 0xFFL).to_int().to_byte())
      }
    }
    EtfTerm::EFloat(f) => {
      out.push(TAG_NEW_FLOAT.to_byte())
      put_u64(out, f.reinterpret_as_uint64())
    }
    EtfTerm::ETuple(items) => {
      out.push(TAG_SMALL_TUPLE.to_byte())
      out.push(items.length().to_byte())
      for it in items {
        encode_term(it, out)
      }
    }
    EtfTerm::EImproperList(items, tail) => {
      // 108 LIST:count|items|尾项(无 NIL——improper 回写正形;
      // [alias|Ref] 族 OTP24+ gen Tag 回写)
      out.push(TAG_LIST.to_byte())
      put_u32(out, items.length())
      for it in items {
        encode_term(it, out)
      }
      encode_term(tail, out)
    }
    EtfTerm::EList(items) =>
      if items.length() == 0 {
        // 空表=106 NIL 直形(ETF 规范——erl term_to_binary([])=131,106;
        // 真帧对拍 2026-11-07:spawn_ctl 真帧 ArgList=[]=6a 直形;
        // 108+0+106 形被 dist decode 判 corrupted)
        out.push(TAG_NIL.to_byte())
      } else {
        out.push(TAG_LIST.to_byte())
        put_u32(out, items.length())
        for it in items {
          encode_term(it, out)
        }
        out.push(TAG_NIL.to_byte())
      }
    EtfTerm::ENil => out.push(TAG_NIL.to_byte())
    EtfTerm::EString(s) => {
      out.push(TAG_STRING.to_byte())
      put_u16(out, s.length())
      for ch in s {
        out.push((ch.to_int() & 255).to_byte())
      }
    }
    EtfTerm::EBinary(b) => {
      out.push(TAG_BINARY.to_byte())
      put_u32(out, b.length())
      for byte in b {
        out.push(byte)
      }
    }
    EtfTerm::EMap(pairs) => {
      out.push(TAG_MAP.to_byte())
      put_u32(out, pairs.length())
      for pair in pairs {
        encode_term(pair.0, out)
        encode_term(pair.1, out)
      }
    }
    EtfTerm::EPid(node, id, serial, creation) => {
      out.push(TAG_NEW_PID.to_byte())
      encode_atom(node, out)
      put_u32(out, id)
      put_u32(out, serial)
      put_u32(out, creation)
    }
    EtfTerm::EPort(node, id, creation) => {
      out.push(TAG_NEW_PORT.to_byte())
      encode_atom(node, out)
      put_u32(out, id)
      put_u32(out, creation)
    }
    EtfTerm::ERef(node, id, _, creation) => {
      // 'Z' NEWER_REFERENCE:idlen=1(骨架 v0 单字 id)
      out.push(TAG_NEWER_REFERENCE.to_byte())
      put_u16(out, 1)
      encode_atom(node, out)
      put_u32(out, creation)
      put_u32(out, id)
    }
  }
}

///|
/// atom 规范形:'w'(len u8;>255 退 'v' len u16)
fn encode_atom(s : String, out : Array[Byte]) -> Unit raise EtfError {
  let n = s.length()
  if n < 256 {
    out.push(TAG_SMALL_ATOM_UTF8.to_byte())
    out.push(n.to_byte())
  } else {
    out.push(TAG_ATOM_UTF8.to_byte())
    put_u16(out, n)
  }
  for ch in s {
    let code = ch.to_int()
    if code > 255 {
      raise EtfError::Malformed("atom 非 latin1 域(骨架 v0)")
    }
    out.push((code & 255).to_byte())
  }
}

///|
fn put_u16(out : Array[Byte], v : Int32) -> Unit {
  out.push(((v >> 8) & 255).to_byte())
  out.push((v & 255).to_byte())
}

///|
fn put_u32(out : Array[Byte], v : Int32) -> Unit {
  out.push(((v >> 24) & 255).to_byte())
  out.push(((v >> 16) & 255).to_byte())
  out.push(((v >> 8) & 255).to_byte())
  out.push((v & 255).to_byte())
}

///|
fn put_u64(out : Array[Byte], v : UInt64) -> Unit {
  for k in 0..<8 {
    let sh = 56 - k * 8
    out.push(((v >> sh).to_int() & 255).to_byte())
  }
}