// Rumpk Layer 0: The Concrete Foundation
// Markus Maiwald (Architect) | Voxis Forge (AI)
//
// This is the hardware floor. Sets up stack and calls Nim.

const uart = @import("uart.zig");

const hud = @import("hud.zig");
const virtio_net = @import("virtio_net.zig");
const virtio_block = @import("virtio_block.zig");

export fn hal_io_init() void {
    virtio_net.init();
    virtio_block.init();
}

// =========================================================
// Stack Setup (16KB)
// =========================================================

export var stack_bytes: [64 * 1024]u8 align(16) = undefined;

// =========================================================
// Entry Point (Naked - no prologue)
// =========================================================

export fn _start() callconv(.naked) noreturn {
    // ARM64: Set up stack pointer, then call zig_entry
    asm volatile (
    // 1. Enable FP/SIMD (prevents traps if compiler vectorizes crypto)
        \\  mov x0, #3 << 20
        \\  msr cpacr_el1, x0
        \\  isb
        // 2. Set up stack
        \\  adrp x0, stack_bytes
        \\  add x0, x0, :lo12:stack_bytes
        \\  add sp, x0, #65536
        \\  bl zig_entry
        \\  b .
    );
    unreachable;
}

// =========================================================
// HAL Exports to Nim (The ABI Contract)
// =========================================================

export fn console_write(ptr: [*]const u8, len: usize) void {
    uart.write_bytes(ptr[0..len]);
}

export fn rumpk_halt() noreturn {
    uart.puts("[Rumpk L0] Halting.\n");
    while (true) {
        asm volatile ("wfi");
    }
}

// Nim Entry Points
extern fn NimMain() void;
extern fn kmain() void;

// =========================================================
// Zig Entry (called from _start)
// =========================================================

export fn zig_entry() void {
    uart.init();

    // HUD DRAW
    uart.print(hud.CLEAR);
    hud.set_color(36); // Cyan
    hud.draw_box(1, 1, 80, 3, "RUMPK HUD v0.1");
    hud.draw_box(1, 4, 80, 20, "NEXSHELL CONSOLE");
    hud.draw_box(1, 24, 80, 2, "IDENTITY");

    hud.move_to(2, 4);
    uart.print("CPU: AArch64 | STATUS: INITIALIZING | MASK: SOVEREIGN");

    hud.move_to(25, 4);
    uart.print("CELL: /Cell/Root | ID: 0xDEADBEEF");

    hud.move_to(5, 4);
    hud.reset_color();

    uart.puts("[Rumpk L0] Handing off to Nim L1...\n");

    // Initialize Nim Runtime
    NimMain();

    // HANDOFF
    kmain();

    // If Nim returns, halt
    uart.puts("[Rumpk L0] Nim returned unexpectedly.\n");
    rumpk_halt();
}
