# 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.

## Sovereign Init: The Genesis Process

import ../../libs/membrane/libc

proc main() =
  # 1. Pledge Sovereignty
  discard pledge(0xFFFFFFFFFFFFFFFF'u64) # PLEDGE_ALL

  print(cstring("\n"))
  print(cstring("\x1b[1;35m╔═══════════════════════════════════════╗\x1b[0m\n"))
  print(cstring("\x1b[1;35m║     SOVEREIGN INIT (NexInit v1.0)     ║\x1b[0m\n"))
  print(cstring("\x1b[1;35m╚═══════════════════════════════════════╝\x1b[0m\n\n"))

  print(cstring("[INIT] Initializing Membrane Network Stack...\n"))
  membrane_init()

  proc glue_get_ip(): uint32 {.importc: "glue_get_ip", cdecl.}

  # --- DHCP PHASE ---
  print(cstring("[INIT] Waiting for DHCP IP Address...\n"))
  var ip: uint32 = 0
  for i in 0 ..< 600: # 60 seconds
    pump_membrane_stack()
    ip = glue_get_ip()
    if ip != 0: break
    discard syscall(0x65, 100000000'u64) # 100ms
    
  if ip == 0:
    print(cstring("[INIT] WARNING: DHCP Discovery timed out. Proceeding...\n"))
  else:
    print(cstring("[INIT] Network ONLINE (10.0.2.15)\n"))

  # --- DNS PHASE ---
  print(cstring("\n[TEST] ══════════════════════════════════════\n"))
  print(cstring("[TEST] DNS Resolution: google.com\n"))
  print(cstring("[TEST] ══════════════════════════════════════\n\n"))
  
  var res: ptr AddrInfo
  for attempt in 1..5:
    print(cstring("[TEST] Resolving google.com (Attempt "))
    # (Simplified number printing not available, just loop)
    
    if getaddrinfo("google.com", nil, nil, addr res) == 0:
      print(cstring(") -> SUCCESS!\n"))
      freeaddrinfo(res)
      break
    else:
      print(cstring(") -> FAILED. Waiting 5s...\n"))
      for j in 1..50:
        pump_membrane_stack()
        discard syscall(0x65, 100000000'u64) # 100ms
  
  # --- SHELL PHASE ---
  proc spawn_fiber(path: cstring): int =
    return int(syscall(0x300, cast[uint64](path), 0, 0))
    
  print(cstring("[INIT] Spawning mksh...\n"))
  discard spawn_fiber(cstring("/bin/mksh"))
  
  # --- SUPERVISOR PHASE ---
  print(cstring("[INIT] Entering Supervisor Loop...\n"))
  var loop_count = 0
  while true:
    pump_membrane_stack()
    loop_count += 1
    if loop_count mod 100 == 0:
      print(cstring("[INIT] Heartbeat\n"))
    discard syscall(0x65, 100000000'u64) # 100ms

when isMainModule:
  main()
