# Nexus Membrane: Socket Shim
# Manages state for fake file descriptors.

import net_glue

const MAX_SOCKETS = 1024

var socket_table: array[MAX_SOCKETS, ptr NexusSock]

proc new_socket*(): int =
  ## Allocate a new NexusSocket and return a fake FD.
  ## Reserve FDs 0, 1, 2 for stdio compatibility.
  for i in 3 ..< MAX_SOCKETS:
    if socket_table[i] == nil:
      var s = create(NexusSock)
      s.fd = i
      s.state = CLOSED
      socket_table[i] = s
      return i
  return -1

proc get_socket*(fd: int): ptr NexusSock =
  if fd < 0 or fd >= MAX_SOCKETS: return nil
  return socket_table[fd]

proc connect_flow*(fd: int, ip: uint32, port: uint16): int =
  let s = get_socket(fd)
  if s == nil: return -1
  return glue_connect(s, cast[ptr IpAddr](addr ip), port)

proc send_flow*(fd: int, buf: pointer, len: int): int =
  let s = get_socket(fd)
  if s == nil: return -1
  return glue_write(s, buf, len)
