ry08737
📎 1 file 12,208 chars
📄
pasted-code-1790864517558.txt
txt 372 lines
â–¶
# Minecraft Plugin Development Prompt: LevelsSMP Remake

You are an expert Minecraft plugin developer. Create a complete, fully functional Minecraft plugin called **LevelsSMP Remake**, inspired by the original LevelsSMP Remake plugin.

The plugin must be compatible with Paper and Spigot, use clean Java code, and include a fully customizable `config.yml`.

Do not create a basic prototype. Build a complete, working plugin with all the features listed below.

## 1. Multiplier System

Create an XP multiplier system where every player has their own multiplier.

* Default multiplier: 1.0x or a configurable value.
* Maximum multiplier: configurable.
* Minimum multiplier: configurable.
* Players can gain multipliers by killing other players.
* Players can lose multipliers when killed, according to configurable rules.
* Players can craft multipliers if the crafting system permits it.
* Players can withdraw multipliers.
* Players can claim dropped multipliers.
* Multipliers must persist after server restarts.
* All multiplier values must be saved separately for each player using their UUID.
* Support decimal multipliers, such as 1.5x, 2.5x and 3.75x.
* Prevent multipliers from becoming negative or exceeding the configured maximum.

## 2. Player Multiplier Inspection

This is one of the most important features.

Implement a fully functional command:

`/multiplier get `

It must retrieve the multiplier of the specified player, not the command sender.

Example:

`/multiplier get Steve`

Output:

`Steve's current XP multiplier: 2.5x`

Requirements:

* The command must work for both online and offline players, where stored data exists.
* It must use the target player's UUID to retrieve their multiplier.
* It must never accidentally display the command sender's multiplier.
* If the player has no saved data, show an appropriate message.
* Include tab completion for online players.
* Add configurable permission requirements.
* Include an optional console command for inspecting player multipliers.

Also implement:

* `/multiplier` — check your own multiplier.
* `/multiplier top` — display players with the highest multipliers.
* `/multiplier set  ` — set a player's multiplier.
* `/multiplier add  ` — add to a player's multiplier.
* `/multiplier remove  ` — remove from a player's multiplier.
* `/multiplier reset ` — reset a player's multiplier.
* `/multiplier reload` — reload the configuration.

Admin commands must have appropriate permissions.

## 3. Natural Death Multiplier Settings

Add a dedicated configuration section for multiplier loss on death.

The server owner must be able to turn natural death multiplier loss ON or OFF independently from PvP deaths.

Example configuration:

```yaml
death-settings:
  natural-death:
    enabled: true
    lose-multiplier: true
    loss-amount: 1.0
    drop-multiplier: false

  pvp-death:
    enabled: true
    lose-multiplier: true
    loss-amount: 1.0
    drop-multiplier: true

  environmental-death:
    enabled: true
    lose-multiplier: true
    loss-amount: 1.0
```

Behavior:

* When `natural-death.enabled` is false, natural deaths must not cause multiplier loss.
* When `natural-death.lose-multiplier` is false, players retain their multiplier after natural deaths.
* PvP deaths must follow the separate PvP settings.
* Environmental deaths must follow their own settings.
* Do not accidentally classify PvP deaths as natural deaths.
* Support deaths caused by mobs, falling, lava, drowning, explosions, and other causes.
* Make all loss amounts configurable.
* Make the system work correctly with Minecraft's death and respawn events.

## 4. Multiplier Gain and Loss

Implement the original-style SMP multiplier mechanics.

When a player kills another player:

* The killer receives the victim's multiplier or the configured amount.
* The victim loses the configured amount or the amount transferred.
* Respect the configured maximum multiplier.
* Send customizable messages to both players.

Include configurable options for:

* Multiplier gained per kill.
* Multiplier lost per death.
* Whether multipliers are transferred or independently added.
* Whether a player can gain a multiplier from killing the same player repeatedly.
* Kill cooldowns.
* World-based restrictions.
* Combat logging behavior.

## 5. Multiplier Crafting

Implement multiplier crafting.

