package dev.nexo.module.combat.velocity;

import dev.nexo.client.Chat;
import dev.nexo.module.combat.VelocityModule;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S02PacketChat;
import net.minecraft.network.play.server.S03PacketTimeUpdate;
import net.minecraft.network.play.server.S06PacketUpdateHealth;
import net.minecraft.network.play.server.S07PacketRespawn;
import net.minecraft.network.play.server.S08PacketPlayerPosLook;
import net.minecraft.network.play.server.S12PacketEntityVelocity;
import net.minecraft.network.play.server.S13PacketDestroyEntities;
import net.minecraft.network.play.server.S18PacketEntityTeleport;
import net.minecraft.network.play.server.S25PacketBlockBreakAnim;
import net.minecraft.network.play.server.S27PacketExplosion;
import net.minecraft.network.play.server.S29PacketSoundEffect;
import net.minecraft.network.play.server.S2BPacketChangeGameState;
import net.minecraft.network.play.server.S2CPacketSpawnGlobalEntity;
import net.minecraft.network.play.server.S2FPacketSetSlot;

/**
 * 1:1 port of Boop's {@code BufferVelocity}.
 *
 * <p>Nothing happens until a knockback actually arrives. At that moment the mode starts
 * <em>blinking</em>: every packet that reaches the client from then on is held instead of processed.
 * The client briefly stops seeing the world, so the server's movement prediction for us keeps
 * running against a state it already accepted - and when the batch is replayed, the knockback lands
 * into a prediction that no longer matches, which cancels most of its effect.
 *
 * <p>There is no timer: once it starts blinking, the batch is only released when the module is
 * switched off (or the world changes). That is deliberate - the whole point is that the server's
 * prediction runs against a stale state for as long as the hold lasts.
 *
 * <p>An exact allow-list runs first and is never held, even mid-blinking. Those packets either
 * carry state the client cannot reconstruct out of order (health, time, chat, inventory, position
 * corrections, teleports) or would look wrong if delayed (thunder, game-state change).
 */
public class BufferVelocity extends VelocityMode {
    protected final List<Packet<?>> heldPackets = new ArrayList<Packet<?>>();
    protected WorldClient packetWorld;
    protected boolean blinking;

    /** Wall-clock time the current hold began, for the timeout. */
    protected long holdStartMs;
    /** Highest countdown number already announced, so each number prints once. */
    private int announcedCountdown;

    /**
     * Hard limit on how long packets may stay held.
     *
     * <p>Holding without a timer means the client stops acknowledging inbound state entirely. The
     * server eventually gives up on it - keepalive or transaction timeouts - and drops the
     * connection. Releasing before that happens keeps the hold usable for as long as it is useful
     * and no longer.
     */
    /** Configured warning length, clamped to a sane range. */
    protected static int releaseWarningSeconds() {
        int seconds = dev.nexo.config.NexoConfig.velocityreleaseSeconds;
        if (seconds < 1) {
            seconds = 1;
        }
        if (seconds > 10) {
            seconds = 10;
        }
        return seconds;
    }

    /**
     * Configured hold limit in milliseconds.
     *
     * @return the limit, or {@code 0} when the timeout is disabled
     */
    protected static long holdTimeoutMs() {
        int tenths = dev.nexo.config.NexoConfig.velocityholdTimeout;
        if (tenths <= 0) {
            return 0L;
        }
        if (tenths > 300) {
            tenths = 300;
        }
        // tenths of a second -> milliseconds
        return tenths * 100L;
    }
    protected boolean pendingJump;

    public BufferVelocity(VelocityModule parent) {
        super(parent);
    }

