#!/usr/bin/env node

import { listAudioDevices } from "./list-devices.js";
import { spawn } from "child_process";
import readline from "node:readline";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const here = dirname(fileURLToPath(import.meta.url));

async function testDevice(deviceId) {
	console.log(`\nTesting device ${deviceId}...`);
	console.log("Speak into your microphone. Press Ctrl+C to stop.\n");

	const voiceScript = join(here, "voice.js");
	// Pass empty string for soxPath (will use default), then deviceId
	const args = deviceId ? [voiceScript, "", deviceId] : [voiceScript];
	const proc = spawn("node", args, {
		stdio: ["pipe", "inherit", "inherit"],
	});

	// Send test grammar
	proc.stdin.write("update,hello,test,lumia\n");

	return new Promise((resolve) => {
		proc.on("close", () => {
			resolve();
		});

		// Allow user to stop with Ctrl+C
		process.on("SIGINT", () => {
			proc.kill();
			resolve();
		});
	});
}

async function main() {
	console.log("LumiaWakeWord Audio Device Tester");
	console.log("==================================\n");

	try {
		const devices = await listAudioDevices();

		if (process.platform !== "win32") {
			console.log("Note: On macOS/Linux, the default audio input is used automatically.");
			console.log("Device selection is primarily for Windows users.\n");
		}

		console.log("Available audio input devices:");
		devices.forEach((device) => {
			console.log(`  ${device.id}: ${device.name}`);
		});

		if (process.platform === "win32") {
			const rl = readline.createInterface({
				input: process.stdin,
				output: process.stdout,
			});

			const deviceId = await new Promise((resolve) => {
				rl.question(
					"\nEnter device ID to test (or press Enter for default): ",
					(answer) => {
						rl.close();
						resolve(answer.trim() || "0");
					}
				);
			});

			await testDevice(deviceId);

			console.log("\n\nTo use this device permanently, you can:");
			console.log(`1. Set environment variable: AUDIO_DEVICE=${deviceId}`);
			console.log(`2. Pass as 3rd argument when running voice.js`);
			console.log(`3. Update your application to pass the device ID\n`);
		} else {
			console.log("\nTesting default audio input...");
			await testDevice(null);
		}
	} catch (err) {
		console.error("Error:", err);
		process.exit(1);
	}
}

main();