// NEXUS IMMUNE SYSTEM (NPL) - THE VOICE & COMMAND PLANE
// Markus Maiwald (Architect) | Voxis Forge (AI)

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

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

const CmdPacket = extern struct {
    kind: u32,
    arg: u64,
};

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

const SysTable = extern struct {
    magic: 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;
const CMD_ION_START = 2;
const CMD_GPU_MATRIX = 0x100;
const CMD_GET_GPU_STATUS = 0x102;

// The Main Loop for the NexShell Fiber
export fn nexshell_main() void {
    const sys = @as(*SysTable, @ptrFromInt(ION_BASE));

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

    const event_ring = sys.s_event;
    const cmd_ring = sys.s_cmd;

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

    while (true) {
        // 1. Process Telemetry Events
        const head = @atomicLoad(u32, &event_ring.head, .acquire);
        const tail = @atomicLoad(u32, &event_ring.tail, .monotonic);

        if (head != tail) {
            const pkt = event_ring.data[tail & event_ring.mask];
            print("\n[NexShell] ALERT | EventID: ");
            if (pkt.id == 777) {
                print("777 (SECURITY_HEARTBEAT)\n");
            } else {
                print("GENERIC\n");
            }
            @atomicStore(u32, &event_ring.tail, tail + 1, .release);
        }

        // 2. Process User Input (Non-blocking)
        const c = console_read();
        if (c != -1) {
            const byte = @as(u8, @intCast(c));
            if (byte == '\r' or byte == '\n') {
                print("\n");
                process_command(input_buffer[0..input_idx], cmd_ring);
                input_idx = 0;
            } else if (byte == 0x7F or byte == 0x08) {
                if (input_idx > 0) {
                    input_idx -= 1;
                    print("\x08 \x08"); // Backspace
                }
            } else if (input_idx < 63) {
                input_buffer[input_idx] = byte;
                input_idx += 1;
                const bs = [1]u8{byte};
                print(&bs);
            }
        }

        fiber_yield();
    }
}

var forward_mode: bool = true;

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");

        // ALWAYS FORWARD TO USERLAND first so it can process its own exit
        print("[NexShell] Forwarding to Subject...\n");

        // Combine command + newline to avoid fragmentation
        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, "subject") or std.mem.eql(u8, cmd_text, "nipbox")) {
            forward_mode = true;
            print("[NexShell] Resuming Subject Pipe.\n");
            return;
        }

        if (std.mem.eql(u8, cmd_text, "io stop") or std.mem.eql(u8, cmd_text, "ion stop")) {
            print("[NexShell] Pushing CMD_ION_STOP...\n");
            push_cmd(cmd_ring, CMD_ION_STOP, 0);
        } else if (std.mem.eql(u8, cmd_text, "matrix on")) {
            print("[NexShell] Engaging Matrix Protocol (Emergency Override)...\n");
            push_cmd(cmd_ring, CMD_GPU_MATRIX, 1);
        } else if (std.mem.eql(u8, cmd_text, "matrix off")) {
            print("[NexShell] Disengaging Matrix Protocol...\n");
            push_cmd(cmd_ring, CMD_GPU_MATRIX, 0);
        } else if (std.mem.eql(u8, cmd_text, "matrix status")) {} else if (std.mem.eql(u8, cmd_text, "help")) {
            print("[NexShell] Kernel Commands: io stop, matrix on/off, matrix status, subject, help\n");
        } else {
            print("[NexShell] Unknown Kernel 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) {
        print("[NexShell] CMD RING FULL!\n");
        return;
    }

    ring.data[head & ring.mask] = .{ .kind = kind, .arg = arg };
    @atomicStore(u32, &ring.head, next, .release);
}

// OS Shims
extern fn write(fd: c_int, buf: [*]const u8, count: usize) isize;
extern fn console_read() c_int;
extern fn ion_push_stdin(ptr: [*]const u8, len: usize) void;
extern fn fiber_yield() void;

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