import { getDB } from "../app";
import { getSettings } from "../storage/db";

let cachedVoice: SpeechSynthesisVoice | null = null;

function findGermanVoice(): SpeechSynthesisVoice | null {
	if (cachedVoice) return cachedVoice;
	if (!window.speechSynthesis) return null;

	const voices = window.speechSynthesis.getVoices();
	const voice = voices.find((v) => v.lang.startsWith("de")) ?? null;
	if (voice) {
		cachedVoice = voice;
	}
	return voice;
}

// Voices may load async — cache when ready
if (typeof window !== "undefined" && window.speechSynthesis) {
	window.speechSynthesis.onvoiceschanged = () => {
		findGermanVoice();
	};
	// Try immediately (some browsers have voices ready synchronously)
	findGermanVoice();
}

/**
 * Speak German text via Web Speech API.
 * Checks speechEnabled setting. Silent fallback on any error.
 */
export async function speakText(text: string): Promise<void> {
	try {
		if (!window.speechSynthesis) return;

		const db = getDB();
		const settings = await getSettings(db);
		if (settings?.speechEnabled !== true) return;

		const utterance = new SpeechSynthesisUtterance(text);
		utterance.lang = "de-DE";
		utterance.rate = 0.9;
		utterance.pitch = 1.1;

		const voice = findGermanVoice();
		if (voice) {
			utterance.voice = voice;
		}

		window.speechSynthesis.speak(utterance);
	} catch {
		// Silent fallback — never throw to caller
	}
}
