// MARKUS MAIWALD (ARCHITECT) | VOXIS FORGE (AI)
// RUMPK HAL // RISC-V ENTRY
const std = @import("std");
const uart = @import("uart.zig");
const virtio_net = @import("virtio_net.zig");

// =========================================================
// Entry Point (Naked)
// =========================================================

export fn _start() callconv(.naked) noreturn {
    asm volatile (
    // 1. Disable Interrupts
        \\ csrw sie, zero
        \\ csrw satp, zero
        // 1.1 Enable FPU (sstatus.FS = Initial [01])
        \\ li t0, 0x2000
        \\ csrs sstatus, t0

        // 1.2 Initialize Global Pointer
        \\ .option push
        \\ .option norelax
        \\ la gp, __global_pointer$
        \\ .option pop

        // 2. Set up Stack
        \\ la sp, stack_bytes
        \\ li t0, 65536
        \\ add sp, sp, t0

        // 2.1 Install Trap Handler (Direct Mode)
        \\ la t0, trap_entry
        \\ csrw stvec, t0

        // 3. Jump to Zig Entry
        \\ call zig_entry
        \\ 1: wfi
        \\ j 1b
    );
    unreachable;
}

export fn trap_entry() callconv(.naked) void {
    asm volatile (
        \\ // Minimal context save (clobbering scratch regs for debug)
        \\ csrr t0, scause
        \\ csrr t1, sepc
        \\ csrr t2, stval
        \\ mv a0, t0
        \\ mv a1, t1
        \\ mv a2, t2
        \\ call rss_trap_handler
        \\ 1: wfi
        \\ j 1b
    );
}

export fn rss_trap_handler(cause: usize, epc: usize, val: usize) void {
    uart.print("\n\n!!! SOVEREIGN TRAP !!!\n");
    uart.print("SCAUSE: 0x");
    uart.print_hex(cause);
    uart.print("\n");
    uart.print("SEPC:   0x");
    uart.print_hex(epc);
    uart.print("\n");
    uart.print("STVAL:  0x");
    uart.print_hex(val);
    uart.print("\n");
    uart.print("SYSTEM HALTED.\n");
    while (true) {}
}

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

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

// =========================================================
// Zig Higher-Level Entry
// =========================================================

extern fn kmain() void;
extern fn NimMain() void;

export fn zig_entry() void {
    // UART init (QEMU default 0x10000000)
    uart.init_riscv();
    uart.print("[Rumpk L0] zig_entry reached\n");

    // HUD DISABLED FOR PHASE 8.7 - LINEAR LOGGING ONLY
    // 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: RISC-V 64 | 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.print("[Rumpk RISC-V] Handing off to Nim L1...\n");
    // VirtIO Init moved to Kernel L1 (Sovereign Mode)
    _ = virtio_net;

    // Initialize Nim Runtime
    NimMain();

    // Call Kernel
    kmain();

    // Halt if return
    rumpk_halt();
}

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

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

export fn console_read() c_int {
    if (uart.read_byte()) |b| {
        return @as(c_int, b);
    }
    return -1;
}

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

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

export fn rumpk_halt() noreturn {
    uart.print("[Rumpk RISC-V] Halting.\n");
    while (true) {
        asm volatile ("wfi");
    }
}

var mock_ticks: u64 = 0;

export fn rumpk_timer_now_ns() u64 {
    // Phase 1 Mock: Incrementing counter to simulate time passage per call
    // This allows Watchdog logic to detect elapsed "time" in coop loop.
    mock_ticks += 100000; // 100us per call
    return mock_ticks;
}