* Allow crafting recipes for multiplier items.
* Make the recipes configurable.
* Make the crafting restrictions configurable.
* Prevent crafting multipliers when a player is at or above a configurable multiplier threshold.
* Allow the server owner to enable or disable crafting.
* Ensure that custom multiplier items cannot be forged or duplicated through unintended crafting mechanics.

Example setting:

```yaml
crafting:
  enabled: true
  max-multiplier-to-craft: 1.5
```

If the player's multiplier is 1.5x or above, show:

`You cannot craft multipliers at 1.5x or above!`

## 6. Multiplier Withdrawal and Claiming

Allow players to withdraw multiplier items.

Example command:

`/multiplier withdraw 1`

The player withdraws one multiplier item and their multiplier is reduced accordingly.

Allow players to claim multiplier items that have been dropped.

Requirements:

* Custom item identification using persistent data.
* Configurable item names, lore and material.
* Prevent item duplication.
* Validate items before allowing them to be claimed.
* Handle inventory-full situations.
* Make withdrawal amounts configurable.
* Include appropriate success and error messages.

## 7. Deathban and Revive Beacon System

Implement the original-style deathban mechanics.

Features:

* Players can become deathbanned under configurable conditions.
* Deathbanned players cannot continue playing normally.
* They receive a customizable kick message.
* Players can be revived using a Revive Beacon.
* Add commands to manage deathbans.
* Prevent unauthorized revivals.
* Save deathban information persistently.
* Support configurable deathban duration or permanent deathbans.

Commands:

* `/deathban list`
* `/deathban revive `
* `/deathban check `

Add configurable messages for deathbans and revivals.

## 8. XP Core System

Implement XP Cores.

* Players can claim XP Cores.
* XP Cores contain a configurable amount of XP.
* XP Core items must be uniquely identifiable.
* Prevent duplication and exploitation.
* Allow configurable XP amounts.
* Allow configurable item materials, names and lore.
* Make claiming messages customizable.

## 9. Configuration System

Create a detailed and well-organized `config.yml`.

All important mechanics and messages must be configurable without editing Java code.

Include sections for:

* General plugin settings.
* Multiplier limits.
* Multiplier gain and loss.
* Natural death settings.
* PvP death settings.
* Environmental death settings.
* Multiplier crafting.
* Multiplier withdrawal.
* Multiplier claiming.
* Deathbans.
* Revive Beacons.
* XP Cores.
* Commands.
* Permissions.
* Messages.
* Debugging.

Example message configuration:

```yaml
messages:
  multiplier-gained: "&aYou killed %player% and gained their multiplier! New multiplier: &l%multiplier%x"

  multiplier-lost: "&cYou died to %player% and lost a multiplier! New multiplier: &l%multiplier%x"

  multiplier-dropped: "&cYou died and dropped a multiplier! New multiplier: &l%multiplier%x"

  multiplier-claimed: "&aYou claimed a multiplier! New multiplier: &l%multiplier%x"

  cannot-craft: "&cYou cannot craft multipliers at 1.5x or above!"

  multiplier-check: "&aYour current XP multiplier: &l%multiplier%x"

  multiplier-get: "&a%player%'s current XP multiplier: &l%multiplier%x"

  deathbanned: "&4&lYou have been DEATHBANNED! Someone must revive you with a Revive Beacon."

  deathban-kick: "&cYou are deathbanned! Someone must revive you with a Revive Beacon."

  player-revived: "&aYou have revived %player%!"

  no-deathbanned-players: "&cThere are no deathbanned players to revive!"

  multiplier-withdrawn: "&aYou withdrew %amount% multiplier(s)! New multiplier: &l%multiplier%x"

  xp-core-claimed: "&aYou claimed an XP Core containing %xp% XP!"

  no-permission: "&cYou don't have permission to do that."

  player-not-found: "&cPlayer not found."

  invalid-amount: "&cPlease enter a valid amount."
```

Make sure every placeholder is correctly replaced. In particular, `%player%` in `multiplier-get` must refer to the target player, not the command sender.

Support color codes using `&` and optionally hexadecimal colors.

## 10. XP Multiplier Integration

