// ===== 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,
  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,
            "未部署 \{modname}(先:--deploy \{modname} \"代码\")",
          )
        }
      _ => ()
    }
    return (true, fmt_val(r))
  }
  // 包装模板+compile:forms→load→(once:call/deploy:止)
  let mname = if mode == "deploy" { modname } else { "ae" }
  let forms = @lang.parse_module("module \{mname}\nfn go() { \{expr} }\n") catch {
    e =>
      match e {
        _ => return (false, "parse 错")
      }
  }
  let reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "compile",
    "forms",
    [@lang.forms_of(forms), @rpc.EtfVal::VNil],
  ) catch {
    _ => return (false, "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 (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 拒")
  }
  (true, fmt_val(call_reply))
}

///|
async fn main {
  let args = @env.args()
  let mut expr = ""
  let mut node_short = ""
  let mut mode = "once"
  let mut modname = ""
  let mut cookie = "moonbit123"
  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 a == "--cookie" && i + 1 < args.length() {
      cookie = args[i + 1] + ""
      i += 2
      continue
    }
    if a == "--deploy" && i + 1 < args.length() {
      mode = "deploy"
      modname = args[i + 1] + ""
      i += 2
      continue
    }
    if a == "--invoke" && i + 1 < args.length() {
      mode = "invoke"
      modname = args[i + 1] + ""
      i += 2
      continue
    }
    if expr.length() == 0 {
      expr = a
    }
    i += 1
  }
  // 缺省 session:--node 未传时读发现文件(名+cookie 一体拿)
  if node_short.length() == 0 {
    let d = read_discover() catch { _ => None }
    match d {
      Some((dn, dc)) => {
        node_short = dn
        if cookie == "moonbit123" {
          cookie = dc
        }
        println("[session] 发现文件:\{dn}(省 --node/--cookie)")
      }
      None => ()
    }
  }
  if mode == "invoke" && modname.length() == 0 {
    println("用法:--invoke (须先 --deploy)")
    return
  }
  if mode != "invoke" && expr.length() == 0 {
    println(
      "用法:anthos-eval \"40 + 2\" [--node <短名>] | --deploy <名> \"代码\" --node <短名> | --invoke <名> --node <短名>",
    )
    return
  }
  // deploy 形 module 名预验:erl module 名须小写字母开头
  if mode == "deploy" {
    let cs = modname.to_array()
    if cs.length() == 0 {
      println("[deploy] module 名空")
      return
    }
    let c0 = cs[0].to_int()
    if c0 < 97 || c0 > 122 {
      println("[deploy] module 名须小写字母开头(得:\{modname})")
      return
    }
  }
  if node_short.length() > 0 {
    let (ok, r) = eval_dist(expr, node_short, mode, modname, cookie) catch {
      _ => (false, "dist 链内部拒")
    }
    let label = if mode == "invoke" {
      "[invoke] \{modname}"
    } else if mode == "deploy" {
      "[deploy] \{modname}"
    } else {
      "[eval] \{expr}"
    }
    println("\{label} = \{r}")
    if r == "42" {
      println("[2i-b] VERDICT: PASS(dist 求值 42)")
    } else if ok {
      println("[2i-b] VERDICT: PASS(\{r})")
    } else {
      println("[2i-b] 求值未成:\{r}(纯 parse 形仍可用:去掉 --node)")
    }
  } 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 形)")
  }
}

///|
/// 发现文件读(/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..