import { $ } from "bun";
import * as fs from "fs/promises";
import * as path from "path";
import * as os from "os";
import toml from "toml";

if (!(await fs.exists(path.join(process.cwd(), "Cargo.toml")))) {
  throw new Error("Please run this script in the project's root directory.");
}

console.log("Running benchmark...");

const output = await $`cargo bench --bench convert_bench`.text();

const start = output.indexOf("convert()");
if (start === -1) {
  throw new Error(`Unexpected benchmark result:\n${output}`);
}

const result = output.substring(start).trim();
console.log(`Result:\n${result}`);

await writeResultReadme(result);

console.log("Saved result to benches/README.md");

function osCpus(): string {
  const cpus = new Map<string, number>();
  for (const cpu of os.cpus()) {
    cpus.set(cpu.model, (cpus.get(cpu.model) ?? 0) + 1);
  }
  return [...cpus.entries()]
    .map(([cpu, count]) => `${cpu} x ${count}`)
    .join("\n");
}

function osMemoryGB(): string {
  return (os.totalmem() / (1024 * 1024 * 1024)).toFixed(1) + " GB";
}

async function libVersion(): Promise<string> {
  const tomlString = (await fs.readFile("Cargo.toml")).toString();
  const cargo = toml.parse(tomlString);
  return cargo.package.version;
}

async function writeResultReadme(result: string) {
  const md = `# Benchmark

A benchmark converts [Elon Musk - Wikipedia.html](<../examples/page-to-markdown/html/Elon Musk - Wikipedia.html>) to Markdown, IO time is not included.

library version: ${await libVersion()}

# Environment

System: ${os.platform()} ${os.arch()} ${os.version()}

CPUs: ${osCpus()}

Memory: ${osMemoryGB()}

# Result

\`\`\`
${result}
\`\`\`

*Updated at ${new Date().toUTCString()}*

*Generated by [bench.ts](bench.ts)*
`;
  fs.writeFile(path.join(process.cwd(), "benches/README.md"), md);
}
