using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;

namespace AxCopilot.Security;

internal static class AntiTamper
{
	private static readonly string[] TrustedIpPrefixes = new string[6] { "11.99.", "11.90.", "11.96.", "12.25.", "12.23.", "12.24." };

	private static readonly string[] KnownDebuggers = new string[16]
	{
		"dnspy", "dnspy-x86", "ilspy", "dotpeek", "de4dot", "ollydbg", "x64dbg", "x32dbg", "windbg", "ida",
		"ida64", "ghidra", "cheatengine", "processhacker", "fiddler", "wireshark"
	};

	[DllImport("kernel32.dll")]
	private static extern bool IsDebuggerPresent();

	[DllImport("kernel32.dll")]
	private static extern bool CheckRemoteDebuggerPresent(nint hProcess, ref bool isDebuggerPresent);

	public static void Check()
	{
	}

	private static bool IsBeingDebugged()
	{
		if (Debugger.IsAttached)
		{
			return true;
		}
		try
		{
			if (IsDebuggerPresent())
			{
				return true;
			}
		}
		catch
		{
		}
		try
		{
			bool isDebuggerPresent = false;
			CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref isDebuggerPresent);
			if (isDebuggerPresent)
			{
				return true;
			}
		}
		catch
		{
		}
		return false;
	}

	private static bool IsDecompilerRunning()
	{
		try
		{
			Process[] processes = Process.GetProcesses();
			Process[] array = processes;
			foreach (Process process in array)
			{
				try
				{
					string text = process.ProcessName.ToLowerInvariant();
					string[] knownDebuggers = KnownDebuggers;
					foreach (string value in knownDebuggers)
					{
						if (text.Contains(value))
						{
							return true;
						}
					}
				}
				catch
				{
				}
			}
		}
		catch
		{
		}
		return false;
	}

	private static bool IsTrustedNetwork()
	{
		try
		{
			IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
			IPAddress[] array = hostAddresses;
			foreach (IPAddress iPAddress in array)
			{
				if (iPAddress.AddressFamily != AddressFamily.InterNetwork)
				{
					continue;
				}
				string text = iPAddress.ToString();
				string[] trustedIpPrefixes = TrustedIpPrefixes;
				foreach (string value in trustedIpPrefixes)
				{
					if (text.StartsWith(value))
					{
						return true;
					}
				}
			}
		}
		catch
		{
		}
		return false;
	}

	public static bool VerifyAssemblyIntegrity()
	{
		try
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			AssemblyName name = executingAssembly.GetName();
			return name.Version != null && name.Name == "AxCopilot";
		}
		catch
		{
			return false;
		}
	}
}
