# 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
##
## Responsible for bootstrapping the system, starting core services,
## and managing the lifecycle of the user environment.

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

# --- Entry Point ---

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 v0.1)     ║\x1b[0m\n"))
  print(cstring("\x1b[1;35m╚═══════════════════════════════════════╝\x1b[0m\n\n"))

  print(cstring("[INIT] System Ready. Starting heartbeat...\n"))

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

  # Spawn mksh as a separate fiber (NOT execv - we stay alive as supervisor)
  proc spawn_fiber(path: cstring): int =
    # SYS_SPAWN_FIBER = 0x300
    return int(syscall(0x300, cast[uint64](path), 0, 0))
    
  let fiber_id = spawn_fiber(cstring("/bin/mksh"))
  if fiber_id > 0:
    print(cstring("[INIT] Spawned mksh fiber ID: "))
    # Note: Can't easily print int in minimal libc, just confirm success
    print(cstring("OK\n"))
  else:
    print(cstring("\x1b[1;31m[INIT] Failed to spawn shell!\x1b[0m\n"))
  
  
  # Supervisor loop - REACTIVE MODE (Silence Doctrine)
  # Only wake when network packets arrive or other I/O events occur
  print(cstring("[INIT] Entering supervisor mode (REACTIVE)...\n"))
  
  # Slot 2 is CMD_NET_RX (0x501) granted by Kernel
  const SLOT_NET_RX = 2 
  let wait_mask = 1'u64 shl SLOT_NET_RX  # Wait for network events
  
  
  var loop_count = 0
  while true:
    # Process network events and LwIP timers
    pump_membrane_stack()
    
    # Heartbeat every iteration
    loop_count += 1
    if loop_count mod 1 == 0:
      print(cstring("[INIT] Heartbeat\n"))
    
    # Sleep 10ms using Timer Driver (System Call)
    discard syscall(0x65, 10000000'u64)

when isMainModule:
  main()
