import assert from "node:assert/strict";
import { createRequire } from "node:module";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, test } from "vitest";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);

const addonDir = path.resolve(
	__dirname,
	"..",
	"..",
	"..",
	"..",
	"rust-engine",
	"addon",
);
const platformTag = `${process.platform}-${process.arch}`;
const candidates = [
	path.join(addonDir, `forge_engine.${platformTag}.node`),
	path.join(addonDir, "forge_engine.dev.node"),
];

let native;
for (const candidate of candidates) {
	try {
		native = require(candidate);
		break;
	} catch {
		// try next
	}
}

if (!native) {
	console.error("Native addon not found. Run build:native first.");
	process.exit(1);
}

function isClipboardUnavailableError(error) {
	const message = error instanceof Error ? error.message : String(error);
	return /Failed to access clipboard|X11 server|Wayland|clipboard/i.test(
		message,
	);
}

function ignoreUnavailableClipboard(error) {
	if (!isClipboardUnavailableError(error)) throw error;
}

describe("native clipboard: copyToClipboard()", () => {
	test("copies text without throwing", () => {
		try {
			native.copyToClipboard("SF clipboard test");
		} catch (error) {
			ignoreUnavailableClipboard(error);
		}
	});

	test("accepts empty string", () => {
		try {
			native.copyToClipboard("");
		} catch (error) {
			ignoreUnavailableClipboard(error);
		}
	});

	test("accepts unicode text", () => {
		try {
			native.copyToClipboard("Hello 世界");
		} catch (error) {
			ignoreUnavailableClipboard(error);
		}
	});
});

describe("native clipboard: readTextFromClipboard()", () => {
	test("reads back text that was copied", () => {
		const testText = `SF clipboard roundtrip ${Date.now()}`;
		try {
			native.copyToClipboard(testText);
			const result = native.readTextFromClipboard();
			assert.equal(result, testText);
		} catch (error) {
			ignoreUnavailableClipboard(error);
		}
	});

	test("returns a string or null", () => {
		try {
			const result = native.readTextFromClipboard();
			assert.ok(result === null || typeof result === "string");
		} catch (error) {
			ignoreUnavailableClipboard(error);
		}
	});
});

describe("native clipboard: readImageFromClipboard()", () => {
	test("returns a promise", async () => {
		const result = native.readImageFromClipboard();
		assert.ok(result instanceof Promise);
		try {
			await result;
		} catch (error) {
			ignoreUnavailableClipboard(error);
		}
	});

	test("resolves to ClipboardImage or null", async () => {
		let result;
		try {
			result = await native.readImageFromClipboard();
		} catch (error) {
			ignoreUnavailableClipboard(error);
			return;
		}
		if (result !== null) {
			assert.ok(result.data instanceof Uint8Array, "data should be Uint8Array");
			assert.equal(result.mimeType, "image/png");
		}
	});
});
