import { isWechatBrowser } from '../utils/wechat';
import { MicCapture } from './micCapture';
import { isSpeechRecognitionSupported } from './speechRecognition';

/** 微信内置浏览器 Web Speech 不可用，直接走服务端 ASR。 */
export function shouldPreferServerAsr(): boolean {
  return isWechatBrowser();
}

/** Web Speech 出现这些错误时可改用服务端 ASR（录音 + 完成识别）。 */
export function shouldFallbackToServerAsr(errorMessage: string): boolean {
  if (shouldPreferServerAsr()) return false;
  if (!MicCapture.isSupported()) return false;
  return /network|service-not-allowed|语音识别失败|无法启动语音识别/i.test(errorMessage);
}

/** Whether voice input may work in this browser (mic and/or live speech). */
export function isVoiceInputAvailable(): boolean {
  if (typeof navigator === 'undefined') return false;
  if (isWechatBrowser()) return true;
  if (MicCapture.isSupported()) return true;
  if (isSpeechRecognitionSupported() && !shouldPreferServerAsr()) return true;
  return Boolean(navigator.mediaDevices?.getUserMedia);
}

/** Show the mic control in chat; availability is checked on click. */
export function shouldShowVoiceInputControl(): boolean {
  return typeof window !== 'undefined';
}