Every XP gain event must be processed using the player's multiplier.

* Multiply earned XP by the player's multiplier.
* Apply the multiplier consistently to supported XP sources.
* Prevent recursive event handling.
* Avoid multiplying XP twice.
* Make XP multiplier functionality configurable.
* Ensure compatibility with other plugins where practical.

## 11. Permissions

Create a complete permission system.

Example:

```yaml
permissions:
  multiplier:
    check: "levelssmp.multiplier"
    get: "levelssmp.multiplier.get"
    admin: "levelssmp.multiplier.admin"
    withdraw: "levelssmp.multiplier.withdraw"
    claim: "levelssmp.multiplier.claim"

  deathban:
    revive: "levelssmp.deathban.revive"
    admin: "levelssmp.deathban.admin"
```

Register permissions properly in `plugin.yml`.

## 12. Data Storage

Use a persistent and reliable data system.

Prefer SQLite for larger servers, or YAML player files for smaller servers.

Requirements:

* Save multiplier values by UUID.
* Persist deathban status.
* Avoid losing data after crashes.
* Handle offline players.
* Avoid blocking the server's main thread with heavy database operations.
* Include migration support if the data format changes.
* Never rely exclusively on player names for identity.

## 13. Technical Requirements

* Use Java.
* Use Maven or Gradle.
* Target a clearly specified Minecraft version.
* Use the appropriate Paper API.
* Organize code into separate classes for commands, listeners, configuration, data storage, and game mechanics.
* Include `plugin.yml`.
* Include a default `config.yml`.
* Include a README with installation instructions and command documentation.
* Handle errors and invalid input safely.
* Include useful logging.
* Ensure all command executors and tab completers are registered.
* Do not use pseudocode or empty method stubs.
* Do not claim features are implemented if they are not.
* Build the plugin and test it before declaring it complete.

## 14. Testing Requirements

Test all major features, particularly:

1. `/multiplier` shows the command sender's multiplier.
2. `/multiplier get ` displays the target player's multiplier.
3. Offline players can be inspected using stored data.
4. Natural death multiplier loss can be enabled and disabled.
5. PvP deaths use their own configuration.
6. Multiplier values persist across restarts.
7. Multipliers cannot exceed the configured maximum.
8. Multiplier items cannot be duplicated.
9. Admin permissions are enforced.
10. Configuration reloads work correctly.
11. XP is not multiplied twice.
12. Deathban and revival functionality works.

If any test fails, fix the issue before delivering the plugin.

## 15. Final Deliverables

Provide:

* Complete Java source code.
* A compiled plugin `.jar`.
* A fully documented `config.yml`.
* `plugin.yml`.
* A README.
* Build instructions.
* A complete command and permission list.
* A test report.
* A short guide explaining how to enable or disable natural death multiplier loss.

**Important:** The plugin must be genuinely functional. Prioritize correct multiplier tracking, accurate player inspection, configurable death behavior, data safety, and a clean configuration system over unnecessary extra features.
Kodari AI
KodariOct 1 at 2:26 pm 2
LevelsSMPRemake
A comprehensive SMP progression plugin featuring a persistent XP multiplier system with per-player values stored by UUID, configurable gain/loss mechanics for PvP, natural, and environmental deaths, multiplier crafting and withdrawal, XP Core items, and a deathban system with Revive Beacons. Includes full command suite with offline player inspection, tab completion, configurable permissions, YAML-based storage, and a detailed config.yml with customizable messages, limits, and mechanics. Integrates XP multiplication into all XP gain events while preventing double application.
  1. Create the Java 17 Paper/Spigot project, plugin metadata, and configurable defaults.

  2. Implement UUID-based multiplier/deathban storage, commands, and unique multiplier/beacon/core items.

  3. Add crafting, XP, death, combat-log handling, and installation documentation.

Created the LevelsSMP Remake source project for Java 17 and Paper/Spigot 1.20.4, including configurable multiplier and death settings, UUID-based YAML persistence, commands, custom multiplier/XP core/revive beacon items, crafting, XP handling, deathbans, and a README.

