import 'package:package_info_plus/package_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'models/version_info.dart';

/// 版本检测器
/// 负责从服务器获取最新版本信息并与当前版本比较
class VersionChecker {
  final String apiBaseUrl;
  final Dio _dio;

  VersionChecker({required this.apiBaseUrl})
      : _dio = Dio(BaseOptions(
          baseUrl: apiBaseUrl,
          connectTimeout: const Duration(seconds: 10),
          receiveTimeout: const Duration(seconds: 10),
        ));

  /// 获取当前版本信息
  Future<PackageInfo> getCurrentVersion() async {
    return await PackageInfo.fromPlatform();
  }

  /// 从服务器获取最新版本信息
  Future<VersionInfo?> fetchLatestVersion() async {
    try {
      final currentInfo = await getCurrentVersion();
      debugPrint('[VersionChecker] 当前版本: ${currentInfo.version}, buildNumber: ${currentInfo.buildNumber}');
      debugPrint('[VersionChecker] API URL: $apiBaseUrl/api/app/version/check');

      final response = await _dio.get(
        '/api/app/version/check',
        queryParameters: {
          'platform': 'android',
          'current_version': currentInfo.version,
          'current_version_code': currentInfo.buildNumber,
        },
      );

      debugPrint('[VersionChecker] 响应状态: ${response.statusCode}');
      debugPrint('[VersionChecker] 响应数据: ${response.data}');

      if (response.statusCode == 200 && response.data != null) {
        // 检查是否需要更新
        final needUpdate = response.data['needUpdate'] as bool? ?? true;
        if (!needUpdate) {
          debugPrint('[VersionChecker] 服务器返回无需更新');
          return null;
        }
        debugPrint('[VersionChecker] 服务器返回需要更新');
        return VersionInfo.fromJson(response.data);
      }
      return null;
    } catch (e) {
      debugPrint('[VersionChecker] 获取版本失败: $e');
      return null;
    }
  }

  /// 检查是否有新版本
  Future<VersionInfo?> checkForUpdate() async {
    try {
      final currentInfo = await getCurrentVersion();
      final latestInfo = await fetchLatestVersion();

      if (latestInfo == null) return null;

      final currentCode = int.tryParse(currentInfo.buildNumber) ?? 0;
      if (latestInfo.versionCode > currentCode) {
        return latestInfo;
      }

      return null;
    } catch (e) {
      debugPrint('Check update failed: $e');
      return null;
    }
  }

  /// 是否需要强制更新
  Future<bool> needForceUpdate() async {
    final latestInfo = await checkForUpdate();
    return latestInfo?.forceUpdate ?? false;
  }

  /// 获取版本差异
  Future<int> getVersionDiff() async {
    try {
      final currentInfo = await getCurrentVersion();
      final latestInfo = await fetchLatestVersion();

      if (latestInfo == null) return 0;

      final currentCode = int.tryParse(currentInfo.buildNumber) ?? 0;
      return latestInfo.versionCode - currentCode;
    } catch (e) {
      debugPrint('Get version diff failed: $e');
      return 0;
    }
  }
}
