use anyhow::Context as _;

struct ScriptError;

impl std::fmt::Display for ScriptError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Script error")
    }
}

const MEMORY_LIMIT: usize = 30 * 1024;
const INSTRUCTION_LIMIT: u32 = 10000;

pub fn setup_lua() -> anyhow::Result<mlua::Lua> {
    let lua = mlua::Lua::new_with(
        mlua::StdLib::ALL_SAFE ^ mlua::StdLib::OS,
        mlua::LuaOptions::new(),
    )?;
    lua.set_memory_limit(MEMORY_LIMIT)?;
    lua.set_global_hook(
        mlua::HookTriggers::new().every_nth_instruction(INSTRUCTION_LIMIT),
        move |_, _| {
            Err(mlua::Error::RuntimeError(
                "instruction limit exceeded".into(),
            ))
        },
    )?;
    Ok(lua)
}

pub fn render_hash(lua_src: &str, note: u32, velocity: u32) -> anyhow::Result<[u8; 32]> {
    let lua = setup_lua()?;
    lua.load(lua_src).exec().context(ScriptError)?;
    let func: mlua::Function = lua
        .globals()
        .get("sample")
        .context("missing sample function")?;

    use sha2::Digest as _;
    let mut hasher = sha2::Sha256::new();
    for i in 0..64u32 {
        let v: f64 = func
            .call((i as f64 / 44_100.0, note, velocity))
            .context(ScriptError)?;
        let normalized_v = v.clamp(-1.0, 1.0);
        hasher.update(normalized_v.to_le_bytes());
    }

    Ok(hasher.finalize().into())
}

pub fn validate(lua_src: &str) -> anyhow::Result<()> {
    let lua = setup_lua()?;
    lua.load(lua_src).exec().context(ScriptError)?;
    let _: mlua::Function = lua
        .globals()
        .get("sample")
        .context("missing sample function")?;
    Ok(())
}
