import 'package:speech_to_text/speech_to_text.dart';
import 'package:flutter/foundation.dart';

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

  final SpeechToText _speech = SpeechToText();
  bool _isInitialized = false;
  bool _isListening = false;

  bool get isListening => _isListening;

  // 回调
  Function(String text)? _onResult;
  Function(String text)? _onFinalResult;

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

    try {
      _isInitialized = await _speech.initialize(
        onError: (error) {
          debugPrint('⚠️ STT Error: ${error.errorMsg}');
          
          // error_no_match 是常见的"没听到有效语音"错误
          // 不应该中断整个流程
          if (error.errorMsg == 'error_no_match') {
            debugPrint('   (没有匹配到语音，忽略)');
          }
        },
        onStatus: (status) {
          debugPrint('🎤 STT Status: $status');
          if (status == 'listening') {
            _isListening = true;
          } else if (status == 'notListening' || status == 'done') {
            _isListening = false;
          }
        },
      );
      debugPrint('✅ STT Initialized: $_isInitialized');
      return _isInitialized;
    } catch (e) {
      debugPrint('❌ STT Init failed: $e');
      return false;
    }
  }

  Future<void> listen({
    required Function(String text) onResult,
    required Function(String text) onFinalResult,
    String localeId = 'zh-CN',
  }) async {
    if (!_isInitialized) {
      bool success = await init();
      if (!success) return;
    }

    if (_isListening) await stop();

    _onResult = onResult;
    _onFinalResult = onFinalResult;

    await _speech.listen(
      onResult: (result) {
        if (result.recognizedWords.isNotEmpty) {
          if (result.finalResult) {
            debugPrint('🎤 Final: "${result.recognizedWords}"');
            _onFinalResult?.call(result.recognizedWords);
          } else {
            _onResult?.call(result.recognizedWords);
          }
        }
      },
      localeId: localeId,
      listenFor: const Duration(seconds: 60),  // 最大监听时长
      pauseFor: const Duration(milliseconds: 1500),  // 1.5秒静音后视为说完
      listenOptions: SpeechListenOptions(
        partialResults: true,
        cancelOnError: false,  // 不要因错误取消
        listenMode: ListenMode.dictation,
      ),
    );
  }

  Future<void> stop() async {
    await _speech.stop();
    _isListening = false;
  }

  Future<void> cancel() async {
    await _speech.cancel();
    _isListening = false;
  }
}
