import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:root_checker_plus/root_checker_plus.dart';

Future<bool> isDeviceRootedOrJailbroken() async {
  if (Platform.isAndroid) {
    bool? isRooted = await RootCheckerPlus.isRootChecker();
    return isRooted ?? false;
  } else if (Platform.isIOS) {
    return await _isJailbroken();
  } else {
    return false; // Other platforms are not supported
  }
}

Future<bool> _isJailbroken() async {
  DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
  IosDeviceInfo iosInfo = await deviceInfo.iosInfo;

  // List of common jailbreak indicators
  List<String> jailbreakIndicators = ['/Applications/Cydia.app', '/Library/MobileSubstrate/MobileSubstrate.dylib', '/bin/bash', '/usr/sbin/sshd', '/etc/apt', '/private/var/lib/apt/', '/private/var/lib/cydia', '/var/log/syslog'];

  // Check for the existence of jailbreak indicator files
  for (String indicator in jailbreakIndicators) {
    if (File(indicator).existsSync()) {
      return true;
    }
  }

  // Check if we can write outside the app's sandbox
  try {
    File('/private/jailbreak.txt').writeAsStringSync('Jailbreak test');
    return true;
  } catch (e) {
    // If we cannot write outside the sandbox, it's likely not jailbroken
  }

  // Check for suspicious environment variables
  if (Platform.environment.containsKey('DYLD_INSERT_LIBRARIES')) {
    return true;
  }

  return false;
}
