package me.earthme.luminol.mobaireducer;

import me.earthme.luminol.config.modules.optimizations.MobAiThrottleConfig;
import net.minecraft.world.entity.Mob;

/**
 * Distance-based AI throttle for mobs (DAB-style). See {@link MobAiThrottleConfig}.
 *
 * <p>Decides, for the current tick, whether a mob should run its full goal/target/navigation
 * step or skip it this tick. The "how far from a player" signal is {@code activatedTick} from
 * Paper's EntityActivationRange, so this adds no per-mob player scan.
 */
public final class MobAiThrottle {

    private MobAiThrottle() {}

    /**
     * @return true if the mob should run its full AI step this tick; false to skip (throttle).
     *         Always true when disabled, when the mob was recently active, or for low intervals.
     */
    public static boolean shouldRunFullAi(Mob mob) {
        if (!MobAiThrottleConfig.enabled) return true;

        final long currentTick;
        try {
            currentTick = io.papermc.paper.threadedregions.RegionizedServer.getCurrentTick();
        } catch (IllegalStateException notOnRegionThread) {
            return true; // be safe off-region
        }

        long inactiveFor = currentTick - mob.activatedTick;
        if (inactiveFor < MobAiThrottleConfig.inactiveTicksTier1) {
            return true; // a player is (or was just) nearby — full rate, no perceptible lag
        }

        int interval;
        if (inactiveFor >= MobAiThrottleConfig.inactiveTicksTier3) {
            interval = MobAiThrottleConfig.tier3Interval;
        } else if (inactiveFor >= MobAiThrottleConfig.inactiveTicksTier2) {
            interval = MobAiThrottleConfig.tier2Interval;
        } else {
            interval = MobAiThrottleConfig.tier1Interval;
        }
        if (interval <= 1) return true;

        // Stagger by entity id so throttled mobs don't all run their AI on the same tick.
        return ((mob.tickCount + mob.getId()) % interval) == 0;
    }
}
