#!/usr/bin/env node
/**
 * Capture what five JSON parsers actually do with comments (// line comments,
 * /* block comments *\/) embedded in otherwise-valid JSON: whether they accept
 * the input, the exact error string when they do not, and whatever
 * line/column/offset that parser reports.
 *
 * Parsers:
 *   - V8 (Node.js built-in JSON.parse) — the parser behind every browser and
 *     behind FormatArc's own json-formatter tool.
 *   - Python json.loads (stdlib) — invoked as a subprocess via python-runner.py
 *     so the message is Python's own, not a Node re-implementation.
 *   - jq — invoked as a subprocess if installed; recorded as unavailable
 *     (never guessed) if it is not on PATH.
 *   - json5 (npm) — a JSON superset that is specified to allow comments.
 *   - jsonc-parser (npm, the parser VS Code uses for .jsonc/.json-with-comments)
 *     — returns an `errors` array instead of throwing, so that array is kept
 *     verbatim rather than collapsed into a single message.
 *
 * Run:
 *   cd scripts/benchmarks/json-comments-parser-errors
 *   npm install
 *   node measure.mjs            # prints JSON, writes results.json
 */
import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import os from "node:os";

import JSON5 from "json5";
import * as jsonc from "jsonc-parser";

const __dirname = dirname(fileURLToPath(import.meta.url));
const cases = JSON.parse(readFileSync(join(__dirname, "cases.json"), "utf8"));

// ---- V8 (JSON.parse) --------------------------------------------------

function extractV8Position(message) {
  const posMatch = message.match(/position (\d+)/);
  const lineColMatch = message.match(/line (\d+) column (\d+)/);
  if (!posMatch && !lineColMatch) return null;
  return {
    offset: posMatch ? Number(posMatch[1]) : null,
    line: lineColMatch ? Number(lineColMatch[1]) : null,
    column: lineColMatch ? Number(lineColMatch[2]) : null,
  };
}

function runV8(c) {
  try {
    JSON.parse(c.input);
    return { accepted: true, message: null, position: null };
  } catch (e) {
    return { accepted: false, message: e.message, position: extractV8Position(e.message) };
  }
}

// ---- json5 --------------------------------------------------------------

function runJson5(c) {
  try {
    JSON5.parse(c.input);
    return { accepted: true, message: null, position: null };
  } catch (e) {
    const hasPos = typeof e.lineNumber === "number" && typeof e.columnNumber === "number";
    return {
      accepted: false,
      message: e.message,
      position: hasPos
        ? { line: e.lineNumber, column: e.columnNumber, offset: typeof e.offset === "number" ? e.offset : null }
        : null,
    };
  }
}

// ---- jsonc-parser ---------------------------------------------------------
// parse() does lenient error recovery: it can return a value AND report
// errors at the same time (e.g. a single trailing comma is skipped over).
// "accepted" is defined here as "no errors reported", matching how the other
// parsers use accepted = did-not-reject. The raw errors array (numeric error
// codes translated to their printable name via jsonc.printParseErrorCode) is
// kept as-is per the measurement spec, not collapsed into one string.

function runJsonc(c) {
  const errors = [];
  jsonc.parse(c.input, errors);
  if (errors.length === 0) {
    return { accepted: true, message: null, position: null };
  }
  const named = errors.map((e) => ({
    error: jsonc.printParseErrorCode(e.error),
    offset: e.offset,
    length: e.length,
  }));
  return {
    accepted: false,
    message: named.map((e) => `${e.error} at offset ${e.offset}`).join("; "),
    position: { offset: named[0].offset, line: null, column: null },
    errors: named,
  };
}

// ---- Python (subprocess) ---------------------------------------------------

function runPython() {
  const stdout = execFileSync("python3", [join(__dirname, "python-runner.py")], {
    input: JSON.stringify(cases),
    encoding: "utf8",
  });
  return JSON.parse(stdout);
}

// ---- jq (subprocess, optional) --------------------------------------------

function jqAvailable() {
  try {
    execFileSync("jq", ["--version"], { encoding: "utf8" });
    return true;
  } catch {
    return false;
  }
}

function extractJqPosition(message) {
  const m = message.match(/line (\d+), column (\d+)/);
  if (!m) return null;
  return { line: Number(m[1]), column: Number(m[2]), offset: null };
}

function runJq(c) {
  try {
    execFileSync("jq", ["."], { input: c.input, encoding: "utf8" });
    return { accepted: true, message: null, position: null };
  } catch (e) {
    // execFileSync throws on non-zero exit; stderr carries jq's own message.
    const message = String(e.stderr || e.message).trim();
    return { accepted: false, message, position: extractJqPosition(message) };
  }
}

// ---- run everything ---------------------------------------------------

const jqOk = jqAvailable();
const pythonResults = runPython();

const jsonVersion = JSON.parse(readFileSync(join(__dirname, "node_modules/json5/package.json"), "utf8")).version;
const jsoncVersion = JSON.parse(
  readFileSync(join(__dirname, "node_modules/jsonc-parser/package.json"), "utf8"),
).version;
const jqVersion = jqOk ? execFileSync("jq", ["--version"], { encoding: "utf8" }).trim() : null;
const pythonVersion = execFileSync("python3", ["--version"], { encoding: "utf8" }).trim();

const resultCases = cases.map((c) => {
  const parsers = {
    [`V8 (Node.js ${process.version}) JSON.parse`]: runV8(c),
    [`Python ${pythonVersion.replace(/^Python /, "")} json.loads`]: pythonResults[c.id],
    [`jq ${jqVersion || "(not installed)"}`]: jqOk
      ? runJq(c)
      : { available: false, accepted: null, message: null, position: null },
    [`json5 ${jsonVersion}`]: runJson5(c),
    [`jsonc-parser ${jsoncVersion}`]: runJsonc(c),
  };
  return { id: c.id, description: c.description, input: c.input, parsers };
});

const payload = {
  generatedAt: new Date().toISOString(),
  environment: {
    node: process.version,
    python: pythonVersion.replace(/^Python /, ""),
    jq: jqOk ? jqVersion.replace(/^jq-/, "") : null,
    jqAvailable: jqOk,
    json5: jsonVersion,
    jsoncParser: jsoncVersion,
    os: `${os.type()} ${os.release()}`,
    machine: os.cpus()[0]?.model || os.arch(),
  },
  cases: resultCases,
};

writeFileSync(join(__dirname, "results.json"), JSON.stringify(payload, null, 2) + "\n");
console.log(JSON.stringify(payload, null, 2));
