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

const std = @import("std");
const ION_BASE = 0x83000000;

const IonPacket = extern struct {
    data: u64,
    phys: u64,
    len: u16,
    id: u16,
    _pad: u32,
};

const CmdPacket = extern struct {
    kind: u32,
    reserved: u32,
    arg: u64,
    id: [16]u8,
};

fn RingBuffer(comptime T: type) type {
    return extern struct {
        head: u32,
        tail: u32,
        mask: u32,
        data: [256]T,
    };
}

const SysTable = extern struct {
    magic: u32,
    reserved: u32,
    s_rx: *RingBuffer(IonPacket),
    s_tx: *RingBuffer(IonPacket),
    s_event: *RingBuffer(IonPacket),
    s_cmd: *RingBuffer(CmdPacket),
    s_input: *RingBuffer(IonPacket),
};

const CMD_ION_STOP = 1;

extern fn k_handle_syscall(nr: usize, a0: usize, a1: usize, a2: usize) usize;
extern fn console_read() c_int;
extern fn ion_push_stdin(ptr: [*]const u8, len: usize) void;
extern fn fiber_yield() void;
extern fn fiber_sleep(ms: u64) void;
extern fn ion_wait_multi(mask: u64) i32;

export fn nexshell_main() void {
    const sys = @as(*SysTable, @ptrFromInt(ION_BASE));

    print("\n╔═══════════════════════════════════════╗\n");
    print("║   NEXSHELL IMMUNE SYSTEM ACTIVE       ║\n");
    print("╚═══════════════════════════════════════╝\n\n");

    const cmd_ring = sys.s_cmd;

    var input_buffer: [128]u8 = undefined;
    var input_idx: usize = 0;

    print("[NexShell] Entering main loop (REACTIVE MODE)...\n");
    print("> ");

    while (true) {
        const c = console_read();

        if (c != -1) {
            const byte = @as(u8, @intCast(c));

            if (byte == '\r' or byte == '\n') {
                print("\n");
                if (input_idx > 0) {
                    process_command(input_buffer[0..input_idx], cmd_ring);
                }
                input_idx = 0;
                print("> ");
            } else if (byte == 8 or byte == 127) { // Backspace
                if (input_idx > 0) {
                    input_idx -= 1;
                    print("\x08 \x08");
                }
            } else if (input_idx < 127) {
                input_buffer[input_idx] = byte;
                input_idx += 1;
                const bs = [1]u8{byte};
                print(&bs);
            }
        } else {
            // Wait for console.input (Slot 0)
            _ = ion_wait_multi(0x01);
        }

        fiber_yield();
    }
}

var forward_mode: bool = false;

fn process_command(cmd_text: []const u8, cmd_ring: *RingBuffer(CmdPacket)) void {
    if (cmd_text.len == 0) return;

    if (forward_mode) {
        const is_toggle = std.mem.eql(u8, cmd_text, "kernel") or std.mem.eql(u8, cmd_text, "exit");
        print("[NexShell] Forwarding to Subject...\n");

        if (cmd_text.len > 0) {
            var forward_buf: [128]u8 = undefined;
            const copy_len = if (cmd_text.len > 126) 126 else cmd_text.len;
            @memcpy(forward_buf[0..copy_len], cmd_text[0..copy_len]);
            forward_buf[copy_len] = '\n';
            ion_push_stdin(forward_buf[0 .. copy_len + 1].ptr, copy_len + 1);
        }

        if (is_toggle) {
            forward_mode = false;
            print("[NexShell] Dropping to Kernel Debug Mode.\n");
        }
    } else {
        if (std.mem.eql(u8, cmd_text, "ps") or std.mem.eql(u8, cmd_text, "fibers")) {
            print("[NexShell] Active Fibers:\n");
            _ = k_handle_syscall(0x501, 0, 0, 0);
        } else if (std.mem.eql(u8, cmd_text, "stop")) {
            push_cmd(cmd_ring, CMD_ION_STOP, 0);
        } else if (std.mem.eql(u8, cmd_text, "help")) {
            print("[NexShell] ps, stop, help\n");
        } else {
            print("[NexShell] Unknown Command: ");
            print(cmd_text);
            print("\n");
        }
    }
}

fn push_cmd(ring: *RingBuffer(CmdPacket), kind: u32, arg: u64) void {
    const head = @atomicLoad(u32, &ring.head, .acquire);
    const tail = @atomicLoad(u32, &ring.tail, .monotonic);

    const next = (head + 1) & ring.mask;
    if (next == tail) return;

    ring.data[head & ring.mask] = .{ .kind = kind, .reserved = 0, .arg = arg, .id = [_]u8{0} ** 16 };
    @atomicStore(u32, &ring.head, next, .release);
}

fn kernel_write(fd: c_int, buf: [*]const u8, count: usize) isize {
    return @as(isize, @bitCast(k_handle_syscall(0x204, @as(usize, @intCast(fd)), @intFromPtr(buf), count)));
}

fn print(text: []const u8) void {
    _ = kernel_write(1, text.ptr, text.len);
}
