import 'package:ai_english_learning/core/network/api_client.dart';
import 'package:ai_english_learning/features/vocabulary/models/learning_session_model.dart';
import 'package:ai_english_learning/features/vocabulary/models/word_model.dart';

class LearningService {
  final ApiClient _apiClient;

  LearningService({required ApiClient apiClient}) : _apiClient = apiClient;

  /// 开始学习会话
  Future<Map<String, dynamic>> startLearning(String bookId, int dailyGoal) async {
    try {
      final response = await _apiClient.post(
        '/vocabulary/books/$bookId/learn',
        data: {
          'dailyGoal': dailyGoal,
        },
      );
      
      final data = response.data['data'];
      return {
        'session': LearningSession.fromJson(data['session']),
        'tasks': DailyLearningTasks.fromJson(data['tasks']),
      };
    } catch (e) {
      print('开始学习失败: $e');
      rethrow;
    }
  }

  /// 获取今日学习任务
  Future<DailyLearningTasks> getTodayTasks(String bookId, {
    int newWords = 20,
    int review = 50,
  }) async {
    try {
      final response = await _apiClient.get(
        '/vocabulary/books/$bookId/tasks',
        queryParameters: {
          'newWords': newWords,
          'review': review,
        },
      );
      
      return DailyLearningTasks.fromJson(response.data['data']);
    } catch (e) {
      print('获取学习任务失败: $e');
      rethrow;
    }
  }

  /// 提交单词学习结果
  Future<UserWordProgress> submitWordStudy(
    String wordId,
    StudyDifficulty difficulty, {
    int? sessionId,
  }) async {
    try {
      final response = await _apiClient.post(
        '/vocabulary/words/$wordId/study',
        data: {
          'difficulty': difficulty.name,
          if (sessionId != null) 'sessionId': sessionId,
        },
      );
      
      return UserWordProgress.fromJson(response.data['data']);
    } catch (e) {
      print('提交学习结果失败: $e');
      rethrow;
    }
  }

  /// 获取学习统计
  Future<LearningStatistics> getLearningStatistics(String bookId) async {
    try {
      final response = await _apiClient.get(
        '/vocabulary/books/$bookId/statistics',
      );
      
      return LearningStatistics.fromJson(response.data['data']);
    } catch (e) {
      print('获取学习统计失败: $e');
      rethrow;
    }
  }
}
