package net.Chipperfluff.chipi.command;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.command.CommandSource;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;

import net.Chipperfluff.chipi.world.gen.struct.ChipiStructures;

public class ChpCommand {

    public static void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(
            CommandManager.literal("chp")
            .then(
                CommandManager.argument("name", StringArgumentType.word())
                    // autocomplete structure names
                    .suggests(
                        (ctx, builder) ->
                            CommandSource.suggestMatching(ChipiStructures.getNames(), builder))
                    .then(
                        CommandManager.argument("pos", BlockPosArgumentType.blockPos())
                            // default: no marker
                            .executes(ctx -> execute(ctx, false))
                            // optional marker flag
                            .then(
                                CommandManager.argument("marker", BoolArgumentType.bool())
                                    .executes(
                                        ctx -> execute(ctx, BoolArgumentType.getBool(ctx, "marker")
                                    )
                                )
                            )
                        )
            )
        );
    }

    private static int execute(CommandContext<ServerCommandSource> ctx, boolean marker) {
        ServerCommandSource source = ctx.getSource();
        ServerWorld world = source.getWorld();

        String name = StringArgumentType.getString(ctx, "name");
        BlockPos pos = BlockPosArgumentType.getBlockPos(ctx, "pos");

        var structure = ChipiStructures.get(name);

        if (structure == null) {
            source.sendError(Text.literal("Unknown structure: " + name));
            return 0;
        }

        // SINGLE call – structure decides everything
        structure.placeCommand(world, pos, marker);

        source.sendFeedback(
            () -> Text.literal("Placed structure '" + name + (marker ? "' with structure block" : "'")),
            false);

        return 1;
    }
}
