package com.discordrules;

import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.server.level.ServerPlayer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

    public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
        dispatcher.register(Commands.literal("rules").executes(context -> {
            CommandSourceStack source = context.getSource();
            LOGGER.info("[DIAG] /rules invoked. isPlayer={}, token length={}, channel={}, messageId={}, isValid={}",
                source.isPlayer(),
                ServerRulesConfig.BOT_TOKEN.get().length(),
                ServerRulesConfig.CHANNEL_ID.get(),
                ServerRulesConfig.MESSAGE_ID.get(),
                ServerRulesConfig.isMessageIdValid());
            if (!source.isPlayer()) {
                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.sendSystemMessage(DiscordFormatter.formatRules(rulesText)));
                });
                return 1;
            }
            ServerPlayer player = source.getPlayer();
            if (!CooldownManager.checkAndUpdateCooldown(player)) return 0;
            if (RulesCache.isCacheValid()) {
                player.sendSystemMessage(DiscordFormatter.formatRules(RulesCache.getRules()));
                return 1;
            }
            player.sendSystemMessage(Component.literal("\u00a77Fetching latest rules..."));
            DiscordFetcher.fetchRulesAsync().thenAccept(fetchedRules -> {
                String rulesText;
                if (fetchedRules != null) {
                    RulesCache.updateCache(fetchedRules);
                    rulesText = fetchedRules;
                } else {
                    LOGGER.warn("Discord fetch failed. Falling back to cached rules for {}", player.getName().getString());
                    rulesText = RulesCache.getRules();
                }
                MutableComponent formattedRules = DiscordFormatter.formatRules(rulesText);
                source.getServer().execute(() -> player.sendSystemMessage(formattedRules));
            });
            return 1;
        }));
    }
}