    @Override
    public void onPacketReceive(Packet<?> packet, boolean[] cancelled) {
        EntityPlayerSP player = VelocityModule.mc().thePlayer;
        if (player == null || VelocityModule.mc().theWorld == null) {
            return;
        }
        // A respawn invalidates the world the batch belongs to.
        if (packet instanceof S07PacketRespawn) {
            clearHold();
            return;
        }
        // Allow-list first: these are never delayed, blinking or not.
        if (isAlwaysAllowed(packet)) {
            return;
        }
        // Only packets the play handler can actually accept may be held. A status or login packet
        // mixed into the stream (some proxies emit S00PacketServerInfo on the play connection) is
        // not playable at all, and replaying it later casts the play handler to the status handler
        // and crashes the client. Letting them straight through is both safer and closer to vanilla.
        if (!isPlayPacket(packet)) {
            return;
        }
        if (!blinking && isKnockbackPacket(packet)) {
            if (!parent.canActOnSwing()) {
                VelocityTrace.log("hold", "knockback ignored (canActOnSwing=false) "
                        + packet.getClass().getSimpleName());
                return;
            }
            // Decide whether this particular knockback should be suppressed at all. The source has
            // to be inferred from what is in the world, because the packet does not carry it.
            KnockbackSource.Type source = KnockbackSource.classify();
            if (!suppresses(source)) {
                VelocityTrace.log("hold", "knockback allowed through, source=" + source);
                return;
            }
            VelocityTrace.log("hold", "knockback suppressed, source=" + source);
            if (packet instanceof S12PacketEntityVelocity
                    && ((S12PacketEntityVelocity) packet).getMotionY() > 0) {
                pendingJump = true;
            }
            blinking = true;
            packetWorld = VelocityModule.mc().theWorld;
            holdStartMs = System.currentTimeMillis();
            announcedCountdown = 0;
            VelocityTrace.log("hold", "START by " + packet.getClass().getSimpleName()
                    + String.format(" timeout=%.1fs", holdTimeoutMs() / 1000.0));
        }
        if (blinking) {
            cancelled[0] = true;
            heldPackets.add(packet);
            VelocityTrace.log("hold", "held " + packet.getClass().getSimpleName()
                    + " n=" + heldPackets.size());
        }
    }

    /**
     * Whether a knockback from this source should be suppressed.
     *
     * <p>Each source has its own switch so a rod pull can be allowed through (being reeled in
     * repeatedly is far more disruptive than the push itself) while melee stays suppressed.
     */
    private static boolean suppresses(KnockbackSource.Type source) {
        switch (source) {
            case ROD:
                return dev.nexo.config.NexoConfig.velocitykbRod;
            case BOW:
                return dev.nexo.config.NexoConfig.velocitykbBow;
            case MELEE:
            default:
                return dev.nexo.config.NexoConfig.velocitykbMelee;
        }
    }

    /**
     * Whether this packet belongs to the play phase and can be replayed through the play handler.
     *
     * <p>Deliberately a name check rather than an exhaustive allow-list: the goal is only to keep
     * packets from the other connection phases out of the hold, not to police which play packets are
     * held. Anything whose handler lives outside {@code network.play} or {@code network.status} /
     * {@code network.login} is passed through untouched.
     */
    private static boolean isPlayPacket(Packet<?> packet) {
        String name = packet.getClass().getName();
        // Status and login packets have handlers of a different type; replaying them is a cast
        // error by construction.
        if (name.startsWith("net.minecraft.network.status.")
                || name.startsWith("net.minecraft.network.login.")) {
            return false;
        }
        // Handshake is connection setup and never has a play handler.
        if (name.startsWith("net.minecraft.network.handshake.")) {
            return false;
        }
        return true;
    }

    /**
     * Packets that are never held.
     *
     * <p>Transcribed from the reference build; each entry is there because delaying it desyncs
     * something the client cannot repair later.
     */
    protected boolean isAlwaysAllowed(Packet<?> packet) {
        if (packet instanceof S03PacketTimeUpdate
                || packet instanceof S06PacketUpdateHealth
                || packet instanceof S13PacketDestroyEntities
                || packet instanceof S02PacketChat
                || packet instanceof S25PacketBlockBreakAnim
                || packet instanceof S2FPacketSetSlot
                || packet instanceof S08PacketPlayerPosLook
                || packet instanceof S18PacketEntityTeleport) {
            return true;
        }
        if (packet instanceof S2BPacketChangeGameState) {
            int state = ((S2BPacketChangeGameState) packet).getGameState();
            // 1 = begin raining, 2 = end raining, 7 = rain fade value, 8 = rain fade time.
            if (state == 1 || state == 2 || state == 7 || state == 8) {
                return true;
            }
        }
        if (packet instanceof S2CPacketSpawnGlobalEntity) {
            // 1.8.9 exposes no accessor for the type field, so every global entity spawn is let
            // through instead of only lightning. The difference is a few cosmetic entities.
            return true;
        }
        if (packet instanceof S29PacketSoundEffect
                && "ambient.weather.thunder".equalsIgnoreCase(
                        ((S29PacketSoundEffect) packet).getSoundName())) {
            return true;
        }
        return false;
    }

    @Override
    public void onPostPlayerUpdate() {
        if (!blinking) {
            return;
        }
        if (holdStartMs <= 0L) {
            // Defensive: a hold without a start time would compute an enormous elapsed and release
            // on the very next tick, then repeat - the countdown would spam chat every second.
            // Re-stamp it instead so the timeout measures from now.
            holdStartMs = System.currentTimeMillis();
            return;
        }
        long timeout = holdTimeoutMs();
        if (timeout <= 0L) {
            // Timeout disabled: the hold only ends when the module is switched off or the world
            // changes. Useful when a longer silence is wanted, at the risk of the server timing the
            // connection out.
            return;
        }
        long elapsed = System.currentTimeMillis() - holdStartMs;
        long remaining = timeout - elapsed;
        // Count down the last few seconds in chat so the release is never a surprise: the client
        // freezes for a moment when the backlog goes out, and without warning that looks like a
        // hang.
        if (dev.nexo.config.NexoConfig.velocityreleaseCountdown
                && remaining > 0 && remaining <= releaseWarningSeconds() * 1000L) {
            int seconds = (int) ((remaining + 999L) / 1000L);
            if (seconds > 0 && seconds <= releaseWarningSeconds() && seconds != announcedCountdown) {
                announcedCountdown = seconds;
                if (dev.nexo.config.NexoConfig.velocitydebug) {
                    dev.nexo.client.Chat.print("&ereleasing in &f" + seconds + "&e...");
                }
            }
        }
        if (remaining > 0) {
            return;
        }
        // Timed out. Hand everything over before the server decides we are gone.
        if (dev.nexo.config.NexoConfig.velocitydebug) {
            dev.nexo.client.Chat.print("&ereleased (timeout)");
        }
        announcedCountdown = 0;
        flushAll();
    }

    @Override
    public void onPostPlayerInput() {
        // The jump is issued from flushAll() instead: with no timer the release only happens when
        // the module is turned off, so there is no tick to wait for here.
    }

    @Override
    public void reset(boolean release) {
        if (release) {
            // flushAll() reads and clears pendingJump itself, so it must run first.
            flushAll();
        } else {
            pendingJump = false;
            clearHold();
        }
    }

    private boolean isKnockbackPacket(Packet<?> packet) {
        EntityPlayerSP player = VelocityModule.mc().thePlayer;
        if (player == null) {
            return false;
        }
        if (packet instanceof S12PacketEntityVelocity) {
            return ((S12PacketEntityVelocity) packet).getEntityID() == player.getEntityId();
        }
        if (packet instanceof S27PacketExplosion) {
            S27PacketExplosion explosion = (S27PacketExplosion) packet;
            return explosion.func_149149_c() != 0.0f
                    || explosion.func_149144_d() != 0.0f
                    || explosion.func_149147_e() != 0.0f;
        }
        return false;
    }

    protected void flushAll() {
        List<Packet<?>> batch = new ArrayList<Packet<?>>(heldPackets);
        WorldClient world = packetWorld;
        int count = batch.size();
        boolean jump = pendingJump;
        VelocityTrace.log("release", "FLUSH " + count + " packets"
                + String.format(" held=%.1fs", (System.currentTimeMillis() - holdStartMs) / 1000.0));
        clearHold();
        parent.replayPackets(batch, world);
        // The knockback packet is inside the batch, so jumping has to happen after the replay.
        if (jump) {
            EntityPlayerSP player = VelocityModule.mc().thePlayer;
            if (player != null && player.movementInput != null) {
                player.movementInput.jump = true;
            }
        }
    }

    protected void clearHold() {
        heldPackets.clear();
        packetWorld = null;
        blinking = false;
        holdStartMs = 0L;
        announcedCountdown = 0;
    }

    /** Packets currently held, for the HUD. */
    public int heldCount() {
        return heldPackets.size();
    }

    public boolean isBlinking() {
        return blinking;
    }
}