The compiled .jar is not included, and I did not run a build or server integration tests. Build it with gradle build; the README lists the commands, permissions, and how to disable natural-death multiplier loss.

ry08737

so what now?

Kodari AI
KodariOct 3 at 6:41 am 1

Tell me what you want to build or fix next—describe the feature or bug, and I’ll take it from there.

ry08737

where can i get the plugin?

Kodari AI
KodariOct 3 at 6:42 am 1

The project includes the plugin’s source, but not a compiled .jar. Build it with JDK 17 and Gradle using gradle build; the jar will be at build/libs/LevelsSMPRemake-1.0.0.jar. Copy it into your server’s plugins folder and restart.

ry08737

can you add a actionbar that shows the multi you have

Kodari AI
KodariOct 3 at 7:06 am 1
  1. Add a configurable actionbar format and enable toggle.

  2. Refresh each online player’s current multiplier once per second, with legacy & colors.

Added an actionbar that shows each online player’s current multiplier, refreshed every second. Customize or disable it in config.yml under actionbar.

ry08737

also make it that from 0.1 to 1 multiplier you lose or gain 0.1 multi so 0.1-0.2-0.3-.4-.5-.6-.7-.8-.9-1 but from 1 you gain or lose 1.5 so 1-1.5-2-2.5

Kodari AI
KodariOct 3 at 7:11 am 1
  1. Deaths move down one rung: 0.1 steps through 1.0, then 0.5 steps above it.

  2. Kill gains move up the same ladder, with existing min/max limits and transfer eligibility preserved.

  3. Remove the obsolete fixed gain/loss amounts from the default config.

Multiplier gains and death losses now follow the ladder: 0.1 steps up to 1.0, then 0.5 steps above 1.0. So gaining from 1.0 gives 1.5; losing from 1.0 gives 0.9. Existing minimum and maximum limits still apply, and the fixed gain/loss amount options were removed from the default config.

ry08737

also make me able to withdraw as an op from other people and let me look at theyre multiplier with /multiplier check (name) also make it so if you have an exp core you cant craft with it cuz you can make a normal beacon with it so make it that it cant be put in a crafting table. also make the multiplier a paper and not a emerald

Kodari AI
KodariOct 3 at 7:34 am 1
  1. Add operator-only multiplier withdrawals for other players and /multiplier check <name>.

  2. Prevent the exp core from being used in crafting recipes.

  3. Change the multiplier item from emerald to paper.

  1. Added /multiplier check <name> and operator-only /multiplier withdraw <name> <amount>; withdrawn items go to the operator.

  2. Next: block XP cores from crafting recipes.

  3. Then: switch the multiplier item to paper.

  1. Added player checks and operator-only withdrawals from another player’s balance.

  2. XP cores are now rejected as crafting ingredients.

  3. Final: change the multiplier item material to paper.

  • Added /multiplier check <name> to view a player’s multiplier.

  • Operators can withdraw from another player with /multiplier withdraw <name> <amount>; the item goes to the operator.

  • XP cores can’t be used as crafting ingredients.

  • Multiplier items now use paper, including the configured and fallback material.

ry08737

also make the beacon right clickable and then it shows a screen of people that are death banned and youre able to choose one to undeathban. also add a config for the recipe and add the every time you spawn, you get 10 second immortality to players and mobs and i can change that in the config on/off and how much seconds

Kodari AI
KodariOct 3 at 3:13 pm 1
  1. Find the beacon interaction and death-ban system; add a GUI to choose and unban a death-banned player.

  2. Make the beacon recipe configurable.

  3. Add configurable spawn immunity for players and mobs.

  • Right-clicking a revive beacon opens a paginated list of death-banned players. Click a name to undeathban them; the beacon is consumed when revive-beacon.require-item is enabled.

  • The beacon recipe is configurable under revive-beacon.recipe in config.yml. Its default recipe uses gold ingots, a nether star, and obsidian.

  • Players receive damage immunity when they join or respawn, and mobs receive it when they spawn. Configure it with spawn-immunity.enabled and spawn-immunity.duration-seconds (default: 10).

ry08737

add a command /givemultiplier that gives a physical multiplier shard

