# SPDX-License-Identifier: LSL-1.0
# Copyright (c) 2026 Markus Maiwald
# Stewardship: Self Sovereign Society Foundation
#
# This file is part of the Nexus Sovereign Core.
# See legal/LICENSE_SOVEREIGN.md for license terms.

## Nexus Membrane: Socket Interface

# 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-99 for system/vfs.
  for i in 100 ..< 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, 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)

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

proc close_flow*(fd: int): int =
  let s = get_socket(fd)
  if s == nil: return -1
  let res = glue_close(s)
  socket_table[fd] = nil
  return res

proc is_connected*(fd: int): bool =
  let s = get_socket(fd)
  if s != nil:
    return s.state == ESTABLISHED
  return false

proc is_closed_or_error*(fd: int): bool =
  let s = get_socket(fd)
  if s != nil:
    return s.state == CLOSED
  return true

