import 'package:flutter_tts/flutter_tts.dart';

typedef TtsCompletionCallback = void Function();
typedef TtsErrorCallback = void Function(String error);

class TtsEngineManager {
  static final TtsEngineManager _instance = TtsEngineManager._internal();
  factory TtsEngineManager() => _instance;
  TtsEngineManager._internal();

  final FlutterTts _flutterTts = FlutterTts();

  TtsCompletionCallback? onComplete;
  TtsErrorCallback? onError;

  bool _isInitialized = false;

  Future<void> init({String language = 'zh-CN', double speechRate = 0.5}) async {
    if (_isInitialized) return;
    await _flutterTts.setLanguage(language);
    await _flutterTts.setSpeechRate(speechRate);
    _flutterTts.setCompletionHandler(() {
      if (onComplete != null) onComplete!();
    });
    _flutterTts.setErrorHandler((msg) {
      if (onError != null) onError!(msg);
    });
    _isInitialized = true;
  }

  Future<void> speak(String text, {String? language, double? speechRate}) async {
    if (!_isInitialized) {
      await init(language: language ?? 'zh-CN', speechRate: speechRate ?? 0.5);
    }
    if (language != null) await _flutterTts.setLanguage(language);
    if (speechRate != null) await _flutterTts.setSpeechRate(speechRate);
    await _flutterTts.speak(text);
  }

  Future<void> stop() async {
    await _flutterTts.stop();
  }

  Future<void> setLanguage(String language) async {
    await _flutterTts.setLanguage(language);
  }

  Future<void> setSpeechRate(double rate) async {
    await _flutterTts.setSpeechRate(rate);
  }

  void dispose() {
    _flutterTts.stop();
    _isInitialized = false;
  }
}