// ===== anthos-eval:moonanthos 单发求值(moonx 形) =====
// 用法:moonx thy1016/anthos-eval "40 + 2"           ← 纯 parse 形(token/AST dump)
//      moonx thy1016/anthos-eval "40 + 2" --node P  ← dist 求值形(远端 beam eval)
// 首刀验证面=moonrun×dist(茗篇坑预判①——不通则纯 parse 首发候二版)

///|
/// rpc 通道(mooniex 已证形:'p' 前缀+tick 跳+ctl 消费)
struct EvalRpcPort {
  sock : @socket.Tcp
  codec : &@dist.EtfPort
}

///|
impl @rpc.RpcPort for EvalRpcPort with fn send(
  self,
  node : String,
  frame : Bytes,
) -> Unit raise @rpc.RpcError {
  let out : Array[Byte] = [0x70]
  for i in 0.. raise @rpc.RpcError::Transport("send 拒")
  }
}

///|
impl @rpc.RpcPort for EvalRpcPort with fn recv(self) -> Bytes raise @rpc.RpcError {
  // drain 收:空 tick/非 'p' 帧/'p' 但 msg 项非 {Ref,Reply} 形(EXIT/io
  // 协议等信号)全跳——只放行真回执(runtime_concurrency 茧篇地基案:
  // spawn 的输出经 group_leader 路由回本连接,信号与回执共享通道;
  // 探针实证 EXIT 形 'p' 帧混入——msg 首元 VRef 才是回执判据)
  let mut result : Bytes? = None
  while result is None {
    let body = @channel.recv_frame(self.sock) catch {
      _ => raise @rpc.RpcError::Transport("recv 拒")
    }
    if body.length() == 0 {
      continue
    }
    if body.length() < 2 || body[0].to_int() != 112 || body[1].to_int() != 131 {
      continue
    }
    let stripped = body[1:].to_owned()
    let ctl_dec = self.codec.decode_term(stripped, 1, []) catch {
      _ => continue
    }
    let next_pos = ctl_dec.1
    // ctl 判:tag 22(SEND_SENDER)={22,FromPid,ToPid}+msg——**rex reply
    // 投递实形**(dop_gen 词表直书,probe dump 铁证 2026-11-07);io 类
    // 信号(tag 6 REG_SEND 到 user/无名)全 drain;ref 精核在 parse_reply
    let is_reply_ctl = match ctl_dec.0 {
      @dist.EtfItem::ITuple(items) =>
        items.length() >= 1 && items[0] is IInt(22)
      _ => false
    }
    if !is_reply_ctl {
      continue
    }
    if next_pos >= stripped.length() {
      continue
    }
    let rest : Array[Byte] = []
    for i2 in next_pos.. continue
    }
    let msg_val = msg_dec.0
    match msg_val {
      @dist.EtfItem::ITuple(items) =>
        if items.length() == 2 {
          result = Some(msg_bytes)
        }
      _ => ()
    }
  }
  match result {
    Some(b) => b
    None => raise @rpc.RpcError::Transport("recv 无回执")
  }
}

///|
/// 回执值→串(Erlang 打印形官方渲染)
fn fmt_val(v : @rpc.EtfVal) -> String {
  match v {
    VInt(n) => "\{n}"
    VAtom(a) => a
    VString(sv) => "\"\{escape_str(sv)}\""
    VNil => "[]"
    VFloat(d) => "\{d}"
    VTuple(items) => "{" + join_vals(items) + "}"
    VList(items) => "[" + join_vals(items) + "]"
    VBinary(b) => fmt_binary(b)
    VMap(pairs) => fmt_map(pairs)
    VPid(_node, id, ser, cre) => "<\{id}.\{ser}.\{cre}>"
    VPort(_node, id, _cre) => "#Port<\{id}>"
    VRef(_node, id, ser, cre) => "#Ref<\{id}.\{ser}.\{cre}>"
    VOther(desc) => "<\{desc}>"
  }
}

///|
/// 值列表拼接(", " 分隔,递归渲染)
fn join_vals(items : Array[@rpc.EtfVal]) -> String {
  let parts : Array[String] = []
  for i in items {
    let _ = parts.push(fmt_val(i))
  }
  parts.join(", ")
}

///|
/// binary 渲染(前 16 字节,超出省略)
fn fmt_binary(b : Bytes) -> String {
  let parts : Array[String] = []
  let n = if b.length() > 16 { 16 } else { b.length() }
  for i in 0.. 16 {
    let _ = parts.push("...")
  }
  "<<\{parts.join(", ")}>>"
}

///|
/// map 渲染(#{k => v, ...})
fn fmt_map(pairs : Array[(@rpc.EtfVal, @rpc.EtfVal)]) -> String {
  let parts : Array[String] = []
  for p in pairs {
    let (k, val) = p
    let _ = parts.push("\{fmt_val(k)} => \{fmt_val(val)}")
  }
  "#{" + parts.join(", ") + "}"
}

///|
/// CLI 版本位(与 moon.mod version 同步改——发布两处纪律)
const VERSION : String = "0.5.8"

///|
async fn eval_dist(
  expr : String,
  node_short : String,
  mode : String,
  modname : String,
  cookie : String,
) -> (Bool, String) raise Error {
  let client = @client.BeamClient::connect(
    node_short~,
    cookie~,
    name="ae0",
    alive_port=17998,
    drain=2,
  ) catch {
    _ =>
      return (
        false,
        "对端节点 \{node_short} 连接拒(未起?名不对?——示例:--node probea)",
      )
  }
  let codec_impl = @eetf_codec.EtfCodecEetf::new(tag=0)
  let port : &@rpc.RpcPort = EvalRpcPort::{
    sock: client.sock(),
    codec: codec_impl,
  }
  let codec : &@rpc.EtfCodec = codec_impl
  let my_full = "ae0@dev"
  let caller = @rpc.EtfVal::VPid(my_full, 1, 1, client.creation())
  let mut refi = 500
  fn next_ref() -> @rpc.EtfVal {
    refi += 1
    @rpc.EtfVal::VRef(my_full, refi, 0, client.creation())
  }
  // invoke 形:module 须已驻留——纯 call(零 compile/load)
  if mode == "invoke" {
    let r = @rpc.call(
      codec,
      port,
      node_short,
      caller~,
      ref_=next_ref(),
      modname,
      "go",
      [],
    ) catch {
      _ => return (false, "rpc: invoke 传输拒")
    }
    match r {
      VTuple(items) =>
        if items.length() >= 1 && items[0] is VAtom("badrpc") {
          return (false, badrpc_detail(items, modname))
        }
      _ => ()
    }
    return (true, fmt_val(r))
  }
  // 包装模板+compile:forms→load→(once:call/deploy:止)
  let mname = if mode == "deploy" { modname } else { "ae" }
  // 智能模板:module 级词(record/type)或自带 fn→原文模块形(export 自动
  // 派生——顶层 fn 全导出,lang MVP 派生面);否则表达式模板
  let has_module_level = expr.contains("record ") || expr.contains("type ")
  let has_fn = expr.contains("fn ")
  let src = if has_module_level || has_fn {
    "module \{mname}\n\{expr}\n"
  } else {
    "module \{mname}\nfn go() { \{expr} }\n"
  }
  let forms = @lang.parse_module(src) catch {
    e =>
      match e {
        e => {
          let msg = match e {
            Parse(m) => m
            Lex(m) => m
          }
          return (false, "parse 错: \{msg}")
        }
      }
  }
  let reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "compile",
    "forms",
    [@lang.forms_of(forms), @rpc.EtfVal::VNil],
  ) catch {
    e => {
      let d = match e {
        @rpc.RpcError::Transport(m) => "T:\{m}"
        @rpc.RpcError::BadReply(m) => "B:\{m}"
        @rpc.RpcError::Codec(m) => "C:\{m}"
        _ => "?"
      }
      return (false, "rpc: compile 拒[\{d}]")
    }
  }
  let beam_bin = match reply {
    VTuple(items) =>
      if items.length() == 3 && items[0] is VAtom("ok") {
        match items[2] {
          VBinary(b) => b
          _ => return (false, "compile: 回执非 binary")
        }
      } else {
        return (false, "compile: 非 ok(回执:\{fmt_val(reply)})")
      }
    _ => return (false, "compile: 拒(回执:\{fmt_val(reply)})")
  }
  let _ = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "code",
    "load_binary",
    [VAtom(mname), VString(""), VBinary(beam_bin)],
  ) catch {
    _ => return (false, "rpc: load 拒")
  }
  if mode == "deploy" {
    return (true, "已部署 \{mname}(invoke:--invoke \{mname})")
  }
  let call_reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    mname,
    "go",
    [],
  ) catch {
    _ => return (false, "rpc: call 拒")
  }
  match call_reply {
    VTuple(items) =>
      if items.length() >= 1 && items[0] is VAtom("badrpc") {
        return (false, badrpc_detail(items, mname))
      }
    _ => ()
  }
  (true, fmt_val(call_reply))
}

