/**
 * CSV -> Markdown table conversion throughput, measured against the actual
 * production conversion path (lib/tooling.ts runToolConversion).
 *
 * Run:
 *   npx tsx scripts/benchmarks/csv-to-markdown-throughput/measure.ts
 *
 * Writes results.json next to this script. Article numbers must match it.
 */
import { performance } from "node:perf_hooks";
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { runToolConversion } from "../../../lib/tooling";

const HERE = dirname(fileURLToPath(import.meta.url));
const ROW_COUNTS = [10_000, 50_000, 100_000];
const RUNS = 7; // median of 7 warm runs per size

function makeCsv(rows: number): string {
  const lines = ["id,name,email,city,amount"];
  for (let i = 0; i < rows; i++) {
    lines.push(`${i},User ${i},user${i}@example.com,City ${i % 100},${(i * 13) % 10000}`);
  }
  return lines.join("\n");
}

function median(xs: number[]): number {
  const s = [...xs].sort((a, b) => a - b);
  return s[Math.floor(s.length / 2)];
}

const results: Record<string, { rows: number; inputBytes: number; medianMs: number; runsMs: number[] }> = {};

for (const rows of ROW_COUNTS) {
  const csv = makeCsv(rows);
  // warm-up run (not measured)
  runToolConversion("csv-to-markdown", csv, "en");
  const times: number[] = [];
  for (let i = 0; i < RUNS; i++) {
    const t0 = performance.now();
    const res = runToolConversion("csv-to-markdown", csv, "en");
    const t1 = performance.now();
    if (res.error) throw new Error(`conversion failed at ${rows} rows: ${res.error}`);
    times.push(t1 - t0);
  }
  results[`${rows}`] = {
    rows,
    inputBytes: Buffer.byteLength(csv, "utf-8"),
    medianMs: Number(median(times).toFixed(1)),
    runsMs: times.map((t) => Number(t.toFixed(1))),
  };
  console.log(`${rows} rows: median ${median(times).toFixed(1)} ms over ${RUNS} warm runs`);
}

const out = {
  topic: "CSV -> Markdown table conversion throughput (production code path)",
  measuredAt: new Date().toISOString().slice(0, 10),
  environment: {
    machine: "Apple M5 Pro (macOS, Darwin 25.5.0)",
    node: process.version,
    note: "runToolConversion('csv-to-markdown') from lib/tooling.ts (papaparse + remark pipeline), median of 7 warm runs, 5-column synthetic CSV",
  },
  results,
};
writeFileSync(join(HERE, "results.json"), JSON.stringify(out, null, 2) + "\n");
console.log("results.json written");
