import 'dart:io';

import 'package:dio/dio.dart';

import '../network/dio_client.dart';
import '../utils/logger.dart';

class VoiceAssistantService {
  final Dio _dio = DioClient().client;

  Future<Map<String, dynamic>> processVoiceCommand(File audioFile) async {
    final fileName = audioFile.uri.pathSegments.isNotEmpty
        ? audioFile.uri.pathSegments.last
        : 'voice_command.wav';
    final mimeType = _mimeTypeForFileName(fileName);
    final fileSize = await audioFile.length();

    AppLogger.print(
      'Voice upload file=$fileName, bytes=$fileSize, mime=$mimeType, path=${audioFile.path}',
    );

    final formData = FormData.fromMap({
      'audio': await MultipartFile.fromFile(
        audioFile.path,
        filename: fileName,
        contentType: DioMediaType.parse(mimeType),
      ),
    });

    final response = await _dio.post(
      'voice/transcribe',
      data: formData,
      options: Options(contentType: 'multipart/form-data'),
    );

    if (response.data is! Map) {
      throw Exception('استجابة غير متوقعة من الخادم');
    }

    final body = Map<String, dynamic>.from(response.data as Map);
    if (body['success'] != true) {
      throw Exception((body['message'] ?? 'فشل تنفيذ الأمر الصوتي').toString());
    }

    final payload = body['data'];
    if (payload is! Map) {
      throw Exception('بيانات المساعد الصوتي ناقصة');
    }

    AppLogger.print('Voice API success: ${body['message']}');
    return Map<String, dynamic>.from(payload);
  }

  String _mimeTypeForFileName(String fileName) {
    final lower = fileName.toLowerCase();
    if (lower.endsWith('.wav')) return 'audio/wav';
    if (lower.endsWith('.flac')) return 'audio/flac';
    if (lower.endsWith('.mp3')) return 'audio/mp3';
    if (lower.endsWith('.aac')) return 'audio/aac';
    if (lower.endsWith('.ogg')) return 'audio/ogg';
    return 'audio/wav';
  }
}
