import test from "node:test";
import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";
import { compile } from "../src/compile.js";

function createLargeModel(instanceCount = 220) {
  const instances = [];
  const nets = [];

  for (let i = 0; i < instanceCount; i += 1) {
    const idx = i + 1;
    instances.push({
      ref: `R${idx}`,
      part: "resistor",
      properties: { value: `${(idx % 100) + 1}k` },
      placement: { x: null, y: null, rotation: 0, locked: false }
    });
  }

  for (let i = 0; i < instanceCount - 1; i += 1) {
    const idx = i + 1;
    nets.push({
      name: `SIG_${idx}`,
      class: "signal",
      nodes: [
        { ref: `R${idx}`, pin: "2" },
        { ref: `R${idx + 1}`, pin: "1" }
      ]
    });
  }

  nets.push({
    name: "GND",
    class: "ground",
    nodes: [
      { ref: "R1", pin: "1" },
      { ref: `R${instanceCount}`, pin: "2" }
    ]
  });

  return {
    meta: { title: "Perf chain" },
    symbols: {},
    instances,
    nets,
    constraints: {},
    annotations: []
  };
}

test("compile remains under baseline perf budget for large synthetic model", () => {
  const model = createLargeModel();
  const started = performance.now();
  const result = compile(model);
  const elapsedMs = performance.now() - started;

  assert.equal(result.ok, true);
  assert.equal(typeof result.layout_metrics.crossings, "number");
  assert.equal(typeof result.layout_metrics.overlap_edges, "number");
  assert.ok(elapsedMs < 5_000, `compile exceeded baseline budget: ${elapsedMs.toFixed(1)}ms`);
});

test("compile handles 500+ instances and 1000+ net nodes within budget", () => {
  const model = createLargeModel(520);
  const totalNodes = model.nets.reduce((sum, net) => sum + (net.nodes?.length ?? 0), 0);
  const started = performance.now();
  const result = compile(model);
  const elapsedMs = performance.now() - started;

  assert.equal(result.ok, true);
  assert.ok(model.instances.length >= 500);
  assert.ok(totalNodes >= 1000);
  assert.ok(elapsedMs < 10_000, `compile exceeded large-scene budget: ${elapsedMs.toFixed(1)}ms`);
});
