import 'dart:io';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'models/update_config.dart';
import 'models/version_info.dart';
import 'version_checker.dart';
import 'download_manager.dart';
import 'apk_installer.dart';
import 'app_market_detector.dart';

/// 应用更新服务 - UpdateService
///
/// 功能概述:
/// 统一管理应用的版本检查、APK下载、安装更新流程。
/// 支持自托管更新服务器，与 mining-admin-service 后端配合使用。
///
/// 主要功能:
/// 1. 版本检查 - 通过 VersionChecker 与服务器通信获取最新版本信息
/// 2. APK下载 - 支持断点续传、SHA256校验
/// 3. APK安装 - 通过原生 MethodChannel 调用系统安装器
/// 4. 应用市场检测 - 判断是否从应用市场安装，支持引导跳转
///
/// 使用方式:
/// ```dart
/// // 初始化
/// UpdateService.instance.initialize(config: UpdateConfig.mining);
///
/// // 检查更新
/// final result = await UpdateService.instance.checkForUpdate();
/// if (result.hasUpdate) {
///   // 显示更新弹窗
/// }
/// ```
///
/// 后端API:
/// - GET /api/v2/versions/latest?platform=ANDROID - 获取最新版本
/// - GET /api/v2/versions/:id/download - 下载APK文件
class UpdateService {
  static UpdateService? _instance;
  static UpdateService get instance => _instance ??= UpdateService._();

  UpdateService._();

  static const String _lastCheckKey = 'update_last_check_time';

  UpdateConfig _config = UpdateConfig.mining;
  VersionChecker? _versionChecker;
  DownloadManager? _downloadManager;

  final _updateAvailableController = StreamController<VersionInfo?>.broadcast();
  Stream<VersionInfo?> get updateAvailableStream => _updateAvailableController.stream;

  /// 持久化的下载进度流（跨 DownloadManager 实例保持订阅有效）
  final _downloadProgressController = StreamController<DownloadProgress>.broadcast();
  StreamSubscription? _downloadProgressSubscription;

  VersionInfo? _latestVersion;
  VersionInfo? get latestVersion => _latestVersion;

  bool _isChecking = false;
  bool get isChecking => _isChecking;

  /// 初始化更新服务
  void initialize({UpdateConfig? config}) {
    _config = config ?? UpdateConfig.mining;
    _versionChecker = VersionChecker(config: _config);
    debugPrint('UpdateService initialized with config: ${_config.checkUpdateUrl}');
  }

  /// 检查更新
  Future<UpdateCheckResult> checkForUpdate({bool force = false}) async {
    if (_isChecking) {
      return UpdateCheckResult.error('Already checking');
    }

    if (_versionChecker == null) {
      initialize();
    }

    // 检查是否需要检查更新
    if (!force && !await _shouldCheck()) {
      if (_latestVersion != null) {
        return UpdateCheckResult.hasUpdate(_latestVersion!);
      }
      return UpdateCheckResult.noUpdate();
    }

    _isChecking = true;

    try {
      final result = await _versionChecker!.checkForUpdate();

      if (result.hasUpdate && result.versionInfo != null) {
        _latestVersion = result.versionInfo;
        _updateAvailableController.add(_latestVersion);
      } else {
        _latestVersion = null;
        _updateAvailableController.add(null);
      }

      // 保存检查时间
      await _saveLastCheckTime();

      return result;
    } finally {
      _isChecking = false;
    }
  }

  /// 是否应该检查更新
  Future<bool> _shouldCheck() async {
    if (!_config.autoCheck) {
      return false;
    }

    final prefs = await SharedPreferences.getInstance();
    final lastCheck = prefs.getInt(_lastCheckKey) ?? 0;
    final now = DateTime.now().millisecondsSinceEpoch;
    final interval = _config.checkIntervalMinutes * 60 * 1000;

    return (now - lastCheck) >= interval;
  }

  /// 保存最后检查时间
  Future<void> _saveLastCheckTime() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_lastCheckKey, DateTime.now().millisecondsSinceEpoch);
  }

  /// 下载更新
  Future<File?> downloadUpdate(VersionInfo versionInfo) async {
    // 取消旧的进度转发订阅
    await _downloadProgressSubscription?.cancel();
    _downloadManager?.dispose();
    _downloadManager = DownloadManager(versionInfo: versionInfo);
    // 将新 DownloadManager 的进度转发到持久化广播流
    _downloadProgressSubscription = _downloadManager!.progressStream.listen(
      (progress) => _downloadProgressController.add(progress),
    );
    return await _downloadManager!.startDownload();
  }

  /// 获取下载进度流（持久化广播流，订阅后可跨下载任务接收进度）
  Stream<DownloadProgress> get downloadProgressStream =>
      _downloadProgressController.stream;

  /// 取消下载
  void cancelDownload() {
    _downloadManager?.cancelDownload();
  }

  /// 安装更新
  Future<bool> installUpdate(File apkFile) async {
    return await ApkInstaller.installApk(apkFile);
  }

  /// 检查是否来自应用市场
  Future<bool> isFromAppMarket() async {
    return await AppMarketDetector.isFromAppMarket();
  }

  /// 打开应用市场
  Future<bool> openAppMarket() async {
    return await AppMarketDetector.openAppMarketDetail(_config.packageName);
  }

  /// 获取安装来源名称
  Future<String> getInstallerName() async {
    return await AppMarketDetector.getInstallerName();
  }

  /// 清除缓存的更新文件
  Future<void> clearCache() async {
    await _downloadManager?.cleanup();
  }

  void dispose() {
    _downloadProgressSubscription?.cancel();
    _downloadManager?.dispose();
    _downloadProgressController.close();
    _updateAvailableController.close();
  }
}
