Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/events/FishingEventBridge.java
T
2026-09-26 21:09:22 -04:00

292 lines
17 KiB
Java

package games.dmg.fantasystick.events;
import games.dmg.fantasystick.adventure.AdventureQuestState;
import games.dmg.fantasystick.adventure.FishingState;
import games.dmg.fantasystick.session.EquipmentSessions;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Clock;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Function;
import org.bukkit.Location;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/** Acknowledged fishing outcomes and native fishing attempts, independent of chat feedback. */
public final class FishingEventBridge implements AutoCloseable {
public record Actor(String kind, EventInput.Context context) { }
private static final Set<String> DURABLE = Set.of("adventure.site.registered", "adventure.site.updated", "adventure.site.mode_changed",
"adventure.quest.accepted", "config.changed", "fishing.catch_resolved",
"adventure.items_submitted", "adventure.reward_claimed",
"adventure.trophy_earned", "adventure.trophy_redeemed", "combat.reward_resolved",
"dungeon.reward_changed", "dungeon.completed");
private final Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink;
private final Clock clock;
private final EquipmentSessions sessions;
private final FeatureEventOutbox outbox;
public FishingEventBridge(Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink, Clock clock,
Path data, EquipmentSessions sessions, Consumer<Throwable> failures) {
this.sink = Objects.requireNonNull(sink);
this.clock = Objects.requireNonNull(clock);
this.sessions = Objects.requireNonNull(sessions);
outbox = new FeatureEventOutbox(data, "fishing-event-intents", DURABLE, sink, failures);
}
public Actor actor(CommandSender sender) {
try {
if (!(sender instanceof Player player))
return new Actor(sender instanceof BlockCommandSender ? "command_block" : "console", null);
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
var record = active == null ? null : sessions.currentRecord(active).orElse(null);
return new Actor("player", new EventInput.Context(player.getUniqueId(), player.getName(),
record == null ? null : record.id(), record == null ? null : record.name(),
record == null ? null : active.session(), safeLocation(player)));
} catch (RuntimeException unavailable) { return null; }
}
public void site(String type, UUID operation, Actor actor, AdventureQuestState.Site site,
Map<String, Object> changed) {
if (actor == null || site == null || site.fishing() == null) return;
var terms = site.fishing();
var values = new LinkedHashMap<String, Object>();
values.put("actor_kind", actor.kind());
values.put("site_kind", "fishing");
values.put("site_id", site.id().toString());
values.put("site_name", site.name());
values.put("item_id", terms.itemId().toString());
values.put("item_name", terms.itemName());
values.put("required", terms.required().toString());
values.put("chance_percent", terms.chancePercent().toPlainString());
values.put("reward_xp", terms.rewardXp().toString());
values.put("reward_coins", terms.rewardCoins().toString());
values.put("radius", terms.radius());
values.put("mode", site.participationMode().value());
values.put("world_id", site.world().toString());
values.put("x", site.x()); values.put("y", site.y()); values.put("z", site.z());
values.put("changed", changed);
durable(type, operation, actor, values);
}
public void accepted(UUID operation, Actor actor, AdventureQuestState.Quest quest) {
if (actor == null || quest.fishing() == null) return;
var terms = quest.fishing();
var values = new LinkedHashMap<String, Object>();
values.put("site_kind", "fishing"); values.put("quest_id", quest.id().toString());
values.put("catalog_id", quest.catalog().toString()); values.put("site_id", quest.site().toString());
values.put("unit_kind", quest.unitType().name().toLowerCase(java.util.Locale.ROOT));
values.put("unit_id", quest.unit().toString());
values.put("item_id", terms.itemId().toString()); values.put("item_name", terms.itemName());
values.put("required", terms.required().toString());
values.put("chance_percent", terms.chancePercent().toPlainString());
values.put("radius", terms.radius());
values.put("reward_xp", terms.rewardXp().toString());
values.put("reward_coins", terms.rewardCoins().toString());
values.put("roster", quest.snapshot().stream().sorted().map(UUID::toString).toList());
durable("adventure.quest.accepted", operation, actor, values);
}
public void configRead(Actor actor, String key, String effective, String defaultValue) {
if (actor == null) return;
var data = config(actor, key, defaultValue);
data.put("effective", effective); data.put("outcome", "acknowledged_read");
transientEvent("config.read", UUID.randomUUID(), actor, data);
}
public void configChanged(Actor actor, UUID operation, String key, String before,
String effective, String defaultValue) {
if (actor == null) return;
var data = config(actor, key, defaultValue);
data.put("before", before); data.put("after", effective); data.put("effective", effective);
data.put("outcome", "acknowledged_future_casts");
durable("config.changed", operation, actor, data);
}
private static LinkedHashMap<String, Object> config(Actor actor, String key, String defaultValue) {
var data = new LinkedHashMap<String, Object>();
data.put("actor_kind", actor.kind()); data.put("key", key); data.put("default", defaultValue);
data.put("application_scope", "future_fishing_casts");
if (actor.context() == null) data.put("location_status", "not_applicable");
else if (actor.context().location() == null) data.put("location_status", "unavailable");
return data;
}
public Actor actorFromCatch(FishingState.Catch catchReceipt) {
var audit = catchReceipt.audit();
try {
return new Actor("player", new EventInput.Context(UUID.fromString(audit.get("player_id")),
audit.get("player_name"), catchReceipt.character(), audit.get("character_name"),
UUID.fromString(audit.get("session_id")), null));
} catch (RuntimeException unavailable) { return new Actor("system", null); }
}
/** Reconstruct a combat-trophy outcome solely from the saved receipt, including after a prepared retry. */
public void trophyEarned(FishingState.Trophy receipt) {
if ((receipt.type() != FishingState.TrophyType.CHAMPION
&& receipt.type() != FishingState.TrophyType.CAMP
&& receipt.type() != FishingState.TrophyType.DUNGEON)
|| receipt.phase() != FishingState.TrophyPhase.EARNED) return;
var audit = receipt.audit();
var evidence = new LinkedHashMap<String, Object>();
evidence.put("receipt_id", receipt.id().toString());
evidence.put("trophy_type", receipt.type().name().toLowerCase(java.util.Locale.ROOT) + "_trophy");
evidence.put("trophy_name", receipt.name());
evidence.put("source_name", receipt.origin());
evidence.put("carrier_character_id", receipt.carrier().toString());
evidence.put("carrier_is_beneficiary", receipt.rewards().containsKey(receipt.carrier()));
evidence.put("quest_id", receipt.quest().toString());
evidence.put("catalog_id", receipt.catalog().toString());
evidence.put("site_id", receipt.site().toString());
evidence.put("encounter_id", receipt.source().toString());
if (receipt.type() == FishingState.TrophyType.CHAMPION) {
evidence.put("champion_id", audit.getOrDefault("champion_id", "unavailable_legacy_capture"));
evidence.put("defeat_location", savedDefeatLocation(audit));
evidence.put("defeated_at", audit.getOrDefault("defeated_at", "unavailable_legacy_capture"));
} else if (receipt.type() == FishingState.TrophyType.CAMP) {
evidence.put("final_enemy_id", audit.getOrDefault("final_enemy_id", "unavailable_legacy_capture"));
evidence.put("clear_location", savedDefeatLocation(audit));
evidence.put("cleared_at", audit.getOrDefault("defeated_at", "unavailable_legacy_capture"));
evidence.put("arena", savedArena(audit));
} else {
evidence.put("boss_id", audit.getOrDefault("boss_id", "unavailable_legacy_capture"));
evidence.put("room_id", audit.getOrDefault("room_id", "unavailable_legacy_capture"));
evidence.put("boss_death_location", savedDefeatLocation(audit));
evidence.put("completed_at", audit.getOrDefault("defeated_at", "unavailable_legacy_capture"));
}
evidence.put("unit_kind", audit.getOrDefault("unit_kind", "unavailable_legacy_capture"));
evidence.put("unit_id", audit.getOrDefault("unit_id", "unavailable_legacy_capture"));
var roster = audit.get("accepted_roster");
evidence.put("accepted_roster", roster == null || roster.isEmpty()
? List.of() : List.of(roster.split(",")));
evidence.put("accepted_roster_status", roster == null ? "unavailable_legacy_capture" : "captured");
evidence.put("reward_xp_pool", receipt.total().xp().toString());
evidence.put("reward_coin_pool", receipt.total().coins().toString());
evidence.put("phase", "earned");
evidence.put("receipt_revision", Integer.toString(receipt.revision()));
var beneficiaries = new java.util.ArrayList<Map<String, String>>();
receipt.rewards().entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {
var share = new LinkedHashMap<String, String>();
share.put("character_id", entry.getKey().toString());
share.put("allocated_xp", entry.getValue().xp().toString());
share.put("allocated_coins", entry.getValue().coins().toString());
share.put("allocation_status", entry.getValue().xp().signum() == 0
&& entry.getValue().coins().signum() == 0 ? "zero_share_completion" : "positive");
beneficiaries.add(share);
});
evidence.put("beneficiaries", beneficiaries);
durable("adventure.trophy_earned", receipt.id(), new Actor("system", null), evidence);
}
public static Map<String, Object> savedArena(Map<String, String> audit) {
try {
var shape = audit.get("arena_shape");
int x = Integer.parseInt(audit.get("arena_x_blocks"));
int z = Integer.parseInt(audit.get("arena_z_blocks"));
var expected = "circle".equals(shape)
? games.dmg.fantasystick.adventure.AdventureQuestState.Arena.circle(x)
: "rectangle".equals(shape)
? games.dmg.fantasystick.adventure.AdventureQuestState.Arena.rectangle(x, z)
: null;
if (expected == null || expected.zBlocks() != z) return Map.of("status", "unavailable");
return Map.of("shape", shape, "x_blocks", x, "z_blocks", z);
} catch (RuntimeException unavailable) { return Map.of("status", "unavailable"); }
}
public static Map<String, Object> savedDefeatLocation(Map<String, String> audit) {
try {
if (!audit.containsKey("defeat_world_id")) return Map.of("status", "unavailable");
var world = UUID.fromString(audit.get("defeat_world_id"));
double x = Double.parseDouble(audit.get("defeat_x"));
double y = Double.parseDouble(audit.get("defeat_y"));
double z = Double.parseDouble(audit.get("defeat_z"));
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z))
return Map.of("status", "unavailable");
return Map.of("world_id", world.toString(),
"world_name", audit.getOrDefault("defeat_world_name", "unavailable"),
"x", x, "y", y, "z", z);
} catch (RuntimeException unavailable) { return Map.of("status", "unavailable"); }
}
public void durable(String type, UUID operation, Actor actor, Map<String, Object> data) {
if (actor == null) return;
try {
String primary = data.get("beneficiaries") instanceof List<?> ? "beneficiaries"
: data.get("sources") instanceof List<?> ? "sources"
: data.get("roster") instanceof List<?> ? "roster" : null;
String secondary = data.get("accepted_roster") instanceof List<?> roster && !roster.isEmpty()
? "accepted_roster" : null;
if (primary == null) { primary = secondary; secondary = null; }
if ((primary == null || ((List<?>)data.get(primary)).size() <= 20)
&& (secondary == null || ((List<?>)data.get(secondary)).size() <= 20)) {
outbox.accepted(input(type, operation, actor, data));
return;
}
var first = (List<?>)data.get(primary);
int firstParts = Math.max(1, (first.size() + 19) / 20);
int secondParts = secondary == null ? 0 : (((List<?>)data.get(secondary)).size() + 19) / 20;
int total = firstParts + secondParts;
for (int index = 0; index < total; index++) {
String collection = index < firstParts ? primary : secondary;
int collectionPart = index < firstParts ? index : index - firstParts;
var entries = (List<?>)data.get(collection);
int from = collectionPart * 20, to = Math.min(from + 20, entries.size());
var part = new LinkedHashMap<String, Object>(data);
for (var key : List.of("beneficiaries", "sources", "roster", "accepted_roster"))
if (data.get(key) instanceof List<?>) part.put(key, List.of());
part.put(collection, entries.subList(from, to));
if (collection.equals("beneficiaries") && data.get("roster") instanceof List<?> roster
&& roster.size() == entries.size()) part.put("roster", roster.subList(from, to));
part.put("linked_collection", collection);
part.put("collection_total", entries.size());
part.put("collection_part_index", collectionPart);
part.put("part_index", index);
part.put("part_count", total);
outbox.accepted(input(type, operation, actor, part, index));
}
} catch (RuntimeException ignored) { /* Audit availability cannot change acknowledged fishing. */ }
}
public void transientEvent(String type, UUID operation, Actor actor, Map<String, Object> data) {
if (actor == null) return;
try { sink.apply(input(type, operation, actor, data)); }
catch (RuntimeException ignored) { /* Observation cannot change native fishing. */ }
}
private EventInput input(String type, UUID operation, Actor actor, Map<String, Object> data) {
return input(type, operation, actor, data, -1);
}
private EventInput input(String type, UUID operation, Actor actor, Map<String, Object> data, int part) {
var values = new LinkedHashMap<String, Object>(data);
values.put("operation_id", operation.toString());
var identity = "fantasystick:fishing:" + operation + ':' + type + (part < 0 ? "" : ":part:" + part);
return new EventInput(UUID.nameUUIDFromBytes(identity.getBytes(StandardCharsets.UTF_8)), operation,
clock.instant(), type, actor.context(), values);
}
private EventInput.Location safeLocation(Player player) {
try { return location(player.getLocation()); }
catch (RuntimeException unavailable) { return null; }
}
private EventInput.Location location(Location value) {
if (value == null || value.getWorld() == null) return null;
var world = value.getWorld();
if (world.getName() == null) return null;
return new EventInput.Location(world.getUID(), world.getName(), value.getX(), value.getY(), value.getZ(),
clock.instant(), "exact");
}
public void replay() { outbox.replay(); }
public CompletionStage<Void> drained() { return outbox.drained(); }
@Override public void close() { outbox.close(); }
}