using HarmonyLib;
using AsmodeeNet.Network;
using AsmodeeNet.Network.ScalableServer;
using com.daysofwonder.mm;
using Google.Protobuf;
using System;

namespace CustomServerMod
{
    [HarmonyPatch]
    public static class NetworkPatches
    {
        // 1. Redirect REST API
        [HarmonyPatch(typeof(NetworkParameters), "RestAPIBaseUrl")]
        [HarmonyPostfix]
        public static void RestAPIBaseUrl_Postfix(ref string __result)
        {
            CustomServerMod.Log.LogInfo($"[ORIGINAL] HTTP BaseURL request: {__result}");
            
            if (CustomServerMod.RedirectTraffic)
            {
                __result = "http://127.0.0.1:8080";
            }
        }

        // 2. Redirect Scalable Server (TCP)
        [HarmonyPatch(typeof(ServerConnection), "Connect")]
        [HarmonyPrefix]
        public static void Connect_Prefix(ServerConnection __instance)
        {
            if (__instance.NetworkParameters != null)
            {
                CustomServerMod.Log.LogInfo($"[ORIGINAL] TCP Target: {__instance.NetworkParameters.HostName}:{__instance.NetworkParameters.HostPort}");
            }

            if (CustomServerMod.RedirectTraffic && __instance.NetworkParameters != null)
            {
                __instance.NetworkParameters.HostName = "127.0.0.1";
                __instance.NetworkParameters.HostPort = 3000;
            }
        }

        // 3. Bypass SSL/Certificate Pinning
        [HarmonyPatch(typeof(CertificateVerifier), "ValidateCertificate")]
        [HarmonyPrefix]
        public static bool ValidateCertificate_Prefix(ref bool __result)
        {
            if (CustomServerMod.RedirectTraffic)
            {
                __result = true;
                return false;
            }
            return true;
        }

        [HarmonyPatch(typeof(CertificateVerifier), "isValid", MethodType.Getter)]
        [HarmonyPostfix]
        public static void IsValid_Postfix(ref bool __result)
        {
            if (CustomServerMod.RedirectTraffic)
            {
                __result = true;
            }
        }

        [HarmonyPatch(typeof(ServerConnection), "ValidateRemoteCertificate")]
        [HarmonyPrefix]
        public static bool ValidateRemoteCertificate_Prefix(ref bool __result)
        {
            if (CustomServerMod.RedirectTraffic)
            {
                __result = true;
                return false;
            }
            return true;
        }

        // 4. Packet Logger (Incoming)
        [HarmonyPatch(typeof(ServerConnection), "DispatchMessage")]
        [HarmonyPrefix]
        public static void DispatchMessage_Prefix(Message receivedMessage, long packetId)
        {
            if (CustomServerMod.LogPackets)
            {
                try
                {
                    // Use simple ToString or JsonFormatter
                    string json = receivedMessage.ToString();
                    CustomServerMod.Log.LogInfo($"[IN] Packet {packetId} (Type: {receivedMessage.RequestCase}): {json}");
                }
                catch (Exception e)
                {
                    CustomServerMod.Log.LogWarning($"Failed to log incoming packet {packetId}: {e.Message}");
                }
            }
        }

        // 5. Packet Logger (Outgoing)
        // Hook EnqueuePacketToBeSentToServer to capture outgoing messages before they are serialized
        [HarmonyPatch(typeof(ServerConnection), "EnqueuePacketToBeSentToServer")]
        [HarmonyPostfix]
        public static void EnqueuePacketToBeSentToServer_Postfix(Packet packet)
        {
            if (CustomServerMod.LogPackets && packet?.Payload != null)
            {
                try
                {
                    string json = packet.Payload.ToString();
                    CustomServerMod.Log.LogInfo($"[OUT] Packet {packet.Id} (Type: {packet.Payload.RequestCase}): {json}");
                }
                catch (Exception e)
                {
                    CustomServerMod.Log.LogWarning($"Failed to log outgoing packet: {e.Message}");
                }
            }
        }
    }
}
