# 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: Panic Override (Emergency Procedures)

# Rumpk Panic Override
# Required for Nim --os:any / --os:standalone
# This file must be named panicoverride.nim

var nimErrorFlag* {.exportc: "nimErrorFlag", compilerproc.}: bool = false

proc nimAddInt(a, b: int, res: var int): bool {.compilerproc.} =
  let r = a + b
  if (r < a) != (b < 0): return true
  res = r
  return false

proc nimSubInt(a, b: int, res: var int): bool {.compilerproc.} =
  let r = a - b
  if (r > a) != (b < 0): return true
  res = r
  return false

proc nimMulInt(a, b: int, res: var int): bool {.compilerproc.} =
  let r = a * b
  if b != 0 and (r div b) != a: return true
  res = r
  return false

{.push stackTrace: off.}

proc console_write(p: pointer, len: csize_t) {.importc, cdecl.}
proc rumpk_halt() {.importc, cdecl, noreturn.}

# Stubs for missing runtime symbols to satisfy linker
proc setLengthStr*(s: pointer, newLen: int) {.exportc, compilerproc.} = discard
proc addChar*(s: pointer, c: char) {.exportc, compilerproc.} = discard
proc callDepthLimitReached*() {.exportc, compilerproc.} = 
  while true: discard

# Type Info stub for Defect (referenced by digitsutils/exceptions)
var NTIdefect* {.exportc: "NTIdefect__SEK9acOiG0hv2dnGQbk52qg_", compilerproc.}: pointer = nil 

proc rawoutput(s: string) =
  if s.len > 0:
    console_write(unsafeAddr s[0], csize_t(s.len))

proc panic(s: cstring) {.exportc, noreturn.} =
  rawoutput("[PANIC] ")
  if s != nil:
    var i = 0
    while s[i] != '\0':
      var buf: array[1, char]
      buf[0] = s[i]
      console_write(addr buf[0], 1)
      inc i
  rawoutput("\n")
  rumpk_halt()

proc raiseIndexError2(i, n: int) {.exportc, noreturn, compilerproc.} =
  rawoutput("[PANIC] Index Error: ")
  panic("Index Out of Bounds")

proc raiseOverflow() {.exportc, noreturn, compilerproc.} =
  panic("Integer Overflow")

proc raiseRangeError(val: int64) {.exportc, noreturn, compilerproc.} =
  panic("Range Error")

proc raiseDivByZero() {.exportc, noreturn, compilerproc.} =
  panic("Division by Zero")

{.pop.}
