#include "lwip/opt.h"
#include "lwip/arch.h"
#include "lwip/sys.h"

// External references to console
extern void console_write(const void* p, unsigned long len);

// Simple counter for monotonic time
static volatile u32_t lwip_ticks_ms = 0;

// 1. Initialization (Membrane version - minimal)
void sys_init(void) {
    // Silent init for Membrane
}

// 2. The Time Source
u32_t sys_now(void) {
#if defined(__riscv)
    uint64_t ticks;
    __asm__ volatile ("rdtime %0" : "=r"(ticks));
    // RISC-V QEMU virt is 10MHz -> 1ms = 10,000 ticks
    return (u32_t)(ticks / 10000);
#elif defined(__aarch64__)
    uint64_t ticks;
    __asm__ volatile ("mrs %0, cntvct_el0" : "=r"(ticks));
    // ARM64 QEMU virt is usually 62.5MHz or similar, but often 24MHz
    // Let's assume 1 tick = 1 microsecond (1MHz) for simplicity if we don't know freq
    // Actually, cntfrq_el0 holds the frequency.
    return (u32_t)(ticks / 1000); 
#else
    static volatile u32_t lwip_ticks_ms = 0;
    return ++lwip_ticks_ms;
#endif
}

// 3. Panic handler is in clib.c (nexus_lwip_panic)

// 4. Critical Sections (Stubbed)
#if SYS_LIGHTWEIGHT_PROT
sys_prot_t sys_arch_protect(void) { return 0; }
void sys_arch_unprotect(sys_prot_t pval) { (void)pval; }
#endif