Kodari AI
KodariOct 3 at 3:25 pm 1

The generation was stopped before any content could be produced.

ry08737

add a command /givemultiplier that gives a physical multiplier shard and make a data file that shows me all the multiliers that people have in the files

Kodari AI
KodariOct 3 at 3:30 pm 1
  1. Add /givemultiplier to grant a physical multiplier shard.

  2. Save each player’s multiplier in a readable data file.

  • Added operator-only /givemultiplier <player> <amount> to give an online player a physical multiplier shard.

  • The plugin now generates plugins/LevelsSMPRemake/multipliers.yml, listing saved player names and multipliers, and updates it when player data is saved.

ry08737

ok make the 0.1-0.2-0.3 again cuz it doesnt work so from 0-1 you gain 0.1, so 0.1 multi to 0.2 multi to 0.3 multi and make more ingredients for the multiplier recipe. and the beacon recipe.

Kodari AI
KodariOct 3 at 6:39 pm 1
  1. Fix multiplier gains/losses so values below 1.0 change by exactly 0.1.

  2. Add ingredients to the multiplier and beacon recipes.

  1. Multiplier progression now explicitly caps the sub-1.0 step at 1.0, preserving 0.1 gains/losses below it and 0.5 steps above.

  2. Checking how configurable recipes are registered before expanding their defaults.

Multiplier progression now uses 0.1 steps below 1.0, reaching 1.0 cleanly; above 1.0 it uses 0.5 steps.

Expanded default recipes:

  • Multiplier shard: diamonds, gold ingots, an emerald, and redstone.

  • Revive beacon: diamonds, an emerald, gold ingots, a nether star, and obsidian.

Both recipes remain configurable in config.yml.

ry08737

also add ancient debris and netherite ingot

Kodari AI
KodariOct 3 at 6:40 pm 1

Added ancient debris and a netherite ingot to both the multiplier shard and revive beacon recipes. The recipes remain configurable in config.yml.

ry08737

also make a config of what commands unopped players cant use so like a list of the levels command i can turn on or off if unopped players can see and use the command

Kodari AI
KodariOct 3 at 6:43 pm 1
  • Add per-command allow-non-op toggles for each Levels command.

  • Block disabled commands for non-OP players and hide them from the client command list.

Added configurable non-OP access for /multiplier, /deathban, /xpcore, and /givemultiplier. Disabled commands are blocked and hidden from command suggestions; OPs retain access.

Set each command’s allow-non-op value in config.yml. Multiplier and deathban are enabled by default; XP core and give-multiplier are disabled.

ry08737

wait also make if i turn off deathban, it also makes that every time you die with 0.1 multi you dont drop anything and the player that killed you doesnt gain anythnig. also put in config

Kodari AI
KodariOct 3 at 6:45 pm 1
  • When deathbans are disabled, protect players at or below a configurable multiplier threshold from multiplier loss/drop and prevent killer rewards.

  • Add the protection toggle and default 0.1 threshold to config.yml.

When deathbans.enabled: false, players at or below the configured threshold keep their multiplier when they die—no multiplier loss or shard drop, and their killer gets no multiplier reward.

Configure it under deathbans.minimum-multiplier-protection in config.yml; it’s enabled by default with a 0.1 threshold.

ry08737

also make if i configure the multiplier of somebody at the data ile, it also happens so if i change it to 1x it becomes 1x

Kodari AI
KodariOct 3 at 6:50 pm 1
  • Load multipliers.yml player values into the live data when the plugin starts.

  • Persist those values to players.yml so the configured multiplier is active and retained.

multipliers.yml now loads player multipliers on startup and applies them to the live data. For example, set players.<uuid>.multiplier: 1.0; on restart, that becomes the player’s multiplier and is saved to players.yml as well.

ry08737

make it so that a paper doesnt how a value so just if you withdraw it makes it normal like if you have 0.1 a multi just gives or reducde 0.1 multi and if you have 1 multi a multi give or reduce 0.5

