import 'package:flutter/foundation.dart';
import '../config/minimax_config.dart';
import '../models/character_model.dart';
import 'tts/minimax_tts_engine.dart';
import 'tts/system_tts_engine.dart';
import 'tts/tts_engine.dart';

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

  final TtsEngine _minimaxEngine = MiniMaxTtsEngine();
  final TtsEngine _systemEngine = SystemTtsEngine();
  TtsEngine? _activeEngine;

  bool _isInitialized = false;

  VoidCallback? _onStart;
  VoidCallback? _onComplete;
  Function(dynamic)? _onError;

  Future<void> init() async {
    if (_isInitialized) return;

    try {
      _activeEngine = _selectEngine();
      _applyHandlers(_activeEngine);
      await _activeEngine!.init();
      _isInitialized = true;
      debugPrint('✅ TTSService initialized (${_activeEngine.runtimeType})');
    } catch (e) {
      debugPrint('❌ TTSService init error: $e');
    }
  }

  Future<void> speak(String text, {AiVoiceConfig? voiceConfig}) async {
    if (!_isInitialized) await init();
    if (text.isEmpty) return;
    
    if (_activeEngine == null) {
      _activeEngine = _selectEngine();
      _applyHandlers(_activeEngine);
      await _activeEngine!.init();
    }

    debugPrint('🗣️ TTS Speaking: $text');
    if (_activeEngine is MiniMaxTtsEngine) {
      try {
        await _activeEngine!.speak(text, voiceConfig: voiceConfig);
        return;
      } catch (e) {
        debugPrint('⚠️ MiniMax TTS failed, falling back to system TTS: $e');
        await _fallbackSpeak(text, voiceConfig: voiceConfig);
        return;
      }
    }

    await _activeEngine!.speak(text, voiceConfig: voiceConfig);
  }

  /// 预连接 TTS 服务（在语音页面打开时调用）
  Future<void> preconnect() async {
    if (!_isInitialized) await init();
    await _activeEngine?.preconnect();
  }

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

  void setCompletionHandler(VoidCallback handler) {
    _onComplete = handler;
    _minimaxEngine.setCompletionHandler(handler);
    _systemEngine.setCompletionHandler(handler);
  }
  
  void setStartHandler(VoidCallback handler) {
    _onStart = handler;
    _minimaxEngine.setStartHandler(handler);
    _systemEngine.setStartHandler(handler);
  }

  void setErrorHandler(Function(dynamic) handler) {
    _onError = handler;
    _minimaxEngine.setErrorHandler(handler);
    _systemEngine.setErrorHandler(handler);
  }

  TtsEngine _selectEngine() {
    if (MinimaxConfig.isEnabled && !kIsWeb) {
      return _minimaxEngine;
    }
    return _systemEngine;
  }

  Future<void> _fallbackSpeak(String text, {AiVoiceConfig? voiceConfig}) async {
    try {
      _activeEngine = _systemEngine;
      _applyHandlers(_activeEngine);
      await _activeEngine!.init();
      await _activeEngine!.speak(text, voiceConfig: voiceConfig);
    } catch (e) {
      debugPrint('❌ System TTS failed: $e');
      if (_onError != null) _onError!(e);
    }
  }

  void _applyHandlers(TtsEngine? engine) {
    if (engine == null) return;
    if (_onStart != null) engine.setStartHandler(_onStart!);
    if (_onComplete != null) engine.setCompletionHandler(_onComplete!);
    if (_onError != null) engine.setErrorHandler(_onError!);
  }
}
