import 'package:flutter/foundation.dart';
import 'package:flutter_tts/flutter_tts.dart';
import '../../models/character_model.dart';
import 'tts_engine.dart';

class SystemTtsEngine implements TtsEngine {
  final FlutterTts _flutterTts = FlutterTts();
  bool _isInitialized = false;

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

    try {
      if (!kIsWeb) {
        if (defaultTargetPlatform == TargetPlatform.iOS) {
          await _flutterTts.setSharedInstance(true);
          await _flutterTts.setIosAudioCategory(
            IosTextToSpeechAudioCategory.playAndRecord,
            [
              IosTextToSpeechAudioCategoryOptions.allowBluetooth,
              IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
              IosTextToSpeechAudioCategoryOptions.mixWithOthers,
              IosTextToSpeechAudioCategoryOptions.defaultToSpeaker,
            ],
            IosTextToSpeechAudioMode.defaultMode,
          );
        }
      }

      await _flutterTts.setLanguage("zh-CN");
      await _flutterTts.setPitch(1.0);
      await _flutterTts.setSpeechRate(0.5);

      _isInitialized = true;
      debugPrint('✅ SystemTtsEngine initialized');
    } catch (e) {
      debugPrint('❌ SystemTtsEngine init error: $e');
    }
  }

  @override
  Future<void> preconnect() async {
    // 系统 TTS 不需要预连接
  }

  @override
  Future<void> speak(
    String text, {
    AiVoiceConfig? voiceConfig,
  }) async {
    if (!_isInitialized) await init();
    if (text.trim().isEmpty) return;

    if (voiceConfig != null) {
      await _flutterTts.setSpeechRate(voiceConfig.speed.clamp(0.2, 2.0));
      await _flutterTts.setPitch(voiceConfig.pitch.clamp(0.5, 2.0));
    }

    debugPrint('🗣️ SystemTtsEngine Speaking: $text');
    await _flutterTts.speak(text);
  }

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

  @override
  void setCompletionHandler(VoidCallback handler) {
    _flutterTts.setCompletionHandler(handler);
  }

  @override
  void setStartHandler(VoidCallback handler) {
    _flutterTts.setStartHandler(handler);
  }

  @override
  void setErrorHandler(Function(dynamic) handler) {
    _flutterTts.setErrorHandler(handler);
  }

  @override
  void dispose() {
    _flutterTts.stop();
  }
}
