// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { beforeEach, describe, expect, it } from "vitest";
import { resolveTarget } from "./resolve.js";
import type { Target } from "./types.js";

const bench = join(dirname(fileURLToPath(import.meta.url)), "../bench");
const captured = JSON.parse(
	readFileSync(join(bench, "candidates.json"), "utf8"),
) as {
	targets: { id: string; candidates: Target["candidates"] }[];
};

function load(generation: string): void {
	document.body.innerHTML = readFileSync(join(bench, generation), "utf8");
	HTMLElement.prototype.getBoundingClientRect = () =>
		({
			x: 0,
			y: 0,
			top: 0,
			left: 0,
			right: 120,
			bottom: 40,
			width: 120,
			height: 40,
			toJSON() {},
		}) as DOMRect;
}

function survival(generation: string): number {
	load(generation);
	const hits = captured.targets.filter(
		(target) => resolveTarget(target) !== null,
	);
	return hits.length / captured.targets.length;
}

beforeEach(() => {
	document.body.innerHTML = "";
});

describe("banc de resilience (section 9.2)", () => {
	it("resout 100% des cibles sur la generation 1", () => {
		expect(survival("gen-1.html")).toBe(1);
	});

	it("resout 100% des cibles sur la generation 2 (testid conserves)", () => {
		expect(survival("gen-2.html")).toBe(1);
	});

	it("mesure la survie sur la generation 3 sans seuil bloquant", () => {
		const rate = survival("gen-3.html");
		expect(rate).toBeGreaterThanOrEqual(0);
		expect(rate).toBeLessThan(1);
	});
});
