import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:vad/vad.dart';

/// VAD (Voice Activity Detection) + Google Speech-to-Text 服务
/// 
/// 使用 Silero VAD 模型检测语音开始/结束
/// 然后将录制的音频发送给 Google Cloud Speech-to-Text API
class VadSttService {
  static final VadSttService _instance = VadSttService._internal();
  factory VadSttService() => _instance;
  VadSttService._internal();

  VadHandler? _vadHandler;
  bool _isInitialized = false;
  bool _isListening = false;

  // Google Cloud STT 配置
  // TODO: 替换为你的 API Key
  static const String _googleApiKey = 'AIzaSyD7Dg_Goc5Z9c5LzjTCnhCxLuwCVQz89bk';
  static const String _googleSttUrl = 'https://speech.googleapis.com/v1/speech:recognize';

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

  // 统计
  int _speechSegmentCount = 0;
  final Stopwatch _speechStopwatch = Stopwatch();

  bool get isListening => _isListening;

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

    try {
      _vadHandler = VadHandler.create(isDebug: true);
      
      // 设置事件监听
      _setupEventHandlers();
      
      _isInitialized = true;
      debugPrint('✅ VadSttService initialized (Silero VAD + Google STT)');
      return true;
    } catch (e) {
      debugPrint('❌ VadSttService init failed: $e');
      return false;
    }
  }

  void _setupEventHandlers() {
    if (_vadHandler == null) return;

    // 检测到开始说话（可能是误触发）
    _vadHandler!.onSpeechStart.listen((_) {
      debugPrint('🎤 [VAD] 检测到声音...');
      _speechStopwatch.reset();
      _speechStopwatch.start();
    });

    // 确认是真正说话（不是噪音误触发）
    _vadHandler!.onRealSpeechStart.listen((_) {
      _speechSegmentCount++;
      debugPrint('');
      debugPrint('═══════════════════════════════════════');
      debugPrint('🎤 [VAD] 语音段 #$_speechSegmentCount 开始');
      debugPrint('═══════════════════════════════════════');
      
      if (_onSpeechStart != null) _onSpeechStart!();
    });

    // 说话结束，获取音频数据
    _vadHandler!.onSpeechEnd.listen((List<double> samples) async {
      _speechStopwatch.stop();
      final durationMs = _speechStopwatch.elapsedMilliseconds;
      
      final sampleCount = samples.length;
      final estimatedBytes = sampleCount * 2; // 16-bit = 2 bytes per sample
      
      debugPrint('');
      debugPrint('═══════════════════════════════════════');
      debugPrint('🎤 [VAD] 语音段 #$_speechSegmentCount 结束');
      debugPrint('   时长: ${durationMs}ms');
      debugPrint('   采样点: $sampleCount');
      debugPrint('   数据大小: ~${(estimatedBytes / 1024).toStringAsFixed(1)} KB');
      debugPrint('═══════════════════════════════════════');
      
      if (_onSpeechEnd != null) _onSpeechEnd!();
      
      // 太短的语音忽略
      if (durationMs < 500) {
        debugPrint('⚠️ 语音太短，忽略');
        return;
      }
      
      // 发送给 Google STT
      await _transcribeWithGoogle(samples, durationMs);
    });

    // 误触发（检测到声音但不是有效语音）
    _vadHandler!.onVADMisfire.listen((_) {
      _speechStopwatch.stop();
      debugPrint('⚠️ [VAD] 误触发（不是有效语音），忽略');
    });

    // 错误
    _vadHandler!.onError.listen((String message) {
      debugPrint('❌ [VAD] 错误: $message');
    });
  }

  /// 将 double 采样点转换为 16-bit PCM 字节
  Uint8List _convertSamplesToBytes(List<double> samples) {
    final bytes = Uint8List(samples.length * 2);
    for (int i = 0; i < samples.length; i++) {
      // 将 -1.0 ~ 1.0 转换为 -32768 ~ 32767
      int sample = (samples[i] * 32767).clamp(-32768, 32767).toInt();
      // Little endian
      bytes[i * 2] = sample & 0xFF;
      bytes[i * 2 + 1] = (sample >> 8) & 0xFF;
    }
    return bytes;
  }

  /// 发送给 Google Speech-to-Text API
  Future<void> _transcribeWithGoogle(List<double> samples, int durationMs) async {
    if (_googleApiKey == 'YOUR_GOOGLE_API_KEY') {
      debugPrint('⚠️ [Google STT] 请先配置 API Key!');
      debugPrint('📝 [模拟结果] 语音时长 ${durationMs}ms, 采样点 ${samples.length}');
      
      // 模拟返回结果
      if (_onFinalResult != null) {
        _onFinalResult!('[模拟: ${durationMs}ms 语音]');
      }
      return;
    }
    
    debugPrint('📤 [Google STT] 发送音频数据...');
    
    try {
      // 转换为 PCM 字节
      final audioBytes = _convertSamplesToBytes(samples);
      final audioBase64 = base64Encode(audioBytes);
      
      debugPrint('   音频大小: ${(audioBytes.length / 1024).toStringAsFixed(1)} KB');
      
      // 构建请求
      final requestBody = {
        'config': {
          'encoding': 'LINEAR16',
          'sampleRateHertz': 16000, // VAD 默认采样率
          'languageCode': 'zh-CN', // 中文
          'enableAutomaticPunctuation': true,
          // 不指定 model，使用默认模型
        },
        'audio': {
          'content': audioBase64,
        },
      };
      
      final stopwatch = Stopwatch()..start();
      
      final response = await http.post(
        Uri.parse('$_googleSttUrl?key=$_googleApiKey'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(requestBody),
      );
      
      stopwatch.stop();
      debugPrint('   响应时间: ${stopwatch.elapsedMilliseconds}ms');
      
      if (response.statusCode == 200) {
        final result = jsonDecode(response.body);
        
        if (result['results'] != null && (result['results'] as List).isNotEmpty) {
          final transcript = result['results'][0]['alternatives'][0]['transcript'] as String;
          final confidence = result['results'][0]['alternatives'][0]['confidence'] ?? 0.0;
          
          debugPrint('');
          debugPrint('═══════════════════════════════════════');
          debugPrint('📝 [Google STT] 识别结果:');
          debugPrint('   "$transcript"');
          debugPrint('   置信度: ${(confidence * 100).toStringAsFixed(1)}%');
          debugPrint('═══════════════════════════════════════');
          
          if (_onFinalResult != null) {
            _onFinalResult!(transcript);
          }
        } else {
          debugPrint('⚠️ [Google STT] 没有识别到文字');
        }
      } else {
        debugPrint('❌ [Google STT] 请求失败: ${response.statusCode}');
        debugPrint('   ${response.body}');
      }
    } catch (e) {
      debugPrint('❌ [Google STT] 错误: $e');
    }
  }

  Future<void> startListening({
    Function(String text)? onResult,
    Function(String text)? onFinalResult,
    VoidCallback? onSpeechStart,
    VoidCallback? onSpeechEnd,
  }) async {
    if (!_isInitialized) {
      bool success = await init();
      if (!success) return;
    }

    if (_isListening) {
      debugPrint('⚠️ [VAD] 已经在监听中');
      return;
    }

    _onResult = onResult;
    _onFinalResult = onFinalResult;
    _onSpeechStart = onSpeechStart;
    _onSpeechEnd = onSpeechEnd;
    _speechSegmentCount = 0;

    debugPrint('');
    debugPrint('🎤 [VAD] 开始监听...');
    
    try {
      await _vadHandler?.startListening();
      _isListening = true;
      debugPrint('✅ [VAD] 监听已启动，等待语音输入...');
    } catch (e) {
      debugPrint('❌ [VAD] 启动监听失败: $e');
    }
  }

  Future<void> stopListening() async {
    if (!_isListening) return;
    
    debugPrint('🛑 [VAD] 停止监听');
    
    try {
      await _vadHandler?.stopListening();
      _isListening = false;
    } catch (e) {
      debugPrint('❌ [VAD] 停止监听失败: $e');
    }
  }

  void dispose() {
    _vadHandler?.dispose();
    _vadHandler = null;
    _isInitialized = false;
    _isListening = false;
    debugPrint('🗑️ VadSttService disposed');
  }
}
