Volver al índice

src/main/java/ar/com/companeros/social/ChatAudience.java

package ar.com.companeros.social;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.UUID;
import java.util.regex.Pattern;

/** Nombres completos evitan que todo el equipo responda a un pedido individual. */
public final class ChatAudience {
    private static final Pattern GROUP = Pattern.compile("(?iu)^\\s*[¡¿]?\\s*(?:(?:todos|todas|bots|equipo|muchachos|chicos|all|team)(?![\\p{L}\\p{N}_])|(?:mensaje\\s+)?(?:a|para)\\s+(?:todos|todas|(?:los|las)\\s+bots)(?![\\p{L}\\p{N}_]))");
    private static final Pattern COLLECTIVE = Pattern.compile("(?iu)(?<![\\p{L}\\p{N}_])(?:bots|ustedes|vosotros)(?![\\p{L}\\p{N}_])");
    private static final Pattern OTHERS = Pattern.compile("(?iu)(?<![\\p{L}\\p{N}_])(?:los|las)\\s+dem[aá]s(?![\\p{L}\\p{N}_])");
    private ChatAudience() { }
    public static Set<String> named(String text, Collection<String> names) {
        Set<String> selected = new LinkedHashSet<>();
        for (String name : names) {
            String expression = "(?<![\\p{L}\\p{N}_])" + Pattern.quote(name) + "(?![\\p{L}\\p{N}_])";
            var matcher = Pattern.compile(expression, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(text);
            while (matcher.find()) if (!resourceReference(text, name, matcher.start(), matcher.end())) { selected.add(name); break; }
        }
        // Un error corto y unívoco, como carobon, no convierte el pedido en una pregunta a todos.
        if (selected.isEmpty()) {
            var words = Pattern.compile("[\\p{L}\\p{N}_]+").matcher(text);
            while (words.find()) {
                String word = words.group();
                if (word.length() < 4) continue;
                var matches = names.stream().filter(name -> oneEdit(word.toLowerCase(java.util.Locale.ROOT), name.toLowerCase(java.util.Locale.ROOT))).toList();
                if (matches.size() == 1 && !resourceReference(text, matches.get(0), words.start(), words.end())) selected.add(matches.get(0));
            }
        }
        return Set.copyOf(selected);
    }
    // Carbon también es un material cuando se escribe sin tilde; un ingrediente no cambia el interlocutor.
    private static boolean resourceReference(String text, String name, int start, int end) {
        if (start > 0 && ":./".indexOf(text.charAt(start - 1)) >= 0) return true;
        if (start > 0 && text.charAt(start - 1) == '@') return false;
        if (!Set.of("carbon", "iron", "copper", "gold", "diamond", "coal", "redstone").contains(name.toLowerCase(java.util.Locale.ROOT))) return false;
        String token = text.substring(start, end);
        if (!token.equals(token.toLowerCase(java.util.Locale.ROOT))) return false;
        String prefix = text.substring(Math.max(0, start - 70), start);
        return Pattern.compile("(?iu)(?:con|de|del|sin|usa|usar|usando|quema|quemar|fundir|fundi|necesito|necesitamos|tengo|tienes|tenes|consigue|consegui|conseguir|busca|busca[r]?|minar|mina|pica|picar|recoge|recoger|llevo|dame|trae|traigo|gasta|gastar)\\s+(?:(?:el|un|algo|mas|poco|mucho|bloques?|mineral|lingotes?|de|\\d+)\\s+)*$").matcher(prefix).find();
    }
    public static boolean group(String text) {
        // Direcciones de destinatario, no verbos como "consiguieron" ni cualquier mención incidental.
        return text != null && (GROUP.matcher(text).find() || COLLECTIVE.matcher(text).find());
    }

    // Cada humano conserva su interlocutor hasta cambiarlo explícitamente; no hay vencimiento por reloj.
    public static final class ConversationRouting {
        private static final int MAX_HUMANS = 4096;
        private final Map<UUID, Set<String>> focus = new LinkedHashMap<>(16, .75f, true);

        public Set<String> route(UUID human, String text, Collection<String> availableNames) {
            if (human == null || text == null) return Set.of();
            Set<String> available = Set.copyOf(availableNames);
            Set<String> explicit = named(text, available);
            if (!explicit.isEmpty()) {
                focus.put(human, explicit);
                if (focus.size() > MAX_HUMANS) focus.remove(focus.keySet().iterator().next());
                return explicit;
            }
            Set<String> previous = focus.get(human);
            // Una referencia al grupo puede aparecer dentro de la frase, sin repetir nombres.
            // La conversación individual sobrevive al aviso colectivo y no se convierte en un coro.
            if (group(text)) return available;
            if (OTHERS.matcher(text).find()) {
                Set<String> others = new LinkedHashSet<>(available);
                if (previous != null) others.removeAll(previous);
                return Set.copyOf(others);
            }
            if (previous == null) return Set.of();
            Set<String> remaining = previous.stream().filter(available::contains)
                .collect(java.util.stream.Collectors.toUnmodifiableSet());
            if (remaining.isEmpty()) focus.remove(human);
            return remaining;
        }
    }
    private static boolean oneEdit(String a, String b) {
        if (Math.abs(a.length() - b.length()) > 1) return false;
        if (a.length() == b.length()) {
            int first = -1, second = -1;
            for (int i = 0; i < a.length(); i++) if (a.charAt(i) != b.charAt(i)) { if (first < 0) first = i; else if (second < 0) second = i; else return false; }
            return second < 0 || second == first + 1 && a.charAt(first) == b.charAt(second) && a.charAt(second) == b.charAt(first);
        }
        String longer = a.length() > b.length() ? a : b, shorter = a.length() > b.length() ? b : a;
        int i = 0, j = 0, skips = 0;
        while (i < longer.length() && j < shorter.length()) {
            if (longer.charAt(i) == shorter.charAt(j)) { i++; j++; }
            else { i++; if (++skips > 1) return false; }
        }
        return true;
    }
}