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

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

/**
 * List available audio input devices
 * @returns {Promise<Array<{id: string, name: string}>>} Array of available devices
 */
export { listAudioDevices };

/**
 * Start the wake word detection with optional device selection
 * @param {Object} options - Configuration options
 * @param {string} [options.device] - Audio device ID to use
 * @param {string} [options.soxPath] - Path to SoX binary
 * @param {number} [options.sampleRate] - Sample rate (default: 16000)
 * @param {Array<string>} [options.grammar] - Wake words to detect
 * @param {number} [options.confidence] - Confidence threshold (0-1)
 * @param {string} [options.modelPath] - Full path to a Vosk model directory
 * @returns {ChildProcess} The spawned voice detection process
 */
export function startWakeWord(options = {}) {
	const {
		device = null,
		soxPath = null,
		sampleRate = 16000,
		grammar = [],
		confidence = 0.7,
		modelPath = null,
	} = options;

	const voiceScript = join(here, "voice.js");
	const args = [voiceScript];

	if (soxPath) {
		args.push(soxPath);
	} else {
		args.push(""); // placeholder for default sox path
	}

	if (device) {
		args.push(device);
	}

	const env = { ...process.env };
	if (sampleRate) {
		env.SAMPLE_RATE = sampleRate.toString();
	}
	if (device && !args[2]) {
		env.AUDIO_DEVICE = device;
	}
	if (modelPath) {
		env.LUMIA_VOICE_MODEL_PATH = modelPath;
	}

	const proc = spawn("node", args, {
		env,
		stdio: ["pipe", "pipe", "inherit"],
	});

	// Send initial grammar if provided
	if (grammar.length > 0) {
		proc.stdin.write(`update,${grammar.join(",")}\n`);
	}

	// Send confidence threshold if provided
	if (confidence !== 0.7) {
		proc.stdin.write(`confidence,${confidence}\n`);
	}

	return proc;
}

export default {
	listAudioDevices,
	startWakeWord,
};
