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('cn.gogenex.issuer/app_market');

  static const List<String> _marketPackages = [
    'com.android.vending',
    'com.huawei.appmarket',
    'com.xiaomi.market',
    'com.oppo.market',
    'com.bbk.appstore',
    'com.tencent.android.qqdownloader',
    'com.qihoo.appstore',
    'com.baidu.appsearch',
    'com.wandoujia.phoenix2',
    'com.dragon.android.pandaspace',
    'com.sec.android.app.samsungapps',
  ];

  static Future<String?> getInstallerPackageName() async {
    if (!Platform.isAndroid) return null;
    try {
      return await _channel.invokeMethod<String>('getInstallerPackageName');
    } 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;
    return _marketPackages.contains(installer);
  }

  static Future<bool> isFromGooglePlay() async {
    final installer = await getInstallerPackageName();
    return installer == 'com.android.vending';
  }

  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 '应用宝';
      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 {
      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;
    }
  }
}
