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] apiBaseUrl: $apiBaseUrl');
      debugPrint('[VersionChecker] 当前版本: ${currentInfo.version}, buildNumber: ${currentInfo.buildNumber}, packageName: ${currentInfo.packageName}');

      final queryParams = {
        'platform': 'android',
        'current_version': currentInfo.version,
        'current_version_code': currentInfo.buildNumber,
      };
      debugPrint('[VersionChecker] 请求: GET $apiBaseUrl/api/app/version/check $queryParams');

      final response = await _dio.get(
        '/api/app/version/check',
        queryParameters: queryParams,
      );

      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] 服务器返回 needUpdate=false，无需更新');
          return null;
        }
        debugPrint('[VersionChecker] 服务器返回 needUpdate=true，最新版本: ${response.data['version']} (versionCode=${response.data['versionCode']})');
        return VersionInfo.fromJson(response.data);
      }
      debugPrint('[VersionChecker] 异常状态码: ${response.statusCode}');
      return null;
    } catch (e, stack) {
      debugPrint('[VersionChecker] 获取版本失败: $e');
      debugPrint('[VersionChecker] StackTrace: $stack');
      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;
      debugPrint('[VersionChecker] 版本比较: 服务器 versionCode=${latestInfo.versionCode} vs 本地 buildNumber=$currentCode');
      if (latestInfo.versionCode > currentCode) {
        debugPrint('[VersionChecker] 有新版本可更新');
        return latestInfo;
      }

      debugPrint('[VersionChecker] 本地版本不低于服务器版本，无需更新');
      return null;
    } catch (e, stack) {
      debugPrint('[VersionChecker] checkForUpdate 异常: $e');
      debugPrint('[VersionChecker] StackTrace: $stack');
      return null;
    }
  }
}
