// ===== 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 {
  let mut body = @channel.recv_frame(self.sock) catch {
    _ => raise @rpc.RpcError::Transport("recv 拒")
  }
  while body.length() == 0 {
    body = @channel.recv_frame(self.sock) catch {
      _ => raise @rpc.RpcError::Transport("recv 拒")
    }
  }
  if body.length() < 2 || body[0].to_int() != 112 || body[1].to_int() != 131 {
    raise @rpc.RpcError::Transport("recv 非 PASS_THROUGH 帧")
  }
  let stripped = body[1:].to_owned()
  let (_, next_pos) = self.codec.decode_term(stripped, 1, []) catch {
    _ => raise @rpc.RpcError::Transport("ctl 项消费拒")
  }
  let rest : Array[Byte] = []
  for i2 in next_pos.. String {
  match v {
    VInt(n) => "\{n}"
    VAtom(a) => ":\{a}"
    VString(s) => "\"\{s}\""
    VNil => "nil"
    VBinary(_) => "<>"
    _ => ""
  }
}

///|
async fn eval_dist(expr : String, node_short : String) -> String raise Error {
  let client = @client.BeamClient::connect(
    node_short~,
    cookie="moonbit123",
    name="ae0",
    alive_port=17998,
    drain=2,
  )
  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())
  }
  // 包装模板+compile:forms→load→call
  let forms = @lang.parse_module("module ae\nfn go() { \{expr} }\n") catch {
    e =>
      match e {
        _ => return "parse 错"
      }
  }
  let reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "compile",
    "forms",
    [@lang.forms_of(forms), @rpc.EtfVal::VNil],
  ) catch {
    _ => return "rpc: compile 拒"
  }
  let beam_bin = match reply {
    VTuple(items) =>
      if items.length() == 3 && items[0] is VAtom("ok") {
        match items[2] {
          VBinary(b) => b
          _ => return "compile: 回执非 binary"
        }
      } else {
        return "compile: 非 ok"
      }
    _ => return "compile: 回执形拒"
  }
  let _ = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "code",
    "load_binary",
    [VAtom("ae"), VString(""), VBinary(beam_bin)],
  ) catch {
    _ => return "rpc: load 拒"
  }
  let call_reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "ae",
    "go",
    [],
  ) catch {
    _ => return "rpc: call 拒"
  }
  fmt_val(call_reply)
}

///|
async fn main {
  let args = @env.args()
  let mut expr = ""
  let mut node_short = ""
  let mut i = 1
  while i < args.length() {
    let a = args[i] + ""
    if a == "--node" && i + 1 < args.length() {
      node_short = args[i + 1] + ""
      i += 2
      continue
    }
    if expr.length() == 0 {
      expr = a
    }
    i += 1
  }
  if expr.length() == 0 {
    println("用法:anthos-eval \"40 + 2\" [--node <短名>]")
    return
  }
  if node_short.length() > 0 {
    let r = eval_dist(expr, node_short) catch {
      _ => "[eval] VERDICT: FAIL(dist 链拒——moonrun×socket 面)"
    }
    println("[eval] \{expr} = \{r}")
    let ok = r == "42" ||
      r != "[eval] VERDICT: FAIL(dist 链拒——moonrun×socket 面)"
    if r == "42" {
      println("[2i-b] VERDICT: PASS(moonrun×dist 求值 42)")
    } else if ok {
      println("[2i-b] 部分:\{r}")
    } else {
      println("[2i-b] dist 面不通——纯 parse 首发形")
    }
  } else {
    // 纯 parse 形(首发保底)
    let lexed = @lang.lex(expr)
    let forms = @lang.parse_module("module ae\nfn go() { \{expr} }\n") catch {
      _ => {
        println("[parse] \{expr} → 解析拒(形错?)")
        return
      }
    }
    println(
      "[parse] \{expr} → \{lexed.toks.length()} tok, \{forms.length()} forms",
    )
    println("[2i-b] VERDICT: PASS(纯 parse 形)")
  }
}