# 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: The Watchdog (Immune Monitor)


# Watchdog Fiber - Logic Core Immune System

const MAX_PAUSE_TICKS = 1_000_000'u64

# Import timer from HAL (Exposed via abi.zig)
proc cpu_ticks(): uint64 {.importc: "rumpk_timer_now_ns", cdecl.}

proc watchdog_loop() {.cdecl.} =
  ## Fiber 0: The Immune System
  # Note: Uses globals from kernel.nim via 'include'

  kprintln("[Watchdog] Immune System Online.")

  while true:
    # Check if IO is stuck in PAUSE state
    if ion_paused:
      let now = cpu_ticks()

      # If paused and time exceeds threshold
      if (pause_start > 0) and (now > pause_start) and (now - pause_start >
          MAX_PAUSE_TICKS):
        # HEAL
        kprint("[IMMUNE] IO paused too long. Forcing RESUME.\n")
        ion_paused = false
        pause_start = 0

        # Send CMD_ION_START to the Control Loop
        var cmd = CmdPacket(kind: uint32(ion.CmdType.CMD_ION_START), arg: 0)
        discard chan_cmd.send(cmd)

    # Cooperative Multitasking: Must yield!
    # 🏛️ ADAPTIVE GOVERNOR (Phase 3: IDLE)
    # Disabled for pure cooperative benchmarking (no timer IRQ)
    # if not ion_paused:
    #   asm """
    #     csrsi sstatus, 2
    #     wfi
    #     csrci sstatus, 2
    #   """

    fiber_sleep(100)
    # asm "wfi"
