import '../models/writing_task.dart';
import '../models/writing_submission.dart';
import '../models/writing_stats.dart';
import '../../../core/network/api_client.dart';
import '../../../core/network/api_endpoints.dart';
import '../../../core/services/enhanced_api_service.dart';
import '../../../core/models/api_response.dart';
import '../models/writing_task.dart';
import '../models/writing_submission.dart';
import '../models/writing_stats.dart';

/// 写作训练服务
class WritingService {
  final EnhancedApiService _enhancedApiService = EnhancedApiService();
  
  // 缓存时长配置
  static const Duration _shortCacheDuration = Duration(minutes: 5);
  static const Duration _longCacheDuration = Duration(hours: 1);

  /// 获取写作任务列表
  Future<List<WritingTask>> getWritingTasks({
    WritingType? type,
    WritingDifficulty? difficulty,
    int page = 1,
    int limit = 20,
    bool forceRefresh = false,
  }) async {
    try {
      final response = await _enhancedApiService.get<List<WritingTask>>(
        ApiEndpoints.writingPrompts,
        queryParameters: {
          'page': page,
          'limit': limit,
          if (type != null) 'type': type.name,
          if (difficulty != null) 'difficulty': difficulty.name,
        },
        useCache: !forceRefresh,
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final List<dynamic> list = data['data'] ?? [];
          return list.map((json) => WritingTask.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('获取写作任务失败: $e');
    }
  }

  /// 获取单个写作任务详情
  Future<WritingTask> getWritingTask(String taskId) async {
    try {
      final response = await _enhancedApiService.get<WritingTask>(
        '${ApiEndpoints.writingPrompts}/$taskId',
        cacheDuration: _longCacheDuration,
        fromJson: (data) => WritingTask.fromJson(data['data']),
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('获取写作任务详情失败: $e');
    }
  }

  /// 提交写作作业
  Future<WritingSubmission> submitWriting({
    required String taskId,
    required String userId,
    required String content,
    required int timeSpent,
    required int wordCount,
  }) async {
    try {
      final response = await _enhancedApiService.post<WritingSubmission>(
        ApiEndpoints.writingSubmissions,
        data: {
          'prompt_id': taskId,
          'user_id': userId,
          'content': content,
          'time_spent': timeSpent,
          'word_count': wordCount,
        },
        fromJson: (data) => WritingSubmission.fromJson(data['data']),
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('提交写作作业失败: $e');
    }
  }

  /// 获取用户写作历史
  Future<List<WritingSubmission>> getUserWritingHistory({
    required String userId,
    int page = 1,
    int limit = 20,
    bool forceRefresh = false,
  }) async {
    try {
      final response = await _enhancedApiService.get<List<WritingSubmission>>(
        ApiEndpoints.writingSubmissions,
        queryParameters: {
          'page': page,
          'limit': limit,
        },
        useCache: !forceRefresh,
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final List<dynamic> list = data['data'] ?? [];
          return list.map((json) => WritingSubmission.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('获取写作历史失败: $e');
    }
  }

  /// 获取用户写作统计
  Future<WritingStats> getUserWritingStats(String userId, {bool forceRefresh = false}) async {
    try {
      final response = await _enhancedApiService.get<WritingStats>(
        ApiEndpoints.writingStats,
        useCache: !forceRefresh,
        cacheDuration: _shortCacheDuration,
        fromJson: (data) => WritingStats.fromJson(data['data']),
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('获取写作统计失败: $e');
    }
  }

  /// 获取写作反馈
  Future<WritingSubmission> getWritingFeedback(String submissionId) async {
    try {
      final response = await _enhancedApiService.get<WritingSubmission>(
        '${ApiEndpoints.writingSubmissions}/$submissionId',
        cacheDuration: _shortCacheDuration,
        fromJson: (data) => WritingSubmission.fromJson(data['data']),
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('获取写作反馈失败: $e');
    }
  }

  /// 搜索写作任务
  Future<List<WritingTask>> searchWritingTasks({
    required String query,
    WritingType? type,
    WritingDifficulty? difficulty,
    int page = 1,
    int limit = 20,
    bool forceRefresh = false,
  }) async {
    try {
      final response = await _enhancedApiService.get<List<WritingTask>>(
        '${ApiEndpoints.writingPrompts}/search',
        queryParameters: {
          'q': query,
          'page': page,
          'limit': limit,
          if (type != null) 'type': type.name,
          if (difficulty != null) 'difficulty': difficulty.name,
        },
        useCache: !forceRefresh,
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final List<dynamic> list = data['data'] ?? [];
          return list.map((json) => WritingTask.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('搜索写作任务失败: $e');
    }
  }

  /// 获取推荐的写作任务
  Future<List<WritingTask>> getRecommendedWritingTasks({
    required String userId,
    int limit = 10,
    bool forceRefresh = false,
  }) async {
    try {
      final response = await _enhancedApiService.get<List<WritingTask>>(
        '${ApiEndpoints.writingPrompts}/recommendations',
        queryParameters: {
          'limit': limit,
        },
        useCache: !forceRefresh,
        cacheDuration: _shortCacheDuration,
        fromJson: (data) {
          final List<dynamic> list = data['data'] ?? [];
          return list.map((json) => WritingTask.fromJson(json)).toList();
        },
      );
      
      if (response.success && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      throw Exception('获取推荐写作任务失败: $e');
    }
  }
}