import 'package:speech_to_text/speech_to_text.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class SttService {
  final SpeechToText _speech = SpeechToText();
  bool _isAvailable = false;

  Future<bool> initialize() async {
    _isAvailable = await _speech.initialize(
      onError: (val) => print("STT Error: $val"),
      onStatus: (val) => print("STT Status: $val"),
    );
    return _isAvailable;
  }

  Future<void> startListening({
    required Function(String) onResult,
    required Function(String) onStatus,
    Duration listenFor = const Duration(seconds: 30),
    Duration pauseFor = const Duration(seconds: 5),
  }) async {
    if (!_isAvailable) {
      bool available = await initialize();
      if (!available) {
        onStatus("error_unavailable");
        return;
      }
    }

    await _speech.listen(
      onResult: (result) {
        onResult(result.recognizedWords);
        if (result.finalResult) {
          // Do nothing special, controller handles stop
        }
      },
      listenFor: listenFor,
      pauseFor: pauseFor,
      partialResults: true,
      cancelOnError: true,
      listenMode: ListenMode.dictation,
    );
  }

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

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

final sttServiceProvider = Provider<SttService>((ref) => SttService());
