import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:http_parser/http_parser.dart';

class VoiceRecognitionService {
  Future<String?> recognizeSpeech(List<int> audioBytes,
      {String lang = 'cn'}) async {
    try {
      print('准备发送OPUS音频数据，大小: ${audioBytes.length} 字节');
      final uri = Uri.parse('http://143.64.185.20:18606/voice');
      print('发送到: $uri');

      final request = http.MultipartRequest('POST', uri);
      request.files.add(
        http.MultipartFile.fromBytes(
          'audio',
          audioBytes,
          filename: 'record.wav',
          contentType: MediaType('audio', 'wav'),
        ),
      );
      request.fields['lang'] = lang; // 根据参数设置语言

      print('发送请求...');
      final streamResponse = await request.send();
      print('收到响应，状态码: ${streamResponse.statusCode}');

      final response = await http.Response.fromStream(streamResponse);

      if (response.statusCode == 200) {
        print('响应内容: ${response.body}');
        final text = _parseTextFromJson(response.body);
        if (text != null) {
          print('解析出文本: $text');
          return text; // 返回识别的文本
        } else {
          print('解析文本失败');
        }
      } else {
        print('请求失败，状态码: ${response.statusCode}，响应: ${response.body}');
      }
    } catch (e) {
      print('发送录音到服务器时出错: $e');
    }
    return null;
  }

  // 移到类内部作为私有方法
  String? _parseTextFromJson(String body) {
    try {
      final decoded = jsonDecode(body);
      if (decoded.containsKey('text')) {
        return decoded['text'] as String?;
      }
      return null;
    } catch (e) {
      print('JSON解析错误: $e, 原始数据: $body');
      return null;
    }
  }
}
