// Benchmark: feel-wasm (one-shot vs compiled) vs feelin (JS engine).
//
// Prerequisites:
//   wasm-pack build crates/feel-wasm --target nodejs
//   cd crates/feel-wasm && npm install
// Run:
//   node bench.mjs            (or: npm run bench)
//
// Measures, per workload, the throughput of three strategies:
//   1. feel-wasm one-shot  — evaluate(src, ctx): parse + JS<->WASM boundary each call
//   2. feel-wasm compiled  — compile(src) once, then prog.evaluate(ctx): parse once
//   3. feelin              — evaluate(src, ctx): the JS engine, parses each call
//
// (1) vs (2) shows the parse-once win; (2) vs (3) is the cross-engine comparison.

import { evaluate as wasmEvaluate, compile as wasmCompile } from "./pkg/feel_wasm.js";
import { evaluate as feelinEvaluate } from "feelin";

// Same three workloads as the feel-core criterion bench, so numbers line up.
// [label, expression, context]
const workloads = [
  ["trivial", "1 + 1", {}],
  ["decision", 'if person.age >= 18 then "adult" else "minor"', { person: { age: 21 } }],
  ["loop", "for i in [1,2,3,4,5] return i * 2", {}],
];

const ITERATIONS = 50_000;
const WARMUP = 2_000;

// Time `fn` over `iters` runs after `warmup` warmup runs; return ns per op.
function timeNsPerOp(fn, iters = ITERATIONS, warmup = WARMUP) {
  for (let i = 0; i < warmup; i++) fn();
  const start = performance.now();
  for (let i = 0; i < iters; i++) fn();
  const elapsedMs = performance.now() - start;
  return (elapsedMs * 1e6) / iters;
}

const fmt = (ns) => {
  const opsPerSec = 1e9 / ns;
  return `${ns.toFixed(1).padStart(10)} ns/op  ${Math.round(opsPerSec).toLocaleString().padStart(13)} ops/s`;
};

// Sanity-check that all three strategies agree before timing.
function assertAgreement(label, src, ctx) {
  const a = JSON.stringify(wasmEvaluate(src, ctx));
  const prog = wasmCompile(src);
  const b = JSON.stringify(prog.evaluate(ctx));
  prog.free();
  let c;
  try {
    // feelin's evaluate returns { value, warnings }; compare the value.
    c = JSON.stringify(feelinEvaluate(src, ctx).value);
  } catch (e) {
    c = `<feelin error: ${e.message}>`;
  }
  const note = a === c ? "" : `  (feelin differs: ${c})`;
  if (a !== b) throw new Error(`${label}: feel-wasm one-shot vs compiled disagree (${a} vs ${b})`);
  console.log(`# ${label}: "${src}" -> ${a}${note}`);
}

console.log(`# ${ITERATIONS.toLocaleString()} iterations per measurement, ${WARMUP.toLocaleString()} warmup\n`);

for (const [label, src, ctx] of workloads) {
  assertAgreement(label, src, ctx);

  const oneShot = timeNsPerOp(() => wasmEvaluate(src, ctx));

  const prog = wasmCompile(src);
  const compiled = timeNsPerOp(() => prog.evaluate(ctx));
  prog.free();

  const feelin = timeNsPerOp(() => feelinEvaluate(src, ctx));

  console.log(`  feel-wasm one-shot   ${fmt(oneShot)}`);
  console.log(`  feel-wasm compiled   ${fmt(compiled)}`);
  console.log(`  feelin               ${fmt(feelin)}`);
  console.log(`  -> compiled is ${(oneShot / compiled).toFixed(1)}x the one-shot path; ` +
    `${(feelin / compiled).toFixed(1)}x feelin (compiled), ${(feelin / oneShot).toFixed(2)}x feelin (one-shot)\n`);
}
