Volver al índice

src/main/java/ar/com/companeros/world/ProductionPlanner.java

package ar.com.companeros.world;

import java.util.*;
import java.util.function.Function;

/** Plan mecánico de recetas: el agente elige el producto, el inventario impone los recursos. */
public final class ProductionPlanner {
    public static final String TABLE = "minecraft:crafting_table";
    public record Recipe(String id, String output, int amount, boolean table, List<List<String>> ingredients) { }
    public record Step(String recipe, String output, boolean deployTable) { }
    public record Plan(List<Step> steps, Map<String, Integer> missing, boolean complete) { }
    private final Function<String, List<Recipe>> recipes;
    private int remaining = 2048;
    private State bestFailure;
    private static final class State {
        final Map<String, Integer> stock;
        final List<Step> steps;
        final Map<String, Integer> missing;
        boolean table;
        State(Map<String, Integer> stock, boolean table) {
            this.stock = new HashMap<>(stock); this.table = table;
            steps = new ArrayList<>(); missing = new TreeMap<>();
        }
        State(State from) {
            stock = new HashMap<>(from.stock); steps = new ArrayList<>(from.steps);
            missing = new TreeMap<>(from.missing); table = from.table;
        }
        void accept(State from) {
            stock.clear(); stock.putAll(from.stock); steps.clear(); steps.addAll(from.steps);
            missing.clear(); missing.putAll(from.missing); table = from.table;
        }
    }
    public ProductionPlanner(Function<String, List<Recipe>> recipes) { this.recipes = recipes; }

    // Se planifica sobre una copia. Un fallo no consume ni fabrica nada.
    public Plan plan(Map<String, Integer> inventory, boolean hasTable, String output, int additional) {
        if (additional < 1 || additional > 64) throw new IllegalArgumentException("Cantidad de 1 a 64");
        remaining = 2048; bestFailure = null;
        State state = new State(inventory, hasTable);
        boolean complete = ensure(state, output, state.stock.getOrDefault(output, 0) + additional, new HashSet<>());
        State report = complete ? state : bestFailure == null ? state : bestFailure;
        return new Plan(complete ? List.copyOf(state.steps) : List.of(), Map.copyOf(report.missing), complete);
    }
    private boolean ensure(State state, String item, int count, Set<String> parents) {
        if (state.stock.getOrDefault(item, 0) >= count) return true;
        if (--remaining < 0 || parents.size() >= 12 || parents.contains(item) || state.steps.size() >= 128) {
            fail(state, "planning_limit_or_cycle:" + item, count - state.stock.getOrDefault(item, 0)); return false;
        }
        Set<String> path = new HashSet<>(parents); path.add(item);
        List<Recipe> options = recipes.apply(item);
        if (options.isEmpty()) { fail(state, item, count - state.stock.getOrDefault(item, 0)); return false; }
        for (Recipe recipe : options.stream().limit(32).toList()) {
            State trial = new State(state);
            if (recipe.amount <= 0 || recipe.ingredients.isEmpty()) continue;
            if (recipe.table && !trial.table) {
                if (!ensure(trial, TABLE, 1, path)) continue;
                trial.stock.merge(TABLE, -1, Integer::sum);
                trial.steps.add(new Step("", TABLE, true)); trial.table = true;
            }
            int batches = (count - trial.stock.getOrDefault(item, 0) + recipe.amount - 1) / recipe.amount;
            boolean possible = batches <= 64 && assignBatches(trial, recipe, batches, 0, 0, path);
            if (possible && trial.stock.getOrDefault(item, 0) >= count) { state.accept(trial); return true; }
        }
        if (bestFailure == null) fail(state, "recipe_unresolved:" + item, count - state.stock.getOrDefault(item, 0));
        return false;
    }
    // Volver atrás en la asignación evita gastar el único ingrediente que otro slot exige.
    private boolean assignBatches(State state, Recipe recipe, int batches, int batch, int slot, Set<String> path) {
        if (--remaining < 0) { fail(state, "planning_limit:" + recipe.output, 1); return false; }
        if (batch >= batches) return true;
        if (slot >= recipe.ingredients.size()) {
            if (state.steps.size() >= 128) return false;
            State next = new State(state); next.stock.merge(recipe.output, recipe.amount, Integer::sum);
            next.steps.add(new Step(recipe.id, recipe.output, false));
            if (!assignBatches(next, recipe, batches, batch + 1, 0, path)) return false;
            state.accept(next); return true;
        }
        List<String> choices = new ArrayList<>(recipe.ingredients.get(slot));
        if (choices.isEmpty()) return assignBatches(state, recipe, batches, batch, slot + 1, path);
        choices.sort(Comparator.comparingInt(choice -> state.stock.getOrDefault(choice, 0) > 0 ? 0 : 1));
        for (String choice : choices.stream().distinct().limit(32).toList()) {
            State branch = new State(state);
            if (ensure(branch, choice, 1, path)) {
                branch.stock.merge(choice, -1, Integer::sum);
                if (assignBatches(branch, recipe, batches, batch, slot + 1, path)) { state.accept(branch); return true; }
            }
        }
        return false;
    }
    private void fail(State state, String item, int amount) {
        State failure = new State(state); failure.missing.merge(item, Math.max(1, amount), Integer::sum);
        if (bestFailure == null || failure.steps.size() > bestFailure.steps.size()) bestFailure = failure;
    }
}