import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import '../services/storage_service.dart';
import 'api_endpoints.dart';
import '../config/environment.dart';

/// AI相关API服务
class AIApiService {
  static String get _baseUrl => EnvironmentConfig.baseUrl;

  /// 获取认证头部
  Map<String, String> _getAuthHeaders() {
    final storageService = StorageService.instance;
    final token = storageService.getString(StorageKeys.accessToken);
    return {
      'Content-Type': 'application/json',
      if (token != null) 'Authorization': 'Bearer $token',
    };
  }

  /// 写作批改
  Future<Map<String, dynamic>> correctWriting({
    required String content,
    required String taskType,
  }) async {
    try {
      final headers = _getAuthHeaders();
      final response = await http.post(
        Uri.parse('$_baseUrl/api/v1/ai/writing/correct'),
        headers: headers,
        body: json.encode({
          'content': content,
          'task_type': taskType,
        }),
      );

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to correct writing: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error correcting writing: $e');
    }
  }

  /// 口语评估
  Future<Map<String, dynamic>> evaluateSpeaking({
    required String audioText,
    required String prompt,
  }) async {
    try {
      final headers = _getAuthHeaders();
      final response = await http.post(
        Uri.parse('$_baseUrl/api/v1/ai/speaking/evaluate'),
        headers: headers,
        body: json.encode({
          'audio_text': audioText,
          'prompt': prompt,
        }),
      );

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to evaluate speaking: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error evaluating speaking: $e');
    }
  }

  /// 获取AI使用统计
  Future<Map<String, dynamic>> getAIUsageStats() async {
    try {
      final headers = _getAuthHeaders();
      final response = await http.get(
        Uri.parse('$_baseUrl/api/v1/ai/stats'),
        headers: headers,
      );

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to get AI stats: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error getting AI stats: $e');
    }
  }

  /// 上传音频文件
  Future<Map<String, dynamic>> uploadAudio(File audioFile) async {
    try {
      final storageService = StorageService.instance;
      final token = storageService.getString(StorageKeys.accessToken);
      final request = http.MultipartRequest(
        'POST',
        Uri.parse('$_baseUrl/api/v1/upload/audio'),
      );
      
      if (token != null) {
        request.headers['Authorization'] = 'Bearer $token';
      }
      request.files.add(
        await http.MultipartFile.fromPath('audio', audioFile.path),
      );

      final streamedResponse = await request.send();
      final response = await http.Response.fromStream(streamedResponse);

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to upload audio: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error uploading audio: $e');
    }
  }

  /// 上传图片文件
  Future<Map<String, dynamic>> uploadImage(File imageFile) async {
    try {
      final storageService = StorageService.instance;
      final token = storageService.getString(StorageKeys.accessToken);
      final request = http.MultipartRequest(
        'POST',
        Uri.parse('$_baseUrl/api/v1/upload/image'),
      );
      
      if (token != null) {
        request.headers['Authorization'] = 'Bearer $token';
      }
      request.files.add(
        await http.MultipartFile.fromPath('image', imageFile.path),
      );

      final streamedResponse = await request.send();
      final response = await http.Response.fromStream(streamedResponse);

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to upload image: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error uploading image: $e');
    }
  }

  /// 删除文件
  Future<Map<String, dynamic>> deleteFile(String fileId) async {
    try {
      final headers = _getAuthHeaders();
      final response = await http.delete(
        Uri.parse('$_baseUrl/api/v1/upload/file/$fileId'),
        headers: headers,
      );

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to delete file: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error deleting file: $e');
    }
  }

  /// 获取文件信息
  Future<Map<String, dynamic>> getFileInfo(String fileId) async {
    try {
      final headers = _getAuthHeaders();
      final response = await http.get(
        Uri.parse('$_baseUrl/api/v1/upload/file/$fileId'),
        headers: headers,
      );

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to get file info: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error getting file info: $e');
    }
  }

  /// 获取上传统计
  Future<Map<String, dynamic>> getUploadStats({int days = 30}) async {
    try {
      final headers = _getAuthHeaders();
      final response = await http.get(
        Uri.parse('$_baseUrl/api/v1/upload/stats?days=$days'),
        headers: headers,
      );

      if (response.statusCode == 200) {
        return json.decode(response.body);
      } else {
        throw Exception('Failed to get upload stats: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Error getting upload stats: $e');
    }
  }
}