# 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"))

  # 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 - stay alive, check fiber health periodically
  print(cstring("[INIT] Entering supervisor mode...\n"))
  while true:
    # Sleep 1 second between checks
    discard syscall(0x65, 1000000000'u64)  # nanosleep: 1 second
    pump_membrane_stack()
    yield_fiber()

when isMainModule:
  main()
