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

# SPEC-051: CSpace Integration with Fiber Control Block
# Ground Zero Phase 1: Kernel Integration

## CSpace Nim Bindings

# Kernel logging (freestanding-safe)
proc kprintln(s: cstring) {.importc, cdecl.}

# Import CSpace from HAL
proc cspace_init*() {.importc, cdecl.}
proc cspace_get*(fiber_id: uint64): pointer {.importc, cdecl.}
proc cspace_grant_cap*(
  fiber_id: uint64,
  cap_type: uint8,
  perms: uint8,
  object_id: uint64,
  bounds_start: uint64,
  bounds_end: uint64
): int32 {.importc, cdecl.}
proc cspace_lookup*(fiber_id: uint64, slot: uint): pointer {.importc, cdecl.}
proc cspace_revoke*(fiber_id: uint64, slot: uint) {.importc, cdecl.}
proc cspace_check_perm*(fiber_id: uint64, slot: uint, perm_bits: uint8): bool {.importc, cdecl.}

## Capability Types (Mirror from cspace.zig)
type
  CapType* = enum
    CapNull = 0
    CapEntity = 1
    CapChannel = 2
    CapMemory = 3
    CapInterrupt = 4
    CapTime = 5
    CapEntropy = 6

## Permission Flags
const
  PERM_READ* = 0x01'u8
  PERM_WRITE* = 0x02'u8
  PERM_EXECUTE* = 0x04'u8
  PERM_MAP* = 0x08'u8
  PERM_DELEGATE* = 0x10'u8
  PERM_REVOKE* = 0x20'u8
  PERM_COPY* = 0x40'u8
  PERM_SPAWN* = 0x80'u8

## High-level API for kernel use

proc fiber_grant_channel*(fiber_id: uint64, channel_id: uint64, perms: uint8): int32 =
  ## Grant a Channel capability to a fiber
  return cspace_grant_cap(
    fiber_id,
    uint8(CapChannel),
    perms,
    channel_id,
    0,  # No bounds for channels
    0
  )

proc fiber_grant_memory*(
  fiber_id: uint64,
  region_id: uint64,
  start_addr: uint64,
  end_addr: uint64,
  perms: uint8
): int32 =
  ## Grant a Memory capability to a fiber
  return cspace_grant_cap(
    fiber_id,
    uint8(CapMemory),
    perms,
    region_id,
    start_addr,
    end_addr
  )

proc fiber_check_channel_access*(fiber_id: uint64, slot: uint, write: bool): bool =
  ## Check if fiber has channel access via capability
  let perm = if write: PERM_WRITE else: PERM_READ
  return cspace_check_perm(fiber_id, slot, perm)

proc fiber_revoke_capability*(fiber_id: uint64, slot: uint) =
  ## Revoke a capability from a fiber
  cspace_revoke(fiber_id, slot)

## Initialization
proc init_cspace_subsystem*() =
  ## Initialize the CSpace subsystem (call from kmain)
  cspace_init()
  kprintln("[CSpace] Capability system initialized")