Kodari AI
KodariOct 3 at 6:59 pm 1
  • Remove the displayed multiplier amount from physical multiplier paper.

  • Make redeeming it apply a dynamic step: 0.1 below 1.0, 0.5 from 1.0 onward; use the matching step when reducing.

Multiplier shards no longer show a value and apply a step based on the player’s current multiplier: +/−0.1 below 1.0, and +/−0.5 at 1.0 or higher. /multiplier withdraw now withdraws one step; admins can use /multiplier withdraw <player>. Death losses use the same step rules.

ry08737

ok so now if you withdraw you go from 1 to 0.5 to 0.4 to 0.3. fix this

Kodari AI
KodariOct 5 at 6:27 pm 1
  • Make each withdrawal remove 0.5 while the balance is at least 0.5; keep 0.1 withdrawals for balances below 0.5.

/multiplier withdraw now removes 0.5 at balances of 0.5 or higher, so 1.0 withdraws to 0.5, then 0.0. Below 0.5, withdrawals remove 0.1.

ry08737

make so that you dont go from 1 to 0.5 but from 1 to 0.9 to 0.8......

Kodari AI
KodariOct 5 at 6:28 pm 1

Set each withdrawal to remove a fixed 0.1 multiplier so 1.0 steps down through 0.9, 0.8, and onward.

/multiplier withdraw now always removes 0.1, so a 1.0 multiplier goes to 0.9, then 0.8, and so on.

ry08737

ok, so if you withdraw you go from 10 to 9.5 to 9 so you take off 0.5, but from 1 you withdraw 0.1 so from 1 to 0.9 to 0.8 to 0.7 to 0.6

Kodari AI
KodariOct 5 at 6:35 pm 1
  • Use a 0.5 withdrawal when the current multiplier is above 1.0.

  • Use a 0.1 withdrawal at 1.0 or below, subtracting and issuing the same amount.

Withdrawals now remove and issue 0.5 when the multiplier is above 1.0, and 0.1 at 1.0 or below. So 10 goes to 9.5, then 9; 1 goes to 0.9, then 0.8.

ry08737

ok i have a combatlog plugin, but it doesnt give a multiplier if you combatlog. so also add if you get punched you go in multiplier combat (with no actionbar) and if you leave in a certain amount of time in the combat, you drop a multilier and removes 1 multiplier that combatlogged. so it drops one from the player that combatlogged and drops a multi. also make this configurable in the config.

Kodari AI
KodariOct 5 at 6:38 pm 1
  • Inspect current combat/death handling and config structure.

  • Add configurable hit-triggered combat tracking with no actionbar.

  • On combat logout within the configured window, remove one multiplier step and drop one shard.

Combat logging now tags both players when either lands a hit. If either logs out within the timeout, they lose the configured multiplier amount and drop a shard; the other player can receive the kill reward. No combat actionbar is shown.

Configure it under combat-log in config.yml: enabled, tag-on-hit, combat-timeout-seconds, lose-multiplier, loss-amount, drop-multiplier, and reward-killer. The default loss is 1.0; the shard contains the amount actually removed, respecting the configured minimum multiplier.

ry08737

ok make it that every 10 levels you get you gain 1 heart

Kodari AI
KodariOct 5 at 6:57 pm 1
  • Set max health to 20 plus 2 health for every 10 levels.

  • Apply it on level changes and when players join so the bonus persists after reconnecting.

Players now gain 1 max heart (+2 health) for every 10 levels, applied when their level changes and refreshed when they join.

ry08737

ok, so if you die you go from 10 to 9.5 to 9 so you take away 0.5, but from 1 you die and take away 0.1 so from 1 to 0.9 to 0.8 to 0.7 to 0.6

Kodari AI
KodariOct 7 at 1:00 pm 1
  • Use a 0.5 death loss when the multiplier is above 1.0.

  • At 1.0 or below, use a 0.1 loss so 1.0 goes to 0.9, 0.8, and onward.

  • Keep the dropped shard equal to the amount actually removed.

Deaths now remove 0.5 when above 1.0, and 0.1 at 1.0 or below. So 10 → 9.5 → 9, while 1 → 0.9 → 0.8; any dropped shard matches the amount lost.

ry08737

