package com.livingworld.commands;

import com.livingworld.core.simulation.SimulationManager;
import com.livingworld.debug.SimulationProfileSnapshot;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import java.util.StringJoiner;

/**
 * Shows the profiler snapshot from the last simulation cycle.
 */
public final class StatsCommand {

    private StatsCommand() {
    }

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

        SimulationProfileSnapshot snap = simulationManager.createProfileSnapshot();

        String cycleMs = String.format("%.2f", snap.totalCycleNanos() / 1_000_000.0);
        String header = "LW stats:"
                + "  cycle=" + cycleMs + "ms"
                + "  events=" + snap.eventsPublished()
                + "  regions=" + snap.regionsUpdated()
                + "  saves=" + snap.savesPerformed()
                + "  budget_overrun=" + snap.budgetExceeded()
                + "  sim_tick=" + simulationManager.getSimulationTickCounter();
        source.sendSuccess(() -> Component.literal(header), false);

        if (!snap.moduleTimings().isEmpty()) {
            StringJoiner timings = new StringJoiner("  ");
            snap.moduleTimings().forEach((id, nanos) ->
                    timings.add(id + "=" + String.format("%.2f", nanos / 1_000_000.0) + "ms"));
            String moduleLine = "Modules:  " + timings;
            source.sendSuccess(() -> Component.literal(moduleLine), false);
        }
        return 1;
    }
}
