// run_native_seed.ce — load and run a native .dylib module (seed mode)
// Usage: ./cell --dev --seed run_native_seed benches/fibonacci

var fd = use("fd")
var os = use("os")

if (length(args) < 1) {
  print("usage: cell --dev --seed run_native_seed <module>")
  disrupt
}

var name = args[0]
if (ends_with(name, ".cm")) {
  name = text(name, 0, length(name) - 3)
}

var safe = replace(replace(name, "/", "_"), "-", "_")
var symbol = "js_" + safe + "_use"
var dylib_path = "./" + name + ".cm.dylib"

var test_arg = 30
if (length(args) > 1) {
  test_arg = number(args[1])
}

// --- Interpreted run ---
print("--- interpreted ---")
var t1 = os.now()
var mod_interp = use(name)
var t2 = os.now()
var result_interp = null
if (is_function(mod_interp)) {
  print("module returns a function, calling with " + text(test_arg))
  t1 = os.now()
  result_interp = mod_interp(test_arg)
  t2 = os.now()
}
result_interp = result_interp != null ? result_interp : mod_interp
var ms_interp = (t2 - t1) / 1000000
print("result: " + text(result_interp))
print("time:   " + text(ms_interp) + " ms")

// --- Native run ---
if (!fd.is_file(dylib_path)) {
  print("\nno " + dylib_path + " found")
  disrupt
}

print("\n--- native ---")
var t3 = os.now()
var lib = os.dylib_open(dylib_path)
var t4 = os.now()
var mod_native = os.dylib_symbol(lib, symbol)
var t5 = os.now()
var result_native = null
if (is_function(mod_native)) {
  print("module returns a function, calling with " + text(test_arg))
  t4 = os.now()
  result_native = mod_native(test_arg)
  t5 = os.now()
}
result_native = result_native != null ? result_native : mod_native
var ms_native = (t5 - t3) / 1000000
var ms_exec = (t5 - t4) / 1000000
print("result: " + text(result_native))
print("load:   " + text((t4 - t3) / 1000000) + " ms")
print("exec:   " + text(ms_exec) + " ms")
print("total:  " + text(ms_native) + " ms")

// --- Comparison ---
print("\n--- comparison ---")
print("match:  " + text(result_interp == result_native))
if (ms_native > 0) {
  print("speedup: " + text(ms_interp / ms_native) + "x (total)")
}
if (ms_exec > 0) {
  print("speedup: " + text(ms_interp / ms_exec) + "x (exec only)")
}
