ServerEvents.commandRegistry((event) => {
  const { commands: Commands, arguments: Arguments } = event;

  // /rsapi [<player>]
  function playerInventory(player) {
    const result = [];

    function pushItem(pos, item) {
      if (item.isEmpty()) return;
      let nbtData = {};
      try {
        if (item.nbt) {
          nbtData = JSON.parse(item.nbt.toString());
        }
      } catch (e) {
        nbtData = {};
      }
      result.push([pos, item.id, item.count, nbtData]);
    }

    // Main inventory (27 slots)
    player.inventory.items.forEach((item, i) => {
      pushItem(["inventory", i], item);
    });

    // Hotbar (9 slots)
    // player.inventory.hotbar.forEach((item, i) => {
    //  pushItem(["hotbar", i], item);
    // });

    console.log(result);
    return 1;

    // Armor
    // pushItem(["armor", "head"], player.headArmorItem);
    // pushItem(["armor", "chest"], player.chestArmorItem);
    // pushItem(["armor", "legs"], player.legsArmorItem);
    // pushItem(["armor", "feet"], player.feetArmorItem);

    // Offhand
    // pushItem(["offhand", 0], player.offHandItem);

    // Trinkets (if present)
    if (player.trinkets) {
      player.trinkets.groups.forEach((group) => {
        group.slots.forEach((slot) => {
          slot.items.forEach((item, index) => {
            pushItem(["trinkets", group.id, slot.id, index], item);
          });
        });
      });
    }

    console.log(JSON.stringify(result));

    return 1;
  }

  // /rsapi
  event.register(
    Commands.literal("rsapi")
      .requires((src) => src.hasPermission(2))
      .executes((ctx) => playerInventory(ctx.source.player))
      .then(
        // /rsapi [<player>]
        Commands.argument("target", Arguments.PLAYER.create(event)).executes(
          (ctx) => playerInventory(Arguments.PLAYER.getResult(ctx, "target")),
        ),
      ),
  );
});
