package com.example.duneess; import java.util.*; import java.util.function.Consumer; import java.sql.Connection; import java.lang.reflect.InvocationTargetException; import org.bukkit.*; import org.bukkit.command.*; import org.bukkit.entity.Player; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.Damageable; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.persistence.PersistentDataType; /** Staff conveniences using current native recipes and the shared inventory checkpoint. */ public final class StaffItemTools implements CommandExecutor { private final JavaPlugin plugin; public static void start(JavaPlugin plugin){var tools=new StaffItemTools(plugin);for(String name:List.of("condense","fix"))Objects.requireNonNull(plugin.getCommand(name)).setExecutor(tools);} private StaffItemTools(JavaPlugin plugin){this.plugin=plugin;} private record Compression(ItemStack result,int cost){} private static List ingredients(Recipe recipe){ if(recipe instanceof ShapedRecipe r){String[] rows=r.getShape();if(rows.length!=2&&rows.length!=3||Arrays.stream(rows).anyMatch(row->row.length()!=rows.length||row.contains(" ")))return List.of();var list=new ArrayList();for(String row:rows)for(char c:row.toCharArray())list.add(r.getChoiceMap().get(c));return list;} if(recipe instanceof ShapelessRecipe r)return r.getChoiceList();return List.of(); } private static boolean matches(RecipeChoice choice,ItemStack stack){return choice!=null&&choice.test(stack);} private Compression compression(ItemStack item)throws Exception{ var data=item.getItemMeta().getPersistentDataContainer();String custom=data.get(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING),legacy=data.get(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING); var jarvis=Bukkit.getPluginManager().getPlugin("JarvisTranslator"); if("spice".equals(legacy)||"spice".equals(custom)||"smuggled_spice".equals(custom)){var result=(ItemStack)jarvis.getClass().getMethod("compressedSpice",ItemStack.class).invoke(jarvis,item);return result==null?null:new Compression(result,9);} if(custom!=null||legacy!=null||data.has(new NamespacedKey("dunerealms","preview_only")))return null; var all=new ArrayList();Bukkit.recipeIterator().forEachRemaining(all::add); for(int cost:new int[]{9,4})for(var recipe:all){ if(!(recipe instanceof Keyed keyed)||!keyed.getKey().getNamespace().equals("minecraft"))continue; var inputs=ingredients(recipe);var result=recipe.getResult(); if(inputs.size()!=cost||result.getAmount()!=1||result.getType()==item.getType()||inputs.stream().anyMatch(c->!matches(c,item)))continue; // Only reversible storage recipes: never silently turn wood into workbenches. boolean reverse=all.stream().anyMatch(r->{var parts=ingredients(r);return parts.size()==1&&matches(parts.getFirst(),result)&&r.getResult().getType()==item.getType()&&r.getResult().getAmount()==cost;}); if(reverse){var output=result.clone();if(jarvis!=null)jarvis.getClass().getMethod("markCreatedItem",ItemStack.class).invoke(jarvis,output);return new Compression(output,cost);} } return null; } private int condense(Player p)throws Exception{ var inventory=p.getInventory();var contents=inventory.getStorageContents();var seen=new ArrayList();int blocks=0; for(var sample:contents){if(sample==null||sample.isEmpty()||seen.stream().anyMatch(i->i.isSimilar(sample)))continue;seen.add(sample.clone());var rule=compression(sample);if(rule==null)continue; int count=Arrays.stream(contents).filter(i->i!=null&&i.isSimilar(sample)).mapToInt(ItemStack::getAmount).sum(),made=count/rule.cost();if(made==0)continue; var temporary=Bukkit.createInventory(null,36);temporary.setContents(Arrays.stream(contents).map(i->i==null?null:i.clone()).toArray(ItemStack[]::new));int remaining=made*rule.cost(); for(int slot=0;slot<36&&remaining>0;slot++){var item=temporary.getItem(slot);if(item==null||!item.isSimilar(sample))continue;int take=Math.min(item.getAmount(),remaining);item.setAmount(item.getAmount()-take);temporary.setItem(slot,item.isEmpty()?null:item);remaining-=take;} var output=rule.result().clone();output.setAmount(made);if(!temporary.addItem(output).isEmpty())continue; contents=temporary.getContents();blocks+=made; } inventory.setStorageContents(contents);return blocks; } private static int repair(Player p){int count=0;for(int slot=0;slot0){damage.setDamage(0);item.setItemMeta(meta);p.getInventory().setItem(slot,item);count++;}}return count;} @Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args){ if(!(sender instanceof Player p))return true;if(!p.hasPermission("dune.admin")){p.sendMessage("This command is for staff.");return true;}if(args.length!=0){p.sendMessage("/"+command.getName());return true;} try{var core=Bukkit.getPluginManager().getPlugin("DuneCore");if(core==null||!core.isEnabled())throw new IllegalStateException("Shared inventory unavailable. Nothing changed.");int[] count={0};Consumer action=connection->{try{count[0]=command.getName().equals("fix")?repair(p):condense(p);}catch(Exception e){throw new java.util.concurrent.CompletionException(e);}};core.getClass().getMethod("transactNetworkInventory",Player.class,Consumer.class).invoke(core,p,action);p.sendMessage(command.getName().equals("fix")?"Repaired "+count[0]+" items.":"Created "+count[0]+" condensed items.");} catch(Exception e){Throwable cause=e instanceof InvocationTargetException?e.getCause():e;plugin.getLogger().warning("Staff inventory operation failed: "+cause.getClass().getSimpleName());p.sendMessage("Inventory operation could not be confirmed. Reopen your inventory before retrying.");} return true; } }