package com.livingworld.commands;

import com.livingworld.core.simulation.SimulationManager;
import com.livingworld.regions.RegionManager;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.world.phys.Vec3;

/**
 * Forces the full module pipeline to run on a single region immediately,
 * bypassing the scheduler. Useful for observing simulation effects without
 * waiting for the next scheduled tick.
 */
public final class ForceUpdateCommand {

    private ForceUpdateCommand() {
    }

    public static int executeAtSelf(
            CommandSourceStack source,
            RegionManager regionManager,
            SimulationManager simulationManager) {
        if (source == null) throw new IllegalArgumentException("source must not be null");
        if (regionManager == null) throw new IllegalArgumentException("regionManager must not be null");
        if (simulationManager == null) throw new IllegalArgumentException("simulationManager must not be null");

        Vec3 pos = source.getPosition();
        String dimensionId = source.getLevel().dimension().location().toString();
        // Ensure the region is loaded/created before asking the simulation manager to update it.
        var region = regionManager.getOrCreateRegionAtBlock(
                dimensionId, (int) Math.floor(pos.x), (int) Math.floor(pos.z));
        simulationManager.forceUpdateRegion(region.getCoordinate());

        String msg = "Forced update on region " + region.getCoordinate().stableId()
                + " — run '/lw region info' to see the result.";
        source.sendSuccess(() -> Component.literal(msg), true);
        return 1;
    }
}
