// ===== 控制消息解码面(dop 分派)=====
// 帧形(规格书 §4):u32 len(BE) | 0x83 | ['D' atom-cache 段头(可省)] | ETF 项流
//   控制项流首项 = Int tag → dop 词表分派(dop_gen 封闭查表);后续项 = 参数流。
// 六边形:ETF 项解码藏 EtfPort 注入后(moonbit-eetf 组合根 impl)——
//   beam-dist 核心零 eetf 依赖;字节级项解码=组合根役(真件深化候)。
// 'D' 段头:A8 全规格 wire='D'|no_atoms u8|位图|指令段——v0 收 no_atoms=0
//   简形(现役 encode 对称形);非空段诚实拒(全规格接线=A8 真件役,禁静默吞)。

///|
pub(all) suberror ControlError {
  ShortFrame(String) // 帧截断/起头非 83
  UnknownDop(Int32) // tag 不在词表(封闭拒)
  BadTag(String) // 首项非整数(控制项流首项=tag 契约)
  CacheSegment(String) // 'D' 非空段(v0 诚实拒——A8 真件役候)
  Codec(String) // ETF 项解码错(EtfPort 转译)
}

///|
/// ETF 项值(控制面所需子集——beam-dist 自持,eetf 组合根映射;
/// 不 import eetf——六边形归位)
pub(all) enum EtfItem {
  IAtom(String)
  IInt(Int32)
  IPid(String, Int32, Int32, Int32) // node, id, serial, creation
  IRef(String, Int32, Int32) // node, id 序列长, creation
  ITuple(Array[EtfItem])
  IList(Array[EtfItem])
  INil
  IBinary(Bytes)
  IOther // 其余项型(骨架占位——float/map/big 等直通)
}

///|
/// ETF 项解码注入位(组合根=moonbit-eetf impl;decode 一项推进一位)
pub(open) trait EtfPort {
  fn decode_term(self : Self, bytes : Bytes, pos : Int32) -> (EtfItem, Int32) raise ControlError
}

///|
/// 控制消息(tag+词表名+语义动词+参数项流)
pub(all) struct ControlMsg {
  tag : Int32
  name : String
  semantics : String
  items : Array[EtfItem]
}

///|
/// 'D' atom-cache 段头跳过(v0 简形:no_atoms=0 整块无位图;非空段诚实拒)。
/// 返回 ETF 项流起始 pos。frame 裸流(83 起);pos 指向 0x83 后。
fn skip_cache_segment(frame : Bytes, pos : Int32) -> Int32 raise ControlError {
  if pos >= frame.length() || frame[pos].to_int() != 68 {
    // 非 'D'——无段头,原位直过
    return pos
  }
  if pos + 1 >= frame.length() {
    raise ControlError::ShortFrame("'D' 段头截断")
  }
  let no_atoms = frame[pos + 1].to_int()
  if no_atoms == 0 {
    // 简形:'D' 00——整块无位图(A8 勘定:FLAG_BYTES(0) 死区)
    return pos + 2
  }
  raise ControlError::CacheSegment(
    "非空 'D' 段(no_atoms=\{no_atoms})候 A8 真件役",
  )
}

///|
/// 控制帧解码:83 起头核+['D' 段头跳]+首项 tag 分派+参数项流收集。
/// frame = 裸 ETF 流(传输面剥 u32 len 后交付——线形守恒)。
pub fn decode_control(
  frame : Bytes,
  etf : &EtfPort,
) -> ControlMsg raise ControlError {
  if frame.length() < 2 || frame[0].to_int() != 131 {
    raise ControlError::ShortFrame("起头非 VERSION_MAGIC(131)")
  }
  let stream_pos = skip_cache_segment(frame, 1)
  let (first, next_pos) = etf.decode_term(frame, stream_pos)
  let tag = match first {
    IInt(v) => v
    _ => raise ControlError::BadTag("控制项流首项须整数 tag")
  }
  let name = match dop_name_of(tag) {
    Some(found) => found
    None => raise ControlError::UnknownDop(tag)
  }
  let semantics = match dop_semantics_of(tag) {
    Some(found) => found
    // 词表封闭守恒:name 命中而 semantics 缺=词表违(镜像罐防)
    None => raise ControlError::UnknownDop(tag)
  }
  let items : Array[EtfItem] = []
  let mut pos = next_pos
  while pos < frame.length() {
    let (item, next) = etf.decode_term(frame, pos)
    items.push(item)
    pos = next
  }
  ControlMsg::{ tag, name, semantics, items, }
}

///|
/// 控制错误文本面(show 手写——零 derive 守恒)
pub fn show_control_error(e : ControlError) -> String {
  match e {
    ControlError::ShortFrame(m) => "ShortFrame(\{m})"
    ControlError::UnknownDop(tag) => "UnknownDop(\{tag})"
    ControlError::BadTag(m) => "BadTag(\{m})"
    ControlError::CacheSegment(m) => "CacheSegment(\{m})"
    ControlError::Codec(m) => "Codec(\{m})"
  }
}