///|
/// anthropos-gateway——moonanthos FaaS 网关(A1-0 核心竖切)
/// POST /eval body=moonanthos 源码 → lang 编译 → rpc 推靶机 exec →
/// JSON 回执 {"ok":true,"result":...}/{"ok":false,"crash":现场}
/// 节点发现:复用 /tmp/anthos_up.node 协议(anthropos_target boot 写)

///|
const VERSION : String = "0.5.6"

///|
const PORT : Int32 = 7990

///|
/// EtfVal→人读(回执渲染;list 显示面小账同 eval)
fn fmt_val(v : @rpc.EtfVal) -> String {
  match v {
    VInt(n) => "\{n}"
    VAtom(a) => a
    VString(sv) => "\"\{sv}\""
    VNil => "[]"
    VFloat(d) => "\{d}"
    VTuple(items) => "{" + join_vals(items) + "}"
    VList(items) => "[" + join_vals(items) + "]"
    VRef(node, id, serial, creation) => ""
    VPid(node, id, serial, creation) => "<\{id}.\{serial}.\{creation}>"
    VPort(node, id, creation) => ""
    VAtom("true") => "true"
    VAtom("false") => "false"
    VBinary(b) => {
      let parts : Array[String] = []
      let n = if b.length() > 16 { 16 } else { b.length() }
      for i in 0.. 16 {
        let _ = parts.push("...")
      }
      "<<\{parts.join(", ")}>>"
    }
    _ => "?"
  }
}

///|
fn join_vals(items : Array[@rpc.EtfVal]) -> String {
  let parts : Array[String] = []
  for i in items {
    let _ = parts.push(fmt_val(i))
  }
  parts.join(", ")
}

///|
/// 发现文件读取(node 短名+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.. (Bool, String) raise Error {
  conn_seq_cell[0] = conn_seq_cell[0] + 1
  let my_name = "gw\{conn_seq_cell[0]}"
  let client = @client.BeamClient::connect(
    node_short~,
    cookie~,
    name=my_name,
    alive_port=17999,
    drain=2,
  ) catch {
    _ => return (false, "靶机连接拒(未起?bin/start.sh)")
  }
  let codec_impl = @eetf_codec.EtfCodecEetf::new(tag=0)
  let port : &@rpc.RpcPort = GwRpcPort::{
    sock: client.sock(),
    codec: codec_impl,
  }
  let codec : &@rpc.EtfCodec = codec_impl
  let my_full = "\{my_name}@dev"
  let caller = @rpc.EtfVal::VPid(my_full, 1, 1, client.creation())
  let mut refi = 900
  fn next_ref() -> @rpc.EtfVal {
    refi += 1
    @rpc.EtfVal::VRef(my_full, refi, 0, client.creation())
  }
  let mname = "ae"
  let has_fn = expr.contains("fn ")
  let src = if has_fn {
    "module \{mname}\n\{expr}\n"
  } else {
    "module \{mname}\nfn go() { \{expr} }\n"
  }
  let forms2 = @lang.parse_module(src) catch {
    Parse(m) => return (false, "parse: \{m}")
    Lex(m) => return (false, "lex: \{m}")
    _ => return (false, "parse: 拒")
  }
  let reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "compile",
    "forms",
    [@lang.forms_of(forms2), @rpc.EtfVal::VNil],
  ) catch {
    _ => return (false, "compile rpc 拒")
  }
  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, "load 拒")
  }
  let call_reply = @rpc.call(
    codec,
    port,
    node_short,
    caller~,
    ref_=next_ref(),
    "anthropos_exec",
    "eval",
    [VAtom(mname), VAtom("go"), VNil],
  ) catch {
    _ => return (false, "exec rpc 拒")
  }
  match call_reply {
    VTuple(items) =>
      if items.length() == 2 && items[0] is VAtom("ok") {
        (true, fmt_val(items[1]))
      } else if items.length() == 2 && items[0] is VAtom("crash") {
        (false, "exec 崩溃现场: \{fmt_val(items[1])}")
      } else {
        (false, "回执异常形: \{fmt_val(call_reply)}")
      }
    _ => (false, "回执非元组: \{fmt_val(call_reply)}")
  }
}

///|
struct GwRpcPort {
  sock : @socket.Tcp
  codec : &@dist.EtfPort
}

///|
impl @rpc.RpcPort for GwRpcPort 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 GwRpcPort 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() >= 4 {
    }
    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) => {
        // io_request 应答:OTP 编译器/用户代码经 group leader(=我方 caller 假 pid)
        // 发 {io_request,From,Ref,Req} 并同步等 io_reply——不应答=对端永挂
        // (OTP28 compile 告警打印实证:体含未绑定 var 即编译告警→挂死 gw)
        if items.length() == 4 {
          match items[0] {
            IAtom("io_request") => {
              io_reply(self.sock, self.codec, ctl_dec.0, msg_bytes) catch {
                _ => eprintln("DBG-IO io_reply 拒")
              }
              continue
            }
            _ => ()
          }
        }
        if items.length() == 2 {
          result = Some(msg_bytes)
        }
      }
      _ => ()
    }
  }
  match result {
    Some(b) => b
    None => raise @rpc.RpcError::Transport("recv 无回执")
  }
}

///|
/// io_request 应答:回 {io_reply,Ref,ok} 给请求方 pid——Ref **原字节回声**
/// (IRef 三字段与 'Z' 形 u32 creation 不对位,重编码有标签错位雷)
/// wire: 'p'|131|{22,From(gw),To(请求方)}|131|{io_reply,Ref,ok}
async fn io_reply(
  sock : @socket.Tcp,
  codec : &@dist.EtfPort,
  ctl : @dist.EtfItem,
  msg_bytes : Bytes,
) -> Unit {
  let (from_gw, to_req) = match ctl {
    ITuple(items) if items.length() >= 3 => (items[2], items[1])
    _ => (IAtom("none"), IAtom("none"))
  }
  let (gw_node, gw_id, gw_ser, gw_cre) = match from_gw {
    IPid(n, i, s, c) => (n, i, s, c)
    _ => return
  }
  let (to_node, to_id, to_ser, to_cre) = match to_req {
    IPid(n, i, s, c) => (n, i, s, c)
    _ => return
  }
  let ctl_term = @eetf.EtfTerm::ETuple([
    @eetf.EtfTerm::EInt(22),
    @eetf.EtfTerm::EPid(gw_node, gw_id, gw_ser, gw_cre),
    @eetf.EtfTerm::EPid(to_node, to_id, to_ser, to_cre),
  ])
  let ctl_b = @eetf.encode(ctl_term) catch { _ => return }
  // msg=131|104,4|atom io_request|pid From|ref Ref|Req——逐项推进取 ref 段
  let a1 = codec.decode_term(msg_bytes, 3, []) catch { _ => return }
  let a2 = codec.decode_term(msg_bytes, a1.1, []) catch { _ => return }
  let a3 = codec.decode_term(msg_bytes, a2.1, []) catch { _ => return }
  let ref_from = a2.1
  let ref_to = a3.1
  let ref_raw = msg_bytes[ref_from:ref_to].to_owned()
  let out : Array[Byte] = [131, 104, 3]
  let atom_reply = @channel.etf_atom_bytes("io_reply")
  for i in 0.. eprintln("DBG-IO io_reply send 拒")
  }
}

///|
fn json_escape(s : String) -> String {
  let sb = StringBuilder()
  for ch in s {
    if ch == '"' {
      let _ = sb.write_char('\\')
      let _ = sb.write_char('"')
    } else if ch == '\\' {
      let _ = sb.write_char('\\')
      let _ = sb.write_char('\\')
    } else if ch.to_int() == 10 {
      let _ = sb.write_char('\\')
      let _ = sb.write_char('n')
    } else if ch.to_int() < 32 {
      let _ = sb.write_char(' ')
    } else {
      let _ = sb.write_char(ch)
    }
  }
  sb.to_string()
}

///|
async fn main {
  let args = @env.args()
  for ai in 0.. None }
  match discovered {
    Some((dn, _dc)) => println("ok: 靶机 \{dn}(发现文件)")
    None =>
      println(
        "warn: 发现文件缺席——起靶机: anthropos_target/bin/start.sh",
      )
  }
  let server = @http.Server(@socket.Addr::parse("0.0.0.0:\{PORT}"))
  println(
    "anthropos-gateway \{VERSION} 监听 : \{PORT}(POST /eval body=源码)",
  )
  // 外层永驻组(单组永驻回调正形——close-cancel 雷家法):泵监管
  // no_wait 先起,组回调体殿后 serve——组永不收=监管永驻=一致生命周期
  let _ = @async.with_task_group(async fn(group) {
    // 泵 worker 池(静态 4):认领循环服务多节点 watch 连接
    group.spawn_loop(
      async fn() {
        watch_pump_worker(0)
      },
      no_wait=true,
    )
    group.spawn_loop(
      async fn() {
        watch_pump_worker(1)
      },
      no_wait=true,
    )
    group.spawn_loop(
      async fn() {
        watch_pump_worker(2)
      },
      no_wait=true,
    )
    group.spawn_loop(
      async fn() {
        watch_pump_worker(3)
      },
      no_wait=true,
    )
    server.run_forever() <| async fn(request, body, conn) {
    let path = request.path
    let meth = request.meth
    // query 拆分:path 可能含 ?name=x(符号寻址面)
    let mut route_path = path
    let mut query_s = ""
    let qidx = path.find("?")
    if qidx is Some(qp) {
      route_path = path[:qp].to_owned()
      query_s = path[qp + 1:].to_owned()
    }
    if meth is Post && route_path == "/eval" {
      let code = @utf8.decode_lossy(body.read_all().binary())
      let node_cookie = read_discover() catch { _ => None }
      let (ok, result) = match node_cookie {
        Some((dn, dc)) =>
          gateway_eval(code, dn, dc) catch {
            _ => (false, "内部拒")
          }
        None => (false, "无靶机(发现文件缺席)")
      }
      let payload = if ok {
        "{\"ok\":true,\"result\":\"\{json_escape(result)}\"}"
      } else {
        "{\"ok\":false,\"crash\":\"\{json_escape(result)}\"}"
      }
      conn.send_response(200, "OK")
      let _ = conn.write_string(payload)
      ()
    } else if meth is Post &&
      (
        route_path == "/spawn" ||
        route_path == "/spawn_cluster" ||
        route_path == "/nodes" ||
        route_path == "/actors" ||
        route_path == "/shutdown" ||
        route_path == "/send" ||
        route_path == "/call" ||
        route_path == "/monitor" ||
        route_path == "/demonitor" ||
        route_path == "/watch" ||
        route_path == "/unwatch" ||
        route_path == "/poll" ||
        route_path == "/spawn_pool" ||
        route_path == "/stats" ||
        route_path == "/terminate" ||
        route_path == "/deploy" ||
        route_path == "/invoke" ||
        route_path == "/debug"
      ) {
      let code = @utf8.decode_lossy(body.read_all().binary())
      let out = actor_route(route_path, code, query_s)
      conn.send_response(200, "OK")
      let _ = conn.write_string(out)
      ()
    } else if meth is Get && route_path == "/health" {
      conn.send_response(200, "OK")
      let _ = conn.write_string("{\"ok\":true,\"gateway\":\"\{VERSION}\"}")
      ()
    } else {
      conn.send_response(404, "NotFound")
      ()
    }
  }
  })
}