const std = @import("std");

// 1. The SysTable Contract (Must match Kernel!)
const ION_BASE = 0x83000000;

// The Physical Token representing a packet
const IonPacket = extern struct {
    data: u64, // Virtual Addr (ptr)
    phys: u64, // Physical Addr
    len: u16,
    id: u16,
};

const RingBuffer = extern struct {
    // Nim Kernel RingBuffer Layout:
    // data: array[N, T]
    // head: Cursor (Atomic[int64], padded to 64 bytes)
    // tail: Cursor (Atomic[int64], padded to 64 bytes)

    data: [256]IonPacket,

    // Head Cursor
    head_val: i64,
    head_pad: [56]u8,

    // Tail Cursor
    tail_val: i64,
    tail_pad: [56]u8,
};

const SysTable = extern struct {
    magic: u32,
    s_rx: *RingBuffer, // Kernel writes, We read
    s_tx: *RingBuffer, // We write (Network Data)
    s_event: *RingBuffer, // We write (Telemetry/Events)
};

// 2. The Direct Accessor
fn get_systable() *SysTable {
    return @ptrFromInt(ION_BASE);
}

// 3. The Entry Point
export fn main() c_int {
    // A. Announce presence
    print("[ZIG] ION Raw Test: Engaging...\n");

    const sys = get_systable();

    // B. Verify Magic (Sanity Check)
    print("[ZIG] Checking SysTable at 0x83000000...\n");
    if (sys.magic == 0x4E585553) {
        print("[ZIG] MAGIC VERIFIED: 0x4E585553 ('NXUS')\n");
    } else {
        print("[ZIG] MAGIC FAIL: 0x");
        print("Unknown\n");
    }

    // C. ALLOCATE (Simulated for Raw Test)
    const pkt = IonPacket{
        .data = 0xDEADBEEF,
        .phys = 0xCAFEBABE,
        .len = 42,
        .id = 1,
    };

    // D. PUSH to TX Ring (Network Sim)
    {
        const tx = sys.s_tx;
        const head = @atomicLoad(i64, &tx.head_val, .monotonic);
        const head_u64: u64 = @bitCast(head);
        const head_idx: u32 = @truncate(head_u64);
        tx.data[head_idx % 256] = pkt;
        @atomicStore(i64, &tx.head_val, head + 1, .release);
        print("[ZIG] Network Packet pushed to TX Ring.\n");
    }

    // E. PUSH to EVENT Ring (Telemetry Sim)
    {
        const ev = sys.s_event;
        const head = @atomicLoad(i64, &ev.head_val, .monotonic);
        const head_u64: u64 = @bitCast(head);
        const head_idx: u32 = @truncate(head_u64);

        const event = IonPacket{
            .data = 0,
            .phys = 0,
            .len = 0,
            .id = 777, // Event Type: 777 (Test Event)
        };

        ev.data[head_idx % 256] = event;
        @atomicStore(i64, &ev.head_val, head + 1, .release);
        print("[ZIG] Telemetry Event pushed to EVENT Ring.\n");
    }

    // F. YIELD / PUMP (Let Kernel Process)
    print("[ZIG] Yielding to Kernel...\n");

    fiber_yield();

    print("[ZIG] Control returned. Test Complete.\n");

    while (true) {
        fiber_yield();
    }

    return 0;
}

// Minimal Shims
extern fn write(fd: c_int, buf: [*]const u8, count: usize) isize;
extern fn fiber_yield() void;

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

pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
    _ = error_return_trace;
    _ = ret_addr;
    print("\n[Zig] PANIC: ");
    print(msg);
    print("\n");
    while (true) {}
}
