/*
 *  Copyright 2025-2026 R3944Realms
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package top.r3944realms.eroticdungeongame.util;

import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.*;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;

public class EntityUtil {
    public static List<HitResult> getRefLookAtEntityHitResult(Entity looker, Level level, float distance,
                                                              Predicate<Entity> condition, @Nullable Predicate<BlockState> ignorePredicate) {
        if (ignorePredicate == null) return getRefLookAtEntityHitResult(looker, level, distance, condition);
        Vec3 startPosition = looker.getEyePosition();
        Vec3 endPosition = looker.getLookAngle().normalize().scale(distance).add(startPosition);

        // 使用VISUAL或OUTLINE作为基础，然后手动过滤
        ClipContext clipContext = new ClipContext(startPosition, endPosition,
                ClipContext.Block.VISUAL, ClipContext.Fluid.NONE, looker);

        // 手动进行射线检测
        BlockHitResult clip = manualRayTrace(level, clipContext, ignorePredicate);
        endPosition = clip.getLocation();

        AABB range = looker.getBoundingBox().expandTowards(endPosition.subtract(startPosition));
        List<HitResult> hits = new ArrayList<>();
        List<? extends Entity> entities = level.getEntities(looker, range, condition);

        for (Entity entity : entities) {
            entity.getBoundingBox().clip(startPosition, endPosition).ifPresent(vec3 -> {
                hits.add(new EntityHitResult(entity, vec3));
            });
        }
        return hits;
    }

    @Contract("_, _, _ -> new")
    public static @NotNull BlockHitResult manualRayTrace(Level level, @NotNull ClipContext context,
                                                          @Nullable Predicate<BlockState> ignorePredicate) {
        Vec3 from = context.getFrom();
        Vec3 to = context.getTo();

        // 逐步进行射线检测
        double step = 0.1;
        Vec3 direction = to.subtract(from).normalize();
        double maxDistance = from.distanceTo(to);

        for (double d = 0; d < maxDistance; d += step) {
            Vec3 currentPos = from.add(direction.scale(d));
            BlockPos blockPos = BlockPos.containing(currentPos);
            BlockState state = level.getBlockState(blockPos);

            // 如果不是空气且不满足忽略条件
            if (!state.isAir()) {
                if (ignorePredicate == null || !ignorePredicate.test(state)) {
                    // 检查是否有碰撞
                    VoxelShape shape = context.getBlockShape(state, level, blockPos);
                    if (!shape.isEmpty()) {
                        BlockHitResult hit = shape.clip(from, to, blockPos);
                        if (hit != null) {
                            return new BlockHitResult(hit.getLocation(),
                                    Direction.getNearest(direction.x, direction.y, direction.z),
                                    blockPos, false);
                        }

                    }
                }
            }
        }

        // 如果没有碰到任何方块，返回终点
        return new BlockHitResult(to, Direction.getNearest(direction.x, direction.y, direction.z),
                BlockPos.containing(to), false);
    }
    public static List<HitResult> getRefLookAtEntityHitResult(Entity looker, Level level, float distance, Predicate<Entity> condition) {
        Vec3 startPosition = looker.getEyePosition();
        Vec3 endPosition = looker.getLookAngle().normalize().scale(distance).add(startPosition);
        BlockHitResult clip = level.clip(new ClipContext(startPosition, endPosition, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, looker));
        endPosition = clip.getLocation();
        AABB range = looker.getBoundingBox().expandTowards(endPosition.subtract(startPosition));
        List<HitResult> hits = new ArrayList<>();
        List<? extends Entity> entities = level.getEntities(looker, range, condition);
        for (Entity entity : entities) {
            Vec3 vec3 = entity.getBoundingBox().clip(startPosition, endPosition).orElse(null);
            if(vec3 != null) {
                EntityHitResult entityHitResult = new EntityHitResult(entity, vec3);
                hits.add(entityHitResult);
            }
        }
        return hits;
    }

    @Nullable
    public static Entity getTheNearestEntityFromHitResultList(Entity looker, List<HitResult> hitResults) {
        if(!hitResults.isEmpty()) {
            hitResults.sort(Comparator.comparingDouble(e -> e.getLocation().distanceTo(looker.getEyePosition())));
            if(!hitResults.isEmpty()) {
                HitResult hitResult = hitResults.get(0);
                if (hitResult instanceof EntityHitResult entityHitResult)
                    return entityHitResult.getEntity();
                else return null;
            }
        }
        return null;
    }

}
