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

## Rumpk Layer 1: Invariant Verification (The Shield)

# import ion  # Included in ion.nim

# Error type for future use
type
  FiberPanic* = object of CatchableError

# Forward declarations for utilities defined in kernel.nim (included there)
proc kernel_panic*(msg: cstring) {.importc: "panic", cdecl.}
proc kprintln*(s: cstring) {.importc: "kprintln", cdecl.}

template secure_send*(ring_ptr: pointer, pkt: CmdPacket) =
  ## Verifies invariants before pushing to a command ring.

  # 1. PRE-CONDITION: Alignment
  if (cast[uint](ring_ptr) and 0b11) != 0:
    kernel_panic("Invariant Violation: Unaligned Ring Pointer")

  # 2. OPERATION: Try to push via HAL
  # We pass CmdPacket directly (it's >8 bytes now)
  let success = hal_cmd_push(cast[uint64](ring_ptr), pkt)

  # 3. POST-CONDITION: Flow Control Warning
  if not success:
    kprintln("[Invariant] Warning: Command Ring Full, Drop.")

template secure_push_packet*(ring_ptr: pointer, pkt: IonPacket) =
  ## Verifies invariants for IonPacket transfers.
  if (cast[uint](ring_ptr) and 0b11) != 0:
    kernel_panic("Invariant Violation: Unaligned Ring Pointer")

  if not hal_channel_push(cast[uint64](ring_ptr), pkt):
    kprintln("[Invariant] Warning: Packet Ring Full, Drop.")

template secure_recv_cmd*(ring_ptr: pointer, out_pkt: var CmdPacket): bool =
  if (cast[uint](ring_ptr) and 0b11) != 0:
    kernel_panic("Invariant Violation: Unaligned Ring Pointer")

  hal_cmd_pop(cast[uint64](ring_ptr), addr out_pkt)