///|
async fn main {
  let args = @env.args()
  // 选项预扫:--version/-V 短路
  for ai in 0.. None }
    match d {
      Some((dn, dc)) => {
        node_short = dn
        if cookie == "moonbit123" {
          cookie = dc
        }
        println("ok: 发现文件 \{dn}(/tmp/anthos_up.node)")
      }
      None => ()
    }
  }
  if mode == "invoke" && modname.length() == 0 {
    println("error: --invoke 须带模块名(先 --deploy)")
    return
  }
  if mode != "invoke" && expr.length() == 0 {
    print_usage()
    return
  }
  // deploy 形 module 名预验:erl module 名须小写字母开头
  if mode == "deploy" {
    let cs = modname.to_array()
    if cs.length() == 0 {
      println("error: 模块名为空")
      return
    }
    let c0 = cs[0].to_int()
    if c0 < 97 || c0 > 122 {
      println("error: 模块名须以小写字母开头: \{modname}")
      return
    }
  }
  if node_short.length() == 0 && mode != "once" {
    println(
      "error: 未指定节点——先运行 anthos-up,或加 --node <短名>",
    )
    return
  }
  if node_short.length() > 0 {
    let (ok, r) = eval_dist(expr, node_short, mode, modname, cookie) catch {
      _ => (false, "dist 链内部拒")
    }
    if !ok {
      println("error: \{r}")
      return
    }
    println(r)
  } else {
    // 纯 parse 形(首发保底)
    let _forms = @lang.parse_module("module ae\nfn go() { \{expr} }\n") catch {
      _ => {
        println("error: 表达式解析拒(形错?)")
        return
      }
    }
    println("ok: 解析通过(未连节点——加 --node 远程求值)")
  }
}

///|
/// 发现文件读(/tmp/anthos_up.node:node=/pid=/cookie= 三行)
async fn read_discover() -> (String, String)? {
  let text = read_discover_text()
  if text.length() == 0 {
    return None
  }
  let mut n = ""
  let mut c = "moonbit123"
  for line in text.split("\n") {
    let ln = (line + "").to_owned()
    n = kv_of(ln, "node=", n)
    c = kv_of(ln, "cookie=", c)
  }
  if n.length() > 0 {
    Some((n, c))
  } else {
    None
  }
}

///|
async fn read_discover_text() -> String {
  let data = @fs.read_file("/tmp/anthos_up.node") catch { _ => return "" }
  @utf8.decode_lossy(data.binary()).trim().to_owned()
}

///|
/// 行=「键=值」形则取值,否则返原
fn kv_of(line : String, key : String, cur : String) -> String {
  // 逐字符前缀判+尾段拼接(零切片 API 依赖)
  if line.length() <= key.length() {
    return cur
  }
  let mut hit = true
  for i in 0.. Unit {
  println("anthos-eval \{VERSION} — moonanthos 远程求值")
  println("用法: anthos-eval [选项] <表达式>")
  println("      anthos-eval --deploy <模块> <表达式>")
  println("      anthos-eval --invoke <模块>")
  println("选项:")
  println(
    "  --node <名>      对端节点短名(缺省读 /tmp/anthos_up.node)",
  )
  println("  --cookie <串>    dist cookie(默认 moonbit123)")
  println("  --deploy <模块>  部署模块到节点")
  println("  --invoke <模块>  调用已部署模块")
  println("  --version, -V    显示版本")
  println("  --help, -h       显示帮助")
}

///|
/// 串转义(不可打印字符 \x{HH} 形——erl 打印惯例;decode 侧 list→string 面
/// 的显示诚实化)
fn escape_str(sv : String) -> String {
  let sb = StringBuilder()
  for i in 0..= 32 && c < 127 {
      sb.write_char(Int32::unsafe_to_char(c))
    } else {
      sb.write_string("\\x{")
      sb.write_string(hex_byte(c))
      sb.write_string("}")
    }
  }
  sb.to_string()
}

///|
/// 字节 hex
fn hex_byte(v : Int32) -> String {
  let hi = (v >> 4) & 15
  let lo = v & 15
  "\{hex_digit(hi)}\{hex_digit(lo)}"
}

///|
fn hex_digit(d : Int32) -> String {
  if d < 10 {
    Int32::unsafe_to_char(48 + d).to_string()
  } else {
    Int32::unsafe_to_char(87 + d).to_string()
  }
}

///|
/// badrpc 细分:undef=未部署;其余=运行时错(Reason 渲染)
fn badrpc_detail(items : Array[@rpc.EtfVal], modname : String) -> String {
  // {badrpc, {'EXIT', {Reason, Stack}}}
  let reason = if items.length() >= 2 {
    match items[1] {
      VTuple(exit_items) =>
        if exit_items.length() >= 2 && exit_items[0] is VAtom("EXIT") {
          match exit_items[1] {
            VTuple(rstk) =>
              if rstk.length() >= 1 {
                match rstk[0] {
                  VAtom("undef") => "undef"
                  VAtom(ra) => ra
                  _ => "?"
                }
              } else {
                "?"
              }
            other => fmt_val(other)
          }
        } else if exit_items.length() >= 1 {
          fmt_val(exit_items[0])
        } else {
          fmt_val(items[1])
        }
      other => fmt_val(other)
    }
  } else {
    "?"
  }
  if reason == "undef" {
    "未部署 \{modname}(先:--deploy \{modname} \"代码\")"
  } else {
    "运行时错: \{reason}(节点 \{modname} 上 go/0 崩溃——查代码边界:除零/空表等)"
  }
}