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;

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

    try {
      _isInitialized = await _speech.initialize(
        onError: (error) => debugPrint('❌ STT Error: $error'),
        onStatus: (status) {
          debugPrint('🎤 STT Status: $status');
          if (status == 'listening') _isListening = true;
          if (status == 'notListening') _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();

    await _speech.listen(
      onResult: (result) {
        if (result.finalResult) {
          onFinalResult(result.recognizedWords);
        } else {
          onResult(result.recognizedWords);
        }
      },
      localeId: localeId,
      listenFor: const Duration(seconds: 30),
      pauseFor: const Duration(seconds: 3), // Wait 3s of silence to consider "done"
      partialResults: true,
      cancelOnError: true,
      listenMode: ListenMode.dictation,
    );
  }

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

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