package com.livingworld.commands;

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

/**
 * Prints the Living World region state — either at the caller's position or
 * at explicit block coordinates.
 */
public final class RegionInfoCommand {

    private RegionInfoCommand() {
    }

    /** Uses the command-source position (player standing location). */
    public static int executeAtSelf(
            CommandSourceStack source,
            RegionManager regionManager) {
        if (source == null) throw new IllegalArgumentException("source must not be null");
        if (regionManager == null) throw new IllegalArgumentException("regionManager must not be null");

        Vec3 position = source.getPosition();
        String dimensionId = source.getLevel().dimension().location().toString();
        Region region = regionManager.getOrCreateRegionAtBlock(
                dimensionId,
                (int) Math.floor(position.x),
                (int) Math.floor(position.z));

        return sendLines(source, region);
    }

    /** Uses explicit block X/Z coordinates in the caller's current dimension. */
    public static int executeAt(
            CommandSourceStack source,
            RegionManager regionManager,
            int blockX,
            int blockZ) {
        if (source == null) throw new IllegalArgumentException("source must not be null");
        if (regionManager == null) throw new IllegalArgumentException("regionManager must not be null");

        String dimensionId = source.getLevel().dimension().location().toString();
        Region region = regionManager.getOrCreateRegionAtBlock(dimensionId, blockX, blockZ);
        return sendLines(source, region);
    }

    private static int sendLines(CommandSourceStack source, Region region) {
        for (String line : RegionInfoFormatter.format(region)) {
            source.sendSuccess(() -> Component.literal(line), false);
        }
        return 1;
    }
}
