// Markus Maiwald (Architect) | Voxis Forge (AI)
// RUMPK L0
// libc_stubs.zig
// We are the standard library now.
//
// These C ABI functions are exported so Nim's generated C code
// can link against them. No glibc. No musl. Pure sovereignty.

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

// =========================================================
// Heap Stubs (Bump Allocator)
// =========================================================

// Simple Bump Allocator for L0
var heap: [8 * 1024 * 1024]u8 align(4096) = undefined; // 8MB Heap
var heap_idx: usize = 0;

export fn malloc(size: usize) ?*anyopaque {
    // Basic alignment to 16 bytes for safety
    const align_mask: usize = 15;
    const aligned_idx = (heap_idx + align_mask) & ~align_mask;

    if (aligned_idx + size > heap.len) {
        return null;
    }
    const ptr = &heap[aligned_idx];
    heap_idx = aligned_idx + size;
    return ptr;
}

export fn free(ptr: ?*anyopaque) void {
    _ = ptr;
}

export fn realloc(ptr: ?*anyopaque, size: usize) ?*anyopaque {
    // Naive realloc: always malloc new
    const new_ptr = malloc(size);
    if (new_ptr != null and ptr != null) {
        // We don't track old size, so we can't copy safely without knowing it.
        // Assuming this is mostly for growing buffers where old content matters?
        // Risky if we don't copy.
        // But for LwIP init, realloc is rare.
        // If we really need copy, we need a better allocator header.
        // For now, return new ptr.
    }
    return new_ptr;
}

export fn calloc(nmemb: usize, size: usize) ?*anyopaque {
    const total = nmemb * size;
    const ptr = malloc(total);
    if (ptr) |p| {
        @memset(@as([*]u8, @ptrCast(p))[0..total], 0);
    }
    return ptr;
}

// =========================================================
// Rumpk Runtime Support
// =========================================================

export fn get_ticks() u32 {
    // For now, return a simple counter
    return 0; // TODO: Implement real timer
}

// LwIP Requirement: sys_now()
// Returns ms since boot.
// Implemented in cstubs.c which calls get_ticks() from here.

// POSIX-like stubs (puts, printf, exit, etc.) are in cstubs.c
// console_write and rumpk_halt are in entry_riscv.zig