ok only make if you kill somebody they drop multipleir not that you gain one, cuz now it drops multi and you gain one

Kodari AI
KodariOct 29 at 3:27 pm 1
  • Keep the victim’s multiplier loss and shard drop on death or combat logout.

  • Remove multiplier rewards to the killer in both cases.

Victims still lose multiplier and drop a shard when killed or combat-logging, but the killer no longer gains multiplier in either case.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
README.md
Code
14 2,130
src/main/java/com/levelssmp/remake/LevelsSMP.java
package com.levelssmp.remake;

import com.levelssmp.remake.command.DeathbanCommand;
import com.levelssmp.remake.command.GiveMultiplierCommand;
import com.levelssmp.remake.command.MultiplierCommand;
import com.levelssmp.remake.command.XPCoreCommand;
import com.levelssmp.remake.data.PlayerDataStore;
import com.levelssmp.remake.item.ItemFactory;
import com.levelssmp.remake.listener.CommandAccessListener;
import com.levelssmp.remake.listener.GameplayListener;
import com.cryptomorin.xseries.XMaterial;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.plugin.java.JavaPlugin;

import java.math.BigDecimal;

public final class LevelsSMP extends JavaPlugin {
    private PlayerDataStore dataStore;
    private ItemFactory itemFactory;
    private NamespacedKey itemTypeKey;
    private NamespacedKey itemTokenKey;
    private NamespacedKey itemValueKey;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        itemTypeKey = new NamespacedKey(this, "item_type");
        itemTokenKey = new NamespacedKey(this, "item_token");
        itemValueKey = new NamespacedKey(this, "item_value");
        dataStore = new PlayerDataStore(this);
        itemFactory = new ItemFactory(this, dataStore);
        registerCommands();
        Bukkit.getPluginManager().registerEvents(new GameplayListener(this, dataStore, itemFactory), this);
        Bukkit.getPluginManager().registerEvents(new CommandAccessListener(this), this);
        Bukkit.getScheduler().runTaskTimer(this, () -> {
            if (!getConfig().getBoolean("actionbar.enabled", true)) {
                return;
            }
            String format = getConfig().getString("actionbar.format", "&aMultiplier: &f%multiplier%x");
            for (Player player : Bukkit.getOnlinePlayers()) {
                String multiplier = BigDecimal.valueOf(dataStore.getMultiplier(player.getUniqueId()))
                        .stripTrailingZeros().toPlainString();
                player.sendActionBar(ChatColor.translateAlternateColorCodes('&',
                        format.replace("%multiplier%", multiplier)));
            }
        }, 0L, 20L);
        registerMultiplierRecipe();
        registerBeaconRecipe();
        getLogger().info("LevelsSMP Remake enabled.");
    }

    @Override
    public void onDisable() {
        if (dataStore != null) {
            dataStore.save();
        }
    }

    public void reloadPluginConfig() {
        reloadConfig();
        registerMultiplierRecipe();
        registerBeaconRecipe();
    }

    private void registerCommands() {
        MultiplierCommand multiplierCommand = new MultiplierCommand(this, dataStore, itemFactory);
        getCommand("multiplier").setExecutor(multiplierCommand);
        getCommand("multiplier").setTabCompleter(multiplierCommand);
        DeathbanCommand deathbanCommand = new DeathbanCommand(this, dataStore, itemFactory);
        getCommand("deathban").setExecutor(deathbanCommand);
        getCommand("deathban").setTabCompleter(deathbanCommand);
        XPCoreCommand xpCoreCommand = new XPCoreCommand(this, itemFactory);
        getCommand("xpcore").setExecutor(xpCoreCommand);
        getCommand("xpcore").setTabCompleter(xpCoreCommand);
        GiveMultiplierCommand giveMultiplierCommand = new GiveMultiplierCommand(this, itemFactory);
        getCommand("givemultiplier").setExecutor(giveMultiplierCommand);
        getCommand("givemultiplier").setTabCompleter(giveMultiplierCommand);
    }

    private void registerMultiplierRecipe() {
        NamespacedKey recipeKey = new NamespacedKey(this, "multiplier_shard");
        Bukkit.removeRecipe(recipeKey);
        if (!getConfig().getBoolean("crafting.enabled", true)) {
            return;
        }
        ItemStack result = itemFactory.createMultiplier(getConfig().getDouble("crafting.item-value", 0.5), "CRAFT_TEMPLATE");
        ShapedRecipe recipe = new ShapedRecipe(recipeKey, result);
        java.util.List<String> shape = getConfig().getStringList("crafting.recipe.shape");
        if (shape.isEmpty() || shape.size() > 3) {
            getLogger().warning("crafting.recipe.shape must contain 1 to 3 rows; multiplier recipe was not registered.");
            return;
        }
        recipe.shape(shape.toArray(new String[0]));
        org.bukkit.configuration.ConfigurationSection ingredients = getConfig().getConfigurationSection("crafting.recipe.ingredients");
        if (ingredients != null) {
            for (String symbol : ingredients.getKeys(false)) {
                XMaterial.matchXMaterial(ingredients.getString(symbol, "AIR"))
                        .map(XMaterial::parseMaterial)
                        .filter(material -> material != null)
                        .ifPresent(material -> recipe.setIngredient(symbol.charAt(0), material));
            }
        }
        try {
            Bukkit.addRecipe(recipe);
        } catch (IllegalArgumentException exception) {
            getLogger().warning("Invalid multiplier recipe configuration: " + exception.getMessage());
        }
    }

    private void registerBeaconRecipe() {
        NamespacedKey recipeKey = new NamespacedKey(this, "revive_beacon");
        Bukkit.removeRecipe(recipeKey);
        if (!getConfig().getBoolean("revive-beacon.recipe.enabled", true)) {
            return;
        }
        ItemStack result = itemFactory.createBeaconCraftTemplate();
        if (result == null) {
            return;
        }
        ShapedRecipe recipe = new ShapedRecipe(recipeKey, result);
        java.util.List<String> shape = getConfig().getStringList("revive-beacon.recipe.shape");
        if (shape.isEmpty()) {
            shape = java.util.List.of("GGG", "GNG", "GOG");
        }
        if (shape.size() > 3) {
            getLogger().warning("revive-beacon.recipe.shape must contain 1 to 3 rows; revive beacon recipe was not registered.");
            return;
        }
        recipe.shape(shape.toArray(new String[0]));
        org.bukkit.configuration.ConfigurationSection ingredients = getConfig().getConfigurationSection("revive-beacon.recipe.ingredients");
        java.util.Set<Character> symbols = new java.util.LinkedHashSet<>();
        for (String row : shape) {
            for (char symbol : row.toCharArray()) {
                if (symbol != ' ') {
                    symbols.add(symbol);
                }
            }
        }
        for (char symbol : symbols) {
            String symbolName = Character.toString(symbol);
            String materialName = ingredients == null ? null : ingredients.getString(symbolName);
            if (materialName == null) {
                materialName = switch (symbol) {
                    case 'G' -> "GOLD_INGOT";
                    case 'N' -> "NETHER_STAR";
                    case 'O' -> "OBSIDIAN";
                    default -> null;
                };
            }
            org.bukkit.Material material = materialName == null ? null
                    : XMaterial.matchXMaterial(materialName).map(XMaterial::parseMaterial).orElse(null);
            if (material == null) {
                getLogger().warning("Missing or invalid material for revive beacon recipe symbol: " + symbolName);
                return;
            }
            recipe.setIngredient(symbol, material);
        }
        try {
            Bukkit.addRecipe(recipe);
        } catch (IllegalArgumentException exception) {
            getLogger().warning("Invalid revive beacon recipe configuration: " + exception.getMessage());
        }
    }

    public PlayerDataStore getDataStore() {
        return dataStore;
    }

    public ItemFactory getItemFactory() {
        return itemFactory;
    }

    public NamespacedKey getItemTypeKey() {
        return itemTypeKey;
    }

    public NamespacedKey getItemTokenKey() {
        return itemTokenKey;
    }

    public NamespacedKey getItemValueKey() {
        return itemValueKey;
    }
}