import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';

/// 应用市场检测器
/// 检测应用安装来源，决定升级策略
class AppMarketDetector {
  static const MethodChannel _channel =
      MethodChannel('com.durianqueen.mining/app_market');

  /// 常见应用市场包名
  static const List<String> _marketPackages = [
    'com.android.vending', // Google Play
    'com.huawei.appmarket', // 华为应用市场
    'com.xiaomi.market', // 小米应用商店
    'com.oppo.market', // OPPO 软件商店
    'com.bbk.appstore', // vivo 应用商店
    'com.tencent.android.qqdownloader', // 应用宝
    'com.qihoo.appstore', // 360 手机助手
    'com.baidu.appsearch', // 百度手机助手
    'com.wandoujia.phoenix2', // 豌豆荚
    'com.dragon.android.pandaspace', // 91 助手
    'com.sec.android.app.samsungapps', // 三星应用商店
  ];

  /// 获取安装来源
  static Future<String?> getInstallerPackageName() async {
    if (!Platform.isAndroid) return null;

    try {
      final installer =
          await _channel.invokeMethod<String>('getInstallerPackageName');
      return installer;
    } on PlatformException catch (e) {
      debugPrint('Get installer failed (PlatformException): ${e.message}');
      return null;
    } catch (e) {
      debugPrint('Get installer failed: $e');
      return null;
    }
  }

  /// 判断是否来自应用市场
  static Future<bool> isFromAppMarket() async {
    final installer = await getInstallerPackageName();

    if (installer == null || installer.isEmpty) {
      return false; // 直接安装（如 adb install）
    }

    return _marketPackages.contains(installer);
  }

  /// 判断是否来自 Google Play
  static Future<bool> isFromGooglePlay() async {
    final installer = await getInstallerPackageName();
    return installer == 'com.android.vending';
  }

  /// 判断是否来自国内应用市场
  static Future<bool> isFromChineseMarket() async {
    final installer = await getInstallerPackageName();

    if (installer == null || installer.isEmpty) {
      return false;
    }

    // 排除 Google Play
    if (installer == 'com.android.vending') {
      return false;
    }

    return _marketPackages.contains(installer);
  }

  /// 获取安装来源名称（用于显示）
  static Future<String> getInstallerName() async {
    final installer = await getInstallerPackageName();

    if (installer == null || installer.isEmpty) {
      return '直接安装';
    }

    switch (installer) {
      case 'com.android.vending':
        return 'Google Play';
      case 'com.huawei.appmarket':
        return '华为应用市场';
      case 'com.xiaomi.market':
        return '小米应用商店';
      case 'com.oppo.market':
        return 'OPPO 软件商店';
      case 'com.bbk.appstore':
        return 'vivo 应用商店';
      case 'com.tencent.android.qqdownloader':
        return '应用宝';
      case 'com.qihoo.appstore':
        return '360 手机助手';
      case 'com.baidu.appsearch':
        return '百度手机助手';
      case 'com.wandoujia.phoenix2':
        return '豌豆荚';
      case 'com.sec.android.app.samsungapps':
        return '三星应用商店';
      default:
        return installer;
    }
  }

  /// 打开应用市场详情页
  static Future<bool> openAppMarketDetail(String packageName) async {
    final marketUri = Uri.parse('market://details?id=$packageName');

    if (await canLaunchUrl(marketUri)) {
      await launchUrl(marketUri, mode: LaunchMode.externalApplication);
      return true;
    } else {
      // 回退到 Google Play 网页版
      final webUri =
          Uri.parse('https://play.google.com/store/apps/details?id=$packageName');
      if (await canLaunchUrl(webUri)) {
        await launchUrl(webUri, mode: LaunchMode.externalApplication);
        return true;
      }
      return false;
    }
  }

  /// 打开 Google Play 详情页
  static Future<bool> openGooglePlay(String packageName) async {
    final uri = Uri.parse(
        'https://play.google.com/store/apps/details?id=$packageName');

    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
      return true;
    }
    return false;
  }
}
