package com.discordrules;

import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.command.CommandSource;
import net.minecraft.command.Commands;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.IFormattableTextComponent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RulesCommand {
    private static final Logger LOGGER = LogManager.getLogger(RulesCommand.class);

    public static void register(CommandDispatcher<CommandSource> dispatcher) {
        dispatcher.register(Commands.literal("rules").executes(context -> {
            CommandSource source = context.getSource();
            LOGGER.info("[DIAG] /rules invoked. isPlayer={}, token length={}, channel={}, messageId={}, isValid={}",
                source.getEntity() instanceof ServerPlayerEntity,
                ServerRulesConfig.BOT_TOKEN.get().length(),
                ServerRulesConfig.CHANNEL_ID.get(),
                ServerRulesConfig.MESSAGE_ID.get(),
                ServerRulesConfig.isMessageIdValid());
            if (!(source.getEntity() instanceof ServerPlayerEntity)) {
                LOGGER.info("[DIAG] Console path — fetching from Discord");
                DiscordFetcher.fetchRulesAsync().thenAccept(fetchedRules -> {
                    String rulesText;
                    if (fetchedRules != null) {
                        RulesCache.updateCache(fetchedRules);
                        rulesText = fetchedRules;
                    } else {
                        LOGGER.warn("Discord fetch failed. Using fallback rules.");
                        rulesText = RulesCache.getRules();
                    }
                    source.getServer().execute(() -> source.sendSuccess(DiscordFormatter.formatRules(rulesText), false));
                });
                return 1;
            }
            ServerPlayerEntity player = (ServerPlayerEntity) source.getEntity();
            if (!CooldownManager.checkAndUpdateCooldown(player)) return 0;
            if (RulesCache.isCacheValid()) {
                player.sendMessage(DiscordFormatter.formatRules(RulesCache.getRules()), player.getUUID());
                return 1;
            }
            player.sendMessage(new StringTextComponent("\u00a77Fetching latest rules..."), player.getUUID());
            DiscordFetcher.fetchRulesAsync().thenAccept(fetchedRules -> {
                String rulesText;
                if (fetchedRules != null) {
                    RulesCache.updateCache(fetchedRules);
                    rulesText = fetchedRules;
                } else {
                    LOGGER.warn("Discord fetch failed. Falling back to cache for {}", player.getName().getString());
                    rulesText = RulesCache.getRules();
                }
                IFormattableTextComponent formattedRules = DiscordFormatter.formatRules(rulesText);
                source.getServer().execute(() -> player.sendMessage(formattedRules, player.getUUID()));
            });
            return 1;
        }));
    }
}
