// KanuniLabs DataGrid — engine benchmark
// https://kanunilabs.com/benchmarks
//
//   npm install @kanunilabs/datagrid-core
//   node datagrid-pipeline.bench.mjs              # 1,000,000 rows
//   node datagrid-pipeline.bench.mjs 100000
//   node datagrid-pipeline.bench.mjs 1000000 --json
//
// The same data and the same queries go through two paths of the same engine:
//
//   row-based  ClientRowModel. Plain JavaScript over the row objects; the grid
//              uses it on the main thread when the data is small.
//   columnar   runEncodedPipeline over typed-array columns. This is the
//              function the grid's Web Worker runs. It is timed in-process
//              here, so postMessage, buffer transfer and rendering are NOT in
//              these numbers.
//
// Each query is timed 5 times. The script reports the median and, separately,
// the first of the five. They differ for a reason worth knowing: the columnar
// path caches work per column. The first text sort ranks every distinct value
// with Intl.Collator, and the first search lower-cases every distinct value;
// later queries reuse both until the data changes. The first run also pays for
// JIT compilation. Run the script several times: on a laptop the spread
// between runs is real.
import { ColumnModel, ClientRowModel, encodeColumn, runEncodedPipeline } from '@kanunilabs/datagrid-core';

const ROW_COUNT = Number(process.argv.find((a, i) => i > 1 && /^\d+$/.test(a)) ?? 1_000_000);
const JSON_OUT = process.argv.includes('--json');
const REPEATS = 5;

// Deterministic dataset: the same seed gives the same million rows everywhere.
function rng(seed) {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const CATEGORIES = ['Electronics', 'Furniture', 'Grocery', 'Apparel', 'Toys', 'Hardware'];
const REGIONS = ['Marmara', 'Aegean', 'Central', 'Black Sea', 'Mediterranean', 'East'];

function makeRows(count) {
  const rand = rng(42);
  const rows = new Array(count);
  const start = Date.UTC(2023, 0, 1);
  for (let i = 0; i < count; i++) {
    const units = 1 + Math.floor(rand() * 500);
    const unitPrice = Math.round((5 + rand() * 995) * 100) / 100;
    rows[i] = {
      id: i + 1,
      sku: `SKU-${(100000 + i).toString(36).toUpperCase()}`,
      product: `${CATEGORIES[i % CATEGORIES.length]} item ${i + 1}`,
      category: CATEGORIES[Math.floor(rand() * CATEGORIES.length)],
      region: REGIONS[Math.floor(rand() * REGIONS.length)],
      units,
      unitPrice,
      revenue: Math.round(units * unitPrice * 100) / 100,
      orderedAt: new Date(start + Math.floor(rand() * 900) * 86400000).toISOString().slice(0, 10),
    };
  }
  return rows;
}

const columns = [
  { field: 'id', dataType: 'number' },
  { field: 'sku' },
  { field: 'product' },
  { field: 'category' },
  { field: 'region' },
  { field: 'units', dataType: 'number' },
  { field: 'unitPrice', dataType: 'number' },
  { field: 'revenue', dataType: 'number' },
  { field: 'orderedAt', dataType: 'date' },
];

const results = {};

function bench(key, label, fn) {
  const samples = [];
  for (let i = 0; i < REPEATS; i++) {
    const t = performance.now();
    fn();
    samples.push(performance.now() - t);
  }
  const first = samples[0];
  samples.sort((a, b) => a - b);
  const median = samples[Math.floor(samples.length / 2)];
  results[key] = median;
  results[`${key}.first`] = first;
  if (!JSON_OUT) {
    console.log(`   ${label.padEnd(34)} median ${median.toFixed(1).padStart(8)} ms   first ${first.toFixed(1).padStart(8)} ms`);
  }
}

const log = (s) => {
  if (!JSON_OUT) console.log(s);
};

log(`\nKanuniLabs DataGrid engine benchmark — ${ROW_COUNT.toLocaleString('en-US')} rows × ${columns.length} columns\n`);

const rows = makeRows(ROW_COUNT);
const cm = new ColumnModel(columns);
const model = new ClientRowModel(rows, { keyGetter: (r) => r.id });
const NONE = { sort: [], filter: null, searchText: '' };

const Q = {
  sortNumber: { sort: [{ columnId: 'revenue', direction: 'desc' }] },
  sortText: { sort: [{ columnId: 'product', direction: 'asc' }] },
  sortDate: { sort: [{ columnId: 'orderedAt', direction: 'asc' }] },
  sortTwo: { sort: [{ columnId: 'category', direction: 'asc' }, { columnId: 'revenue', direction: 'desc' }] },
  filterEq: { filter: { columnId: 'region', operator: '=', value: 'Marmara' } },
  filterAnd: {
    filter: {
      logic: 'and',
      nodes: [
        { columnId: 'region', operator: '=', value: 'Marmara' },
        { columnId: 'units', operator: '>', value: 250 },
        { columnId: 'category', operator: 'in', value: ['Toys', 'Grocery'] },
      ],
    },
  },
  search: { searchText: 'Marmara' },
  filterSort: {
    sort: [{ columnId: 'revenue', direction: 'desc' }],
    filter: { columnId: 'region', operator: '=', value: 'Marmara' },
  },
};

const LABELS = {
  sortNumber: 'sort — number',
  sortText: 'sort — text',
  sortDate: 'sort — date',
  sortTwo: 'sort — two columns',
  filterEq: 'filter — equality',
  filterAnd: 'filter — AND of 3 clauses',
  search: 'search — free text, all columns',
  filterSort: 'filter + sort',
};

log('── row-based ─────────────────────────────────────────────');
for (const [key, q] of Object.entries(Q)) {
  bench(`row.${key}`, LABELS[key], () => model.compute(cm, { ...NONE, ...q }));
}

log('\n── columnar (the function the worker runs) ───────────────');
const tEncode = performance.now();
const encodedColumns = {};
for (const id of cm.getOrder()) {
  encodedColumns[id] = encodeColumn(rows, cm, id, cm.getDef(id)?.calculateSortValue != null);
}
results.encode = performance.now() - tEncode;
log(`   ${'encode, once per dataset'.padEnd(34)}        ${results.encode.toFixed(0).padStart(8)} ms\n`);

const table = { rowCount: rows.length, columns: encodedColumns };
const searchColumns = cm.getOrder();
for (const [key, q] of Object.entries(Q)) {
  bench(`col.${key}`, LABELS[key], () =>
    runEncodedPipeline(table, { searchColumns, locale: 'en', ...NONE, ...q }),
  );
}

if (JSON_OUT) {
  console.log(JSON.stringify({ rows: ROW_COUNT, columns: columns.length, node: process.version, results }));
} else {
  console.log(`\n   Node ${process.version} · ${process.platform} ${process.arch}\n`);
}
