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}');

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

      if (response.statusCode == 200 && response.data != null) {
        // API wraps response: {"code":0,"data":{...}} — extract the inner object
        final responseMap = response.data as Map<String, dynamic>;
        final data = (responseMap['data'] as Map<String, dynamic>?) ?? responseMap;

        final needUpdate = data['needUpdate'] as bool? ?? false;
        if (!needUpdate) {
          debugPrint('[VersionChecker] 无需更新');
          return null;
        }

        // Fix relative downloadUrl → prepend apiBaseUrl for DownloadManager
        final rawUrl = data['downloadUrl'] as String? ?? '';
        final fixedData = (rawUrl.isNotEmpty && !rawUrl.startsWith('http'))
            ? (Map<String, dynamic>.from(data)..['downloadUrl'] = '$apiBaseUrl$rawUrl')
            : data;

        return VersionInfo.fromJson(fixedData);
      }
      return null;
    } catch (e) {
      debugPrint('[VersionChecker] 获取版本失败: $e');
      return null;
    }
  }

  /// 检查是否有新版本
  Future<VersionInfo?> checkForUpdate() async {
    try {
      final currentInfo = await getCurrentVersion();
      debugPrint('[VersionChecker] 当前 buildNumber=${currentInfo.buildNumber} 开始检查...');
      final latestInfo = await fetchLatestVersion();

      if (latestInfo == null) {
        debugPrint('[VersionChecker] 服务端返回无需更新');
        return null;
      }

      final currentCode = int.tryParse(currentInfo.buildNumber) ?? 0;
      debugPrint('[VersionChecker] 服务端最新 versionCode=${latestInfo.versionCode} 本地=$currentCode');
      if (latestInfo.versionCode > currentCode) {
        debugPrint('[VersionChecker] 发现新版本 ${latestInfo.version}，准备弹窗');
        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;
    }
  }
}
