package ar.com.companeros.social; import java.text.Normalizer; import java.util.*; /** Historial breve de envíos reales; no depende del modelo ni de servicios externos. */ public final class ChatRepeatGuard { private static final long WINDOW_TICKS = 1800; private record Key(UUID sender, String channel, String recipient) { } private record Sent(long tick, String normalized, Set words) { } private final Map> history = new LinkedHashMap<>(); private static final Set STOP = Set.of("el","la","los","las","de","en","un","una","para","por","con","y","a","que","si","me","te","se","mi","tu","sus","su"); // Comparar texto y contenido: pequeños cambios de puntuación no convierten una repetición en novedad. public boolean duplicate(UUID sender, String channel, String recipient, String text, long tick) { var sent = history.get(new Key(sender, channel, recipient.toLowerCase(Locale.ROOT))); if (sent == null) return false; String normalized = normalize(text); Set words = words(normalized); sent.removeIf(previous -> tick < previous.tick() || tick - previous.tick() >= WINDOW_TICKS); for (Sent previous : sent) { if (normalized.equals(previous.normalized())) return true; // Coordenadas, cantidades y niveles distintos sí cambian el mensaje. if (!numbers(normalized).equals(numbers(previous.normalized()))) continue; if (words.size() < 4 || previous.words().size() < 4) continue; Set union = new HashSet<>(words); union.addAll(previous.words()); Set common = new HashSet<>(words); common.retainAll(previous.words()); if ((double) common.size() / union.size() >= .8) return true; } return false; } // Sólo un envío confirmado entra al historial. Rechazos y cooldowns no simulan mensajes enviados. public void record(UUID sender, String channel, String recipient, String text, long tick) { Key key = new Key(sender, channel, recipient.toLowerCase(Locale.ROOT)); if (!history.containsKey(key) && history.size() >= 1024) history.remove(history.keySet().iterator().next()); var sent = history.computeIfAbsent(key, ignored -> new ArrayDeque<>()); String normalized = normalize(text); sent.addLast(new Sent(tick, normalized, words(normalized))); while (sent.size() > 8) sent.removeFirst(); } private static String normalize(String text) { return Normalizer.normalize(text, Normalizer.Form.NFKC).toLowerCase(Locale.ROOT) .replaceAll("[^\\p{L}\\p{N}+-]+", " ").strip(); } private static Set words(String text) { Set words = new HashSet<>(Arrays.asList(text.split(" +"))); words.removeAll(STOP); return Set.copyOf(words); } private static List numbers(String text) { return java.util.regex.Pattern.compile("[+-]?\\d+").matcher(text).results().map(java.util.regex.MatchResult::group).toList(); } }