import { spawn } from "node:child_process";

export interface BrowserOpenResult {
	ok: boolean;
	error?: string;
}

export async function openInBrowser(filePath: string): Promise<BrowserOpenResult> {
	const platform = process.platform;

	if (platform === "darwin") {
		return run("open", [filePath]);
	}

	if (platform === "linux") {
		return run("xdg-open", [filePath]);
	}

	if (platform === "win32") {
		return run("cmd", ["/c", "start", "", filePath]);
	}

	return { ok: false, error: `Unsupported platform: ${platform}` };
}

function run(command: string, args: string[]): Promise<BrowserOpenResult> {
	return new Promise((resolve) => {
		const child = spawn(command, args, {
			stdio: ["ignore", "ignore", "pipe"],
		});

		let stderr = "";
		let settled = false;

		child.stderr?.on("data", (chunk: Buffer | string) => {
			stderr += chunk.toString();
		});

		child.once("error", (error) => {
			if (settled) {
				return;
			}
			settled = true;
			resolve({ ok: false, error: error.message });
		});

		child.once("close", (code) => {
			if (settled) {
				return;
			}
			settled = true;
			if (code === 0) {
				resolve({ ok: true });
				return;
			}

			const detail = stderr.trim();
			resolve({
				ok: false,
				error: detail ? `${command} exited with code ${code}: ${detail}` : `${command} exited with code ${code}`,
			});
		});
	});
}
