import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:network_info_plus/network_info_plus.dart';

class NetworkHelper {
  static final NetworkHelper _instance = NetworkHelper._();
  static NetworkHelper get instance => _instance;

  final _connectivity = Connectivity();
  final _networkInfo = NetworkInfo();

  NetworkHelper._();

  // 检查网络是否可用
  Future<bool> isNetworkAvailable() async {
    try {
      final connectivityResult = await _connectivity.checkConnectivity();
      if (connectivityResult.contains(ConnectivityResult.none)) {
        return false;
      }

      // 如果是WiFi，进一步检查WiFi信息
      if (connectivityResult.contains(ConnectivityResult.wifi)) {
        final wifiName = await _networkInfo.getWifiName();
        final wifiIP = await _networkInfo.getWifiIP();

        // 如果无法获取WiFi名称和IP，可能表示网络异常
        if (wifiName == null && wifiIP == null) {
          return false;
        }
      }

      return true;
    } catch (e) {
      return false;
    }
  }

  // 获取当前网络类型
  Future<String> getNetworkType() async {
    try {
      final connectivityResult = await _connectivity.checkConnectivity();
      if (connectivityResult.contains(ConnectivityResult.mobile)) {
        return 'Mobile';
      } else if (connectivityResult.contains(ConnectivityResult.wifi)) {
        final wifiName = await _networkInfo.getWifiName();
        return 'WiFi${wifiName != null ? " ($wifiName)" : ""}';
      } else if (connectivityResult.contains(ConnectivityResult.ethernet)) {
        return 'Ethernet';
      } else if (connectivityResult.contains(ConnectivityResult.vpn)) {
        return 'VPN';
      } else if (connectivityResult.contains(ConnectivityResult.bluetooth)) {
        return 'Bluetooth';
      } else if (connectivityResult.contains(ConnectivityResult.other)) {
        return 'Other';
      } else if (connectivityResult.contains(ConnectivityResult.none)) {
        return 'No Network';
      } else {
        return 'Unknown';
      }
    } catch (e) {
      return 'Error';
    }
  }

  static final List<String> _commonVpnInterfaceNamePatterns = [
    'tun', // Linux/Unix TUN interface
    'tap', // Linux/Unix TAP interface
    'ppp', // Point-to-Point Protocol
    'pptp', // PPTP VPN
    'l2tp', // L2TP VPN
    'ipsec', // IPsec VPN
    'vpn', // Generic "VPN" keyword
    'wireguard', // WireGuard VPN
    'openvpn', // OpenVPN VPN
    'softether', // SoftEther VPN
  ];

  // 获取当前网络类型有没有包含VPN
  Future<bool> isVPN() async {
    try {
      final interfaces = await NetworkInterface.list();
      bool isIosDevice = Platform.isIOS;
      return interfaces.any((interface) {
        return _commonVpnInterfaceNamePatterns.any((pattern) {
          if (isIosDevice &&
              (interface.name.toLowerCase().contains('ipsec') ||
                  interface.name.toLowerCase().contains('utun6') ||
                  interface.name.toLowerCase().contains('ikev2') ||
                  interface.name.toLowerCase().contains('l2tp'))) {
            return false;
          }
          return interface.name.toLowerCase().contains(pattern);
        });
      });
    } catch (e) {
      return false;
    }
  }

  // 监听网络状态变化
  Stream<List<ConnectivityResult>> onConnectivityChanged() {
    return _connectivity.onConnectivityChanged;
  }
}
