/**
 * Android PDA 语音播报（系统 TextToSpeech）
 * App 端可用；非 App 环境静默跳过。
 */
let ttsInstance = null;
let ttsReady = false;
let ttsInitStarted = false;
const pendingQueue = [];

function flushPending() {
	if (!ttsReady || !ttsInstance) return;
	while (pendingQueue.length) {
		const text = pendingQueue.shift();
		doSpeak(text);
	}
}

function doSpeak(text) {
	if (!ttsInstance || !text) return;
	try {
		const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech');
		// QUEUE_FLUSH：打断当前播报，立即播新内容
		ttsInstance.speak(String(text), TextToSpeech.QUEUE_FLUSH, null);
	} catch (e) {
		console.warn('[tts] speak failed', e);
	}
}

export function initTts() {
	// #ifdef APP-PLUS
	if (ttsInitStarted || typeof plus === 'undefined') return;
	if (plus.os.name !== 'Android') return;
	ttsInitStarted = true;
	try {
		const main = plus.android.runtimeMainActivity();
		const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech');
		const Locale = plus.android.importClass('java.util.Locale');
		ttsInstance = new TextToSpeech(
			main,
			plus.android.implements('android.speech.tts.TextToSpeech$OnInitListener', {
				onInit(status) {
					if (status === TextToSpeech.SUCCESS) {
						try {
							ttsInstance.setLanguage(Locale.CHINA);
							ttsInstance.setSpeechRate(1.0);
						} catch (e) {
							console.warn('[tts] setLanguage failed', e);
						}
						ttsReady = true;
						flushPending();
					} else {
						console.warn('[tts] init status not SUCCESS', status);
						ttsReady = false;
					}
				},
			})
		);
	} catch (e) {
		console.warn('[tts] init failed', e);
		ttsInitStarted = false;
	}
	// #endif
}

/**
 * 播报中文文本；TTS 未就绪时先入队，初始化成功后补播。
 * @param {string} text
 */
export function speak(text) {
	const content = (text || '').trim();
	if (!content) return;
	// #ifdef APP-PLUS
	if (typeof plus === 'undefined' || plus.os.name !== 'Android') return;
	if (!ttsInitStarted) initTts();
	if (ttsReady && ttsInstance) {
		doSpeak(content);
		return;
	}
	pendingQueue.push(content);
	// 避免异常堆积
	if (pendingQueue.length > 5) pendingQueue.splice(0, pendingQueue.length - 5);
	// #endif
}

export function stopSpeak() {
	// #ifdef APP-PLUS
	if (!ttsInstance) return;
	try {
		ttsInstance.stop();
	} catch (e) {
		/* ignore */
	}
	// #endif
}
