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

# src/npl/nipbox/std.nim
# Adapter for Legacy Code -> New LibC

type cptr* = pointer

# LibC Imports
proc write*(fd: cint, buf: cptr, count: csize_t): int {.importc, cdecl.}
proc read*(fd: cint, buf: cptr, count: csize_t): int {.importc, cdecl.}
proc open*(pathname: cstring, flags: cint): cint {.importc, cdecl.}
proc close*(fd: cint): cint {.importc, cdecl.}
proc exit*(status: cint) {.importc, cdecl.}
proc nexus_list*(buf: pointer, len: int): int {.importc, cdecl.}
proc syscall(nr: int, a0: int = 0, a1: int = 0, a2: int = 0): int {.importc, cdecl.}

# Legacy Aliases
proc list_files*(buf: pointer, len: uint64): int64 =
  return int64(nexus_list(buf, int(len)))

proc nexus_syscall*(cmd: cint, arg: uint64): cint =
  return cint(syscall(int(cmd), int(arg), 0, 0))

proc nexus_yield*() =
  discard syscall(0, 0) # Exit/Yield

type FileArgs* = object
  name*: uint64
  data*: uint64
  len*: uint64

proc nexus_file_write*(name: string, data: string) =
  # Disabled
  return

proc nexus_file_read*(name: string, buffer: pointer, max_len: uint64): int =
  # Disabled
  return -1

# Print Helpers
proc print*(s: string) =
  if s.len > 0:
    discard write(cint(1), unsafeAddr s[0], csize_t(s.len))
  var nl = "\n"
  discard write(cint(1), unsafeAddr nl[0], 1)

proc print_raw*(s: string) =
  if s.len > 0:
    discard write(cint(1), unsafeAddr s[0], csize_t(s.len))

proc print_int*(n: int) =
  var s = ""
  var v = n
  if v == 0: s = "0"
  else:
    while v > 0:
      s.add(char((v mod 10) + 48))
      v = v div 10
  # Reverse
  var r = ""
  var i = s.len - 1
  while i >= 0:
    r.add(s[i])
    i -= 1
  print_raw(r)

proc my_readline*(out_str: var string): bool =
  out_str = ""
  while true:
    var c: char
    let n = read(cint(0), addr c, 1)
    if n <= 0: return false

    if c == '\n' or c == '\r':
      print_raw("\n")
      return true
    elif c == '\b' or c == char(127):
      if out_str.len > 0:
        var bs = "\b \b"
        discard write(cint(1), addr bs[0], 3)
        out_str.setLen(out_str.len - 1)
    else:
      out_str.add(c)
      discard write(cint(1), addr c, 1)
