import { duck, unduck } from "tauri-plugin-duck-api";
import { invoke } from "@tauri-apps/api/core";
import { m } from "$lang/messages";
import { locales, type Locale } from "$lang/runtime";

export let tts: "tauri" | "web" | null = null;

export async function initTTS() {
	if (window.__TAURI__) {
		console.log("Using Tauri TTS");
		tts = "tauri";
	} else {
		console.log("Using Web TTS");
		tts = "web";
	}
}

export function findLocaleForValhallaLanguage(language: string) {
	for(const locale of locales) {
		if(m["language.valhalla"]({ language }, { locale }) === language) {
			return locale;
		}
	}
}

export default async function say(text: string, language?: Locale) {
	if (!tts) {
		// alert("TTS not initialized");
		// console.error("TTS not initialized");
		await initTTS();
		// return;
	}
	duck();
	if (tts !== "web") {
		try {
			await invoke("plugin:tts|speak", { text, language: language ? m["language.tts"]({}, { locale: language }) : m["language.tts"]() });
		} catch (e) {
			console.error("Error speaking text", e);
			alert(e);
		}
	} else {
		const utterance = new SpeechSynthesisUtterance(text);
		utterance.lang = m["language.speechSynthesis"]();
		window.speechSynthesis.speak(utterance);
	}
	unduck();
}
