package land.chipmunk.chipmunkmod.util;

import com.mojang.brigadier.Command;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.config.Configuration;
import land.chipmunk.chipmunkmod.modules.Chat;
import land.chipmunk.chipmunkmod.modules.custom_chat.CustomChat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.player.LocalPlayer;
import org.apache.commons.codec.binary.Hex;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class BotValidationUtilities {
    public static int hbot (final String command) throws RuntimeException {
        final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.hbot;
        final Minecraft client = Minecraft.getInstance();
        final ClientPacketListener networkHandler = client.getConnection();

        final String prefix = info.prefix;
        final String key = info.key;
        if (key == null)
            throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");

        try {
            final MessageDigest md = MessageDigest.getInstance("SHA-256");
            final String time = String.valueOf(System.currentTimeMillis() / 10000);
            final String input = prefix + command.replaceAll("&[0-9a-fklmnor]", "") + ";" + client.player.getStringUUID() + ";" + time + ";" + key;
            final byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            final BigInteger bigInt = new BigInteger(1, Arrays.copyOfRange(hash, 0, 4));
            final String stringHash = bigInt.toString(Character.MAX_RADIX);

            Chat.sendChatMessage(prefix + command + " " + stringHash, true);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }

    public static int sbot (final String command) throws RuntimeException {
        final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.sbot;
        final Minecraft client = Minecraft.getInstance();
        final ClientPacketListener networkHandler = client.getConnection();

        final String prefix = info.prefix;
        final String key = info.key;
        if (key == null)
            throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");

        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            final String time = String.valueOf(System.currentTimeMillis() / 20000);
            final String input = prefix + command.replaceAll("&[0-9a-fklmnorx]", "") + ";" + client.player.getName().getString() + ";" + time + ";" + key;
            final byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            final BigInteger bigInt = new BigInteger(1, Arrays.copyOfRange(hash, 0, 4));
            final String stringHash = bigInt.toString(Character.MAX_RADIX);

            Chat.sendChatMessage(prefix + command + " " + stringHash, true);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }

    public static int chomens (final String command) throws RuntimeException {
        final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.chomens;

        final Minecraft client = Minecraft.getInstance();

        final LocalPlayer player = client.player;

        final String prefix = info.prefix;
        final String key = info.key;
        if (key == null)
            throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");

        try {
            final String[] arguments = command.split(" ");

            final String trimmedInput = String.join(" ", arguments).trim();
            final String[] splitInput = trimmedInput.contains("\n")
                    ? trimmedInput.split(" ")
                    : trimmedInput.split("\\s+");
            final String joinedSplitInput = String.join(" ", splitInput);

            final MessageDigest md = MessageDigest.getInstance("SHA-256");
            final String time = String.valueOf(System.currentTimeMillis() / 5_000);
            final String input = player.getStringUUID() + joinedSplitInput + time + key;
            final byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            String stringHash = new String(Hex.encodeHex(hash)).substring(0, 16);

            final boolean shouldSectionSign = CustomChat.INSTANCE.enabled && player.canUseGameMasterBlocks();

            if (shouldSectionSign) {
                stringHash = String.join("",
                                         Arrays.stream(stringHash.split(""))
                                                 .map((letter) -> "§" + letter)
                                                 .toArray(String[]::new)
                );
            }

            final String[] restArguments = Arrays.copyOfRange(arguments, 1, arguments.length);

            final String toSend = prefix +
                    arguments[0] +
                    " " +
                    stringHash +
                    (shouldSectionSign ? "§r" : "") +
                    " " +
                    String.join(" ", restArguments);

            Chat.sendChatMessage(toSend);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }

    public static int qilk (final String command) throws RuntimeException {
        final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.qilk;
        final Minecraft client = Minecraft.getInstance();

        final String prefix = info.prefix;
        final String key = info.key;
        if (key == null)
            throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");

        try {
            final MessageDigest md = MessageDigest.getInstance("SHA-256");
            final long time = Math.floorDiv(System.currentTimeMillis(), 2000);

            final String[] wholeArguments = command.split(" ");
            final String[] restArguments = Arrays.copyOfRange(wholeArguments, 1, wholeArguments.length);

            // lol this is literally chomens bot input with uwu and :
            final String input = "uwu:" + key + ":" + client.player.getStringUUID() + ":" + wholeArguments[0] + ":" + time;

            final byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            final String stringHash = new String(Hex.encodeHex(hash));

            Chat.sendChatMessage(prefix + wholeArguments[0] + " " + stringHash + " " + String.join(" ", restArguments), true);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }

    public static int fnfboyfriend (final String command) {
        try {
            final String prefix = ChipmunkMod.CONFIG.bots.fnfboyfriend.prefix;

            final String[] arguments = command.split(" ");

            final long currentTime = System.currentTimeMillis() / 2000;
            final String key = ChipmunkMod.CONFIG.bots.fnfboyfriend.key;
            if (key == null)
                throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");
            final String input = currentTime + key;
            final MessageDigest digest = MessageDigest.getInstance("SHA-256");
            final byte[] hash = digest.digest(input.getBytes());
            final StringBuilder hexString = new StringBuilder();
            for (final byte b : hash) {
                final String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            final String[] restArguments = Arrays.copyOfRange(arguments, 1, arguments.length);

            final String result = hexString.substring(0, 16);

            Chat.sendChatMessage(prefix + arguments[0] + " " + result + " " + String.join(" ", restArguments));
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }

    public static int nbot (final String command) throws RuntimeException {
        final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.nbot;

        final Minecraft client = Minecraft.getInstance();

        final String prefix = info.prefix;
        final String key = info.key;
        if (key == null)
            throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");

        try {
            final String[] arguments = command.split(" ");

            final MessageDigest md = MessageDigest.getInstance("SHA-256");

            final long time = Math.floorDiv(System.currentTimeMillis(), 250);

            // yep it is very raw code indeed.
            final String input = "ThisCodeIsRaw;" + client.player.getStringUUID() + ";" + time + ";" + key;

            final byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            final byte[] positiveDigest = new byte[digest.length + 1];

            System.arraycopy(digest, 0, positiveDigest, 1, digest.length);

            final BigInteger bi = new BigInteger(positiveDigest);

            final String b36 = bi.toString(36);

            final String stringHash = b36.length() > 16 ? b36.substring(0, 16) : b36;

            final String[] restArguments = Arrays.copyOfRange(arguments, 1, arguments.length);

            final String toSend = prefix +
                    arguments[0] +
                    " " +
                    stringHash +
                    " " +
                    String.join(" ", restArguments);

            Chat.sendChatMessage(toSend, true);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }

    public static int kittycorp (final String command) throws RuntimeException {
        final Configuration.BotInfo info = ChipmunkMod.CONFIG.bots.kittycorp;
        final ClientPacketListener networkHandler = Minecraft.getInstance().getConnection();

        final String prefix = info.prefix;
        final String key = info.key;
        if (key == null)
            throw new RuntimeException("The key of the bot is unspecified (null), did you incorrectly add it to your config?");

        try {
            final MessageDigest md = MessageDigest.getInstance("SHA-256");
            final String time = String.valueOf(System.currentTimeMillis() / 10000);
            final String input = prefix + command.replaceAll("&[0-9a-fklmnorx]", "") + ";" + time + ";" + key;
            final byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            final BigInteger bigInt = new BigInteger(1, Arrays.copyOfRange(hash, 0, 4));
            final String stringHash = bigInt.toString(Character.MAX_RADIX);

            Chat.sendChatMessage(prefix + command + " " + stringHash, true);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return Command.SINGLE_SUCCESS;
    }
}
