# 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: High-Level Sovereign Channels

# MARKUS MAIWALD (ARCHITECT) | VOXIS FORGE (AI)
# RUMPK CORE // CHANNEL
# The primitive for Typed Communication.
#
# DISTINCTION:
# - FIBER: Unit of EXECUTION (Sequential logic, stack-based).
# - CHANNEL: Unit of COMMUNICATION (Object transport, ID-based).
#
# Channels are the "Pipes" of NexShell. They carry KDL/JSON objects
# instead of raw byte streams.

{.push stackTrace: off, lineTrace: off.}

import ring
import crypto # For SipHash if needed, but for now we define ID type

type
  ChannelID* = array[2, uint64] # 128-bit SipHash ID

  Message* = object
    ## A typed payload carried by a channel
    sender*: ChannelID
    target*: ChannelID
    payload*: pointer ## Pointer to KDL object in CAS/Heap
    size*: uint64

  Channel*[N: static[int]] = object
    ## A typed channel carrying Messages
    id*: ChannelID
    name*: cstring
    buffer*: RingBuffer[Message, N]

proc init*[N: static[int]](chan: var Channel[N], id: ChannelID, name: cstring) =
  chan.id = id
  chan.name = name
  chan.buffer.init()

proc send*[N: static[int]](chan: var Channel[N], msg: Message): bool =
  ## Send a message to the channel. Returns false if full.
  chan.buffer.push(msg)

proc recv*[N: static[int]](chan: var Channel[N]): tuple[ok: bool,
    msg: Message] =
  ## Receive a message from the channel.
  chan.buffer.pop()

# =========================================================
# The Global Message Bus (The Hub)
# =========================================================
# In a full NexShell implementation, this would be a registry
# of Channels indexed by their SipHash ID.

{.pop.}
