#[cfg(not(target_arch = "riscv64"))]
mod ebpf;

#[cfg(target_arch = "riscv64")]
mod risc_v;

#[cfg(not(target_arch = "riscv64"))]
pub mod definitions {
    pub use crate::ebpf::*;
}

#[cfg(target_arch = "riscv64")]
pub mod definitions {
    pub use crate::risc_v::*;
}

/// Not part of the public API. Used by macros.
#[cfg(target_arch = "riscv64")]
#[doc(hidden)]
pub mod __private {
    pub use polkavm_derive::{self, default_abi};
}

#[cfg(all(target_feature = "static-syscalls", not(target_arch = "riscv64")))]
#[macro_export]
macro_rules! define_syscall {
    (fn $name:ident($($arg:ident: $typ:ty),*) -> $ret:ty) => {
        #[inline]
        pub unsafe fn $name($($arg: $typ),*) -> $ret {
            // this enum is used to force the hash to be computed in a const context
            #[repr(usize)]
            enum Syscall {
                Code = $crate::sys_hash(stringify!($name)),
            }

            let syscall: extern "C" fn($($arg: $typ),*) -> $ret = core::mem::transmute(Syscall::Code);
            syscall($($arg),*)
        }

    };
    (fn $name:ident($($arg:ident: $typ:ty),*)) => {
        define_syscall!(fn $name($($arg: $typ),*) -> ());
    }
}

#[cfg(all(not(target_feature = "static-syscalls"), not(target_arch = "riscv64")))]
#[macro_export]
macro_rules! define_syscall {
    (fn $name:ident($($arg:ident: $typ:ty),*) -> $ret:ty) => {
        extern "C" {
            pub fn $name($($arg: $typ),*) -> $ret;
        }
    };
    (fn $name:ident($($arg:ident: $typ:ty),*)) => {
        define_syscall!(fn $name($($arg: $typ),*) -> ());
    }
}

/// RISC-V syscall definition macro using PolkaVM imports.
///
/// Unlike BPF which uses symbol resolution or hash-based dispatch,
/// RISC-V/PolkaVM requires explicit import metadata via `#[polkavm_import]`.
#[cfg(target_arch = "riscv64")]
#[macro_export]
macro_rules! define_syscall_riscv {
    (fn $name:ident($($arg:ident: $typ:ty),*) -> $ret:ty) => {
        // Workaround: `abi = ...` overrides the generated code's crate path (similar to
        // `#[serde(crate = "...")]`), letting us point it at this crate's re-export
        // so downstream crates don't need a direct `polkavm-derive` dependency.
        // See: https://github.com/paritytech/polkavm/blob/master/crates/polkavm-derive-impl/src/import.rs
        #[$crate::__private::polkavm_derive::polkavm_import(abi = $crate::__private::polkavm_derive::default_abi)]
        extern "C" {
            pub fn $name($($arg: $typ),*) -> $ret;
        }
    };
    (fn $name:ident($($arg:ident: $typ:ty),*)) => {
        $crate::define_syscall_riscv!(fn $name($($arg: $typ),*) -> ());
    }
}

/// Stub for non-RISC-V targets to produce a clear compile error.
#[cfg(not(target_arch = "riscv64"))]
#[macro_export]
macro_rules! define_syscall_riscv {
    ($($tt:tt)*) => {
        compile_error!("define_syscall_riscv! is only available on RISC-V targets");
    };
}

#[cfg(all(target_feature = "static-syscalls", not(target_arch = "riscv64")))]
pub const fn sys_hash(name: &str) -> usize {
    murmur3_32(name.as_bytes(), 0) as usize
}

#[cfg(all(target_feature = "static-syscalls", not(target_arch = "riscv64")))]
const fn murmur3_32(buf: &[u8], seed: u32) -> u32 {
    const fn pre_mix(buf: [u8; 4]) -> u32 {
        u32::from_le_bytes(buf)
            .wrapping_mul(0xcc9e2d51)
            .rotate_left(15)
            .wrapping_mul(0x1b873593)
    }

    let mut hash = seed;

    let mut i = 0;
    while i < buf.len() / 4 {
        let buf = [buf[i * 4], buf[i * 4 + 1], buf[i * 4 + 2], buf[i * 4 + 3]];
        hash ^= pre_mix(buf);
        hash = hash.rotate_left(13);
        hash = hash.wrapping_mul(5).wrapping_add(0xe6546b64);

        i += 1;
    }

    match buf.len() % 4 {
        0 => {}
        1 => {
            hash = hash ^ pre_mix([buf[i * 4], 0, 0, 0]);
        }
        2 => {
            hash = hash ^ pre_mix([buf[i * 4], buf[i * 4 + 1], 0, 0]);
        }
        3 => {
            hash = hash ^ pre_mix([buf[i * 4], buf[i * 4 + 1], buf[i * 4 + 2], 0]);
        }
        _ => { /* unreachable!() */ }
    }

    hash = hash ^ buf.len() as u32;
    hash = hash ^ (hash.wrapping_shr(16));
    hash = hash.wrapping_mul(0x85ebca6b);
    hash = hash ^ (hash.wrapping_shr(13));
    hash = hash.wrapping_mul(0xc2b2ae35);
    hash = hash ^ (hash.wrapping_shr(16));

    hash
}
