/*
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
 *
 * Copyright (c) 2015 - 2026 CCBlueX
 *
 * LiquidBounce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LiquidBounce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
 */
package net.ccbluex.liquidbounce.features.module.modules.world.traps.traps

import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug
import net.ccbluex.liquidbounce.features.module.modules.world.traps.ModuleAutoTrap
import net.ccbluex.liquidbounce.render.engine.type.Color4b
import net.ccbluex.liquidbounce.utils.client.player
import net.ccbluex.liquidbounce.utils.entity.PlayerSimulationCache
import net.ccbluex.liquidbounce.utils.math.average
import net.minecraft.world.entity.EntityDimensions
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.player.Player
import net.minecraft.world.phys.Vec3
import kotlin.math.sqrt

object TrapPlayerSimulation {
    private val predictedPlayerStatesCache = HashMap<Player, ArrayDeque<PredictedPlayerPos>>()

    private const val SIMULATION_DISTANCE: Double = 10.0

    fun runSimulations(enemies: List<LivingEntity>) {
        val seenPlayers = ReferenceOpenHashSet<Player>()

        for (enemy in enemies) {
            if (enemy !is Player || enemy.distanceToSqr(player) > SIMULATION_DISTANCE * SIMULATION_DISTANCE) {
                continue
            }

            val simulation = PlayerSimulationCache.getSimulationForOtherPlayers(enemy)

            val predictedState = simulation.simulateBetween(0..25)

            var wasAirborne = !enemy.onGround()

            var ticks = 1

            val predictedPos = predictedState.firstNotNullOfOrNull {
                if (wasAirborne && it.onGround) {
                    return@firstNotNullOfOrNull PredictedPlayerPos(it.pos, ticks, enemy.position(), false)
                }

                wasAirborne = !it.onGround
                ticks++

                null
            } ?: PredictedPlayerPos(
                null,
                null,
                enemy.position(),
                enemy.deltaMovement.lengthSqr() < 0.05
            )

            seenPlayers.add(enemy)

            val simulationCache = this.predictedPlayerStatesCache.getOrPut(enemy, ::ArrayDeque)

            simulationCache.addLast(predictedPos)

            while (simulationCache.size > 10) {
                simulationCache.removeFirst()
            }
        }

        this.predictedPlayerStatesCache.keys.retainAll(seenPlayers)
    }

    /**
     * Searches for a position where a trap could be laid. Currently, that is just the landing position of
     * a jumping/falling player.
     *
     * @return position for the trap. `null` if the trap should not be placed.
     */
    fun findPosForTrap(target: LivingEntity, isTargetLocked: Boolean): Vec3? {
        if (target !is Player) {
            return target.position()
        }

        val simulationCache = this.predictedPlayerStatesCache[target] ?: return null

        val lastEntry = simulationCache.last()

        if (lastEntry.isStationary && !isTargetLocked) {
            return lastEntry.currPos
        }

        val positions = simulationCache.mapNotNull { it.nextOnGround }

        val canLayTrapInTime = (lastEntry.ticksToGround ?: 0) >= 8
        val sufficientEvidence = positions.size >= 5

        if (!sufficientEvidence || !canLayTrapInTime && !isTargetLocked) {
            return if (isTargetLocked) lastEntry.currPos else null
        }

        val avg = positions.average()
        val std = positions
            .sumOf { vec -> vec.subtract(avg).lengthSqr() }
            .let { sqrt(it / positions.size) }

        ModuleDebug.debugGeometry(
            ModuleAutoTrap,
            "PredictedPlayerPos",
            ModuleDebug.DebuggedBox(target.dimensions.makeBoundingBox(positions.last()), Color4b.RED.with(a = 127))
        )
        ModuleDebug.debugGeometry(
            ModuleAutoTrap,
            "PredictedPlayerPosStd",
            ModuleDebug.DebuggedBox(
                EntityDimensions.fixed((target.dimensions.width * std).toFloat(), 0.5F).makeBoundingBox(avg),
                Color4b.BLUE.with(a = 127)
            )
        )

        // The simulation is mostly certain that the player will land at that position
        if (std < 1.5) {
            return positions.last()
        }

        return null
    }

    private class PredictedPlayerPos(
        val nextOnGround: Vec3?,
        val ticksToGround: Int?,
        val currPos: Vec3,
        val isStationary: Boolean
    )
}
