package net.minecraft.world.level.levelgen.material;

import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.DoubleSupplier;
import java.util.function.Function;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.Mth;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.PositionalRandomFactory;
import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.VerticalAnchor;
import net.minecraft.world.level.levelgen.WorldGenerationContext;
import net.minecraft.world.level.levelgen.densityfunction.DensityBuffer;
import net.minecraft.world.level.levelgen.densityfunction.DensityFunction;
import net.minecraft.world.level.levelgen.densityfunction.DensitySampler;
import net.minecraft.world.level.levelgen.densityfunction.DensitySamplerSet;
import net.minecraft.world.level.levelgen.densityfunction.DensityVolume;
import net.minecraft.world.level.levelgen.material.condition.ConditionEvaluator;
import net.minecraft.world.level.levelgen.synth.Noise;
import net.minecraft.world.level.levelgen.synth.NormalNoise;
import org.jspecify.annotations.Nullable;

public final class MaterialRuleContext {
	private static final int HOW_FAR_BELOW_PRELIMINARY_SURFACE_LEVEL_TO_BUILD_SURFACE = 8;
	private final MaterialSystem system;
	private final RandomState randomState;
	private final DensityVolume expectedVolume;
	private final DensitySamplerSet densitySamplers;
	private final Function<BlockPos, Holder<Biome>> biomeGetter;
	private final WorldGenerationContext context;
	private final @Nullable Set<Holder<Biome>> possibleBiomes;
	private final DensityVolume preliminarySurfaceVolume;
	private @Nullable DensityBuffer preliminarySurfaceBuffer;
	private final Map<ResourceKey<NormalNoise>, DoubleSupplier> noiseSamplers2d = new IdentityHashMap<>();
	private final Map<ResourceKey<NormalNoise>, DoubleSupplier> noiseSamplers3d = new IdentityHashMap<>();
	private long lastUpdateXZ = -9223372036854775807L;
	private int blockX;
	private int blockZ;
	private int surfaceGradientX;
	private int surfaceGradientZ;
	private int surfaceDepth;
	private long lastSurfaceDepth2Update = this.lastUpdateXZ - 1L;
	private double surfaceSecondary;
	private long lastMinSurfaceLevelUpdate = this.lastUpdateXZ - 1L;
	private int minSurfaceLevel;
	private long lastUpdateY = -9223372036854775807L;
	private final BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
	private @Nullable Holder<Biome> biome;
	private int blockY;
	private int waterHeight;
	private int stoneDepthBelow;
	private int stoneDepthAbove;

	MaterialRuleContext(
		final MaterialSystem system,
		final RandomState randomState,
		final DensityVolume expectedVolume,
		final DensitySamplerSet densitySamplers,
		final Function<BlockPos, Holder<Biome>> biomeGetter,
		final WorldGenerationContext context,
		final @Nullable Set<Holder<Biome>> possibleBiomes
	) {
		this.system = system;
		this.randomState = randomState;
		this.expectedVolume = expectedVolume;
		this.densitySamplers = densitySamplers;
		this.biomeGetter = biomeGetter;
		this.context = context;
		this.possibleBiomes = possibleBiomes;
		this.preliminarySurfaceVolume = new DensityVolume(
			expectedVolume.sizeX(), 1, expectedVolume.sizeZ(), expectedVolume.minBlockX(), 0, expectedVolume.minBlockZ()
		);
	}

	void updateXZ(final int blockX, final int blockZ, final int surfaceGradientX, final int surfaceGradientZ) {
		this.lastUpdateXZ++;
		this.lastUpdateY++;
		this.blockX = blockX;
		this.blockZ = blockZ;
		this.surfaceGradientX = surfaceGradientX;
		this.surfaceGradientZ = surfaceGradientZ;
		this.surfaceDepth = this.system.getSurfaceDepth(blockX, blockZ);
	}

	void updateY(final int stoneDepthAbove, final int stoneDepthBelow, final int waterHeight, final int blockY) {
		this.lastUpdateY++;
		this.biome = null;
		this.blockY = blockY;
		this.waterHeight = waterHeight;
		this.stoneDepthBelow = stoneDepthBelow;
		this.stoneDepthAbove = stoneDepthAbove;
	}

	public double getSurfaceSecondary() {
		if (this.lastSurfaceDepth2Update != this.lastUpdateXZ) {
			this.lastSurfaceDepth2Update = this.lastUpdateXZ;
			this.surfaceSecondary = this.system.getSurfaceSecondary(this.blockX, this.blockZ);
		}

		return this.surfaceSecondary;
	}

	public Holder<Biome> getBiome() {
		if (this.biome == null) {
			this.biome = this.biomeGetter.apply(this.pos.set(this.blockX, this.blockY, this.blockZ));
		}

		return this.biome;
	}

	public int getSeaLevel() {
		return this.system.getSeaLevel();
	}

	public int getMinSurfaceLevel() {
		if (this.lastMinSurfaceLevelUpdate != this.lastUpdateXZ) {
			this.lastMinSurfaceLevelUpdate = this.lastUpdateXZ;
			int index = this.preliminarySurfaceVolume.indexOfBlock(this.blockX, 0, this.blockZ);
			float preliminarySurfaceLevel;
			if (index != -1) {
				if (this.preliminarySurfaceBuffer == null) {
					this.preliminarySurfaceBuffer = DensityBuffer.createUnpooled(this.preliminarySurfaceVolume.size());
					this.densitySamplers.get(this.system.preliminarySurfaceFunction()).sampleVolume(this.preliminarySurfaceBuffer, this.preliminarySurfaceVolume);
				}

				preliminarySurfaceLevel = this.preliminarySurfaceBuffer.get(index);
			} else {
				preliminarySurfaceLevel = this.densitySamplers.sampleValue(this.system.preliminarySurfaceFunction(), this.blockX, 0, this.blockZ);
			}

			this.minSurfaceLevel = Mth.floor(preliminarySurfaceLevel) + this.surfaceDepth - 8;
		}

		return this.minSurfaceLevel;
	}

	public DoubleSupplier getNoiseSampler(final ResourceKey<NormalNoise> noiseId, final boolean is3d) {
		return is3d
			? this.noiseSamplers3d.computeIfAbsent(noiseId, this::createNoiseSampler3d)
			: this.noiseSamplers2d.computeIfAbsent(noiseId, this::createNoiseSampler2d);
	}

	private DoubleSupplier createNoiseSampler2d(final ResourceKey<NormalNoise> noiseId) {
		final Noise noise = this.randomState.getOrCreateNoise(noiseId);
		return new DoubleSupplier() {
			private long lastUpdateXZ;
			private double lastNoise;

			{
				this.lastUpdateXZ = MaterialRuleContext.this.lastUpdateXZ - 1L;
			}

			@Override
			public double getAsDouble() {
				if (this.lastUpdateXZ != MaterialRuleContext.this.lastUpdateXZ) {
					this.lastNoise = noise.get(MaterialRuleContext.this.blockX, 0.0, MaterialRuleContext.this.blockZ);
					this.lastUpdateXZ = MaterialRuleContext.this.lastUpdateXZ;
				}

				return this.lastNoise;
			}
		};
	}

	private DoubleSupplier createNoiseSampler3d(final ResourceKey<NormalNoise> noiseId) {
		final Noise noise = this.randomState.getOrCreateNoise(noiseId);
		return new DoubleSupplier() {
			private long lastUpdateY;
			private double lastNoise;

			{
				this.lastUpdateY = MaterialRuleContext.this.lastUpdateY - 1L;
			}

			@Override
			public double getAsDouble() {
				if (this.lastUpdateY != MaterialRuleContext.this.lastUpdateY) {
					this.lastNoise = noise.get(MaterialRuleContext.this.blockX, MaterialRuleContext.this.blockY, MaterialRuleContext.this.blockZ);
					this.lastUpdateY = MaterialRuleContext.this.lastUpdateY;
				}

				return this.lastNoise;
			}
		};
	}

	public PositionalRandomFactory getOrCreateRandomFactory(final Identifier name) {
		return this.randomState.getOrCreateRandomFactory(name);
	}

	public MaterialRules.DensityGetter getDensitiesInChunk(final DensityFunction function, final boolean prefill) {
		DensitySampler.Bound sampler = this.densitySamplers.get(function);
		if (prefill) {
			DensityBuffer buffer = DensityBuffer.createUnpooled(this.expectedVolume.size());
			sampler.sampleVolume(buffer, this.expectedVolume);
			return () -> {
				int index = this.expectedVolume.indexOfBlock(this.blockX, this.blockY, this.blockZ);
				return index == -1 ? sampler.sampleValue(this.blockX, this.blockY, this.blockZ) : buffer.get(index);
			};
		} else {
			return () -> sampler.sampleValue(this.blockX, this.blockY, this.blockZ);
		}
	}

	public @Nullable Set<Holder<Biome>> possibleBiomes() {
		return this.possibleBiomes;
	}

	public int stoneDepthAbove() {
		return this.stoneDepthAbove;
	}

	public int stoneDepthBelow() {
		return this.stoneDepthBelow;
	}

	public int surfaceDepth() {
		return this.surfaceDepth;
	}

	public int waterHeight() {
		return this.waterHeight;
	}

	public int blockX() {
		return this.blockX;
	}

	public int blockY() {
		return this.blockY;
	}

	public int blockZ() {
		return this.blockZ;
	}

	public BlockPos blockPos() {
		return this.pos.set(this.blockX, this.blockY, this.blockZ);
	}

	public int surfaceGradientX() {
		return this.surfaceGradientX;
	}

	public int surfaceGradientZ() {
		return this.surfaceGradientZ;
	}

	public int resolveAnchorY(final VerticalAnchor anchor) {
		return anchor.resolveY(this.context);
	}

	public BlockState getBand(final int x, final int y, final int z) {
		return this.system.getBand(x, y, z);
	}

	public abstract static class LazyXZCondition implements ConditionEvaluator {
		protected final MaterialRuleContext context;
		private long lastUpdate;
		private @Nullable Boolean result;

		protected LazyXZCondition(final MaterialRuleContext context) {
			this.context = context;
			this.lastUpdate = context.lastUpdateXZ - 1L;
		}

		@Override
		public boolean test() {
			long lastContextUpdate = this.context.lastUpdateXZ;
			if (lastContextUpdate == this.lastUpdate) {
				if (this.result == null) {
					throw new IllegalStateException("Update triggered but the result is null");
				} else {
					return this.result;
				}
			} else {
				this.lastUpdate = lastContextUpdate;
				this.result = this.compute();
				return this.result;
			}
		}

		protected abstract boolean compute();
	}

	public abstract static class LazyYCondition implements ConditionEvaluator {
		protected final MaterialRuleContext context;
		private long lastUpdate;
		private @Nullable Boolean result;

		protected LazyYCondition(final MaterialRuleContext context) {
			this.context = context;
			this.lastUpdate = context.lastUpdateY - 1L;
		}

		@Override
		public boolean test() {
			long lastContextUpdate = this.context.lastUpdateY;
			if (lastContextUpdate == this.lastUpdate) {
				if (this.result == null) {
					throw new IllegalStateException("Update triggered but the result is null");
				} else {
					return this.result;
				}
			} else {
				this.lastUpdate = lastContextUpdate;
				this.result = this.compute();
				return this.result;
			}
		}

		protected abstract boolean compute();
	}
}
