import 'dart:io';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:http/http.dart' as http;
import 'models/update_config.dart';
import 'models/version_info.dart';

/// 版本检查器
/// 负责与服务器通信检查是否有新版本
class VersionChecker {
  final UpdateConfig config;
  PackageInfo? _packageInfo;

  VersionChecker({required this.config});

  /// 获取当前应用版本信息
  Future<PackageInfo> getPackageInfo() async {
    _packageInfo ??= await PackageInfo.fromPlatform();
    return _packageInfo!;
  }

  /// 获取当前版本代码
  Future<int> getCurrentVersionCode() async {
    final info = await getPackageInfo();
    return int.tryParse(info.buildNumber) ?? 0;
  }

  /// 获取当前版本名称
  Future<String> getCurrentVersionName() async {
    final info = await getPackageInfo();
    return info.version;
  }

  /// 检查是否有新版本
  Future<UpdateCheckResult> checkForUpdate() async {
    try {
      final currentVersionCode = await getCurrentVersionCode();
      final platform = Platform.isAndroid ? 'ANDROID' : 'IOS';

      debugPrint('Checking for update: platform=$platform, currentVersion=$currentVersionCode');

      final uri = Uri.parse(config.checkUpdateUrl).replace(
        queryParameters: {
          'platform': platform,
          'versionCode': currentVersionCode.toString(),
        },
      );

      final response = await http.get(
        uri,
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      ).timeout(const Duration(seconds: 30));

      debugPrint('Update check response: ${response.statusCode}');

      if (response.statusCode == 200) {
        final json = jsonDecode(response.body);

        // 检查 API 响应格式
        if (json['hasUpdate'] == true && json['latestVersion'] != null) {
          final versionInfo = VersionInfo.fromJson(json['latestVersion']);
          debugPrint('New version available: ${versionInfo.versionName}');
          return UpdateCheckResult.hasUpdate(versionInfo);
        }

        debugPrint('No update available');
        return UpdateCheckResult.noUpdate();
      } else if (response.statusCode == 404) {
        // 未找到更新信息，视为无更新
        debugPrint('No version info found (404)');
        return UpdateCheckResult.noUpdate();
      } else {
        final errorMsg = 'Server error: ${response.statusCode}';
        debugPrint(errorMsg);
        return UpdateCheckResult.error(errorMsg);
      }
    } catch (e) {
      debugPrint('Update check failed: $e');
      return UpdateCheckResult.error('检查更新失败: $e');
    }
  }

  /// 比较版本号
  static int compareVersions(String v1, String v2) {
    final parts1 = v1.split('.').map((e) => int.tryParse(e) ?? 0).toList();
    final parts2 = v2.split('.').map((e) => int.tryParse(e) ?? 0).toList();

    final maxLength = parts1.length > parts2.length ? parts1.length : parts2.length;

    for (var i = 0; i < maxLength; i++) {
      final p1 = i < parts1.length ? parts1[i] : 0;
      final p2 = i < parts2.length ? parts2[i] : 0;

      if (p1 < p2) return -1;
      if (p1 > p2) return 1;
    }

    return 0;
  }
}
