"""Intent-Erkennung fuer eingehende Chat-Nachrichten.

Regelwerk, kein LLM: bestimmt, WORUM es geht und OB geantwortet wird.
Alles Verdaechtige (GM, Bot-Vorwurf, Moderation) eskaliert sofort —
da antwortet grundsaetzlich kein Automatismus.
"""
import re

INTENT_GREETING = 'greeting'
INTENT_SMALLTALK = 'smalltalk'
INTENT_QUESTION_SPOT = 'question_spot'
INTENT_INVITE = 'invite'
INTENT_THANKS = 'thanks'
INTENT_BYE = 'bye'
INTENT_UNKNOWN = 'unknown'
INTENT_ESCALATE = 'escalate'

_ESCALATE_PATTERNS = (
    r'\bgm\b', r'gamemaster', r'tutor', r'\bcm\b', r'cipsoft',
    r'\bbot', r'\bmacro', r'cheat', r'hack', r'report',
    r'are you (afk|there|a bot)', r'bist du (afk|da|ein bot)',
)

_RULES = (
    (INTENT_GREETING, (
        r'\b(hi|hello|hey|hiya|yo|hallo|moin|servus|na)\b',
    )),
    (INTENT_SMALLTALK, (
        r'\b(sup|wassup|how are you|hows it going|was geht|wg)\b',
        r'\bwie geht',
    )),
    (INTENT_QUESTION_SPOT, (
        r'\b(this spot|spot free|hunting|hunt|level|exp|profit|waste|respawn)\b',
        r'\b(wie lange|how long|since when|seit wann)\b',
    )),
    (INTENT_INVITE, (
        r'\b(party|join|invite|team|th|quest|boss)\b',
    )),
    (INTENT_THANKS, (
        r'\b(thx|thanks|thank you|ty|danke)\b',
    )),
    (INTENT_BYE, (
        r'\b(bye|cya|see you|bb|tschüss|tschuess|ciao)\b',
    )),
)


def _matches(patterns, text):
    return any(re.search(pattern, text) for pattern in patterns)


def classify(message):
    """Liefert den Intent einer Nachricht."""
    text = ' '.join((message or '').lower().split())
    if not text:
        return INTENT_UNKNOWN
    if _matches(_ESCALATE_PATTERNS, text):
        return INTENT_ESCALATE
    for intent, patterns in _RULES:
        if _matches(patterns, text):
            return intent
    return INTENT_UNKNOWN


def should_reply(intent, sender_is_friend=False):
    """Regel: eskalieren nie, unbekannt nur Freunden antworten."""
    if intent == INTENT_ESCALATE:
        return False
    if intent == INTENT_UNKNOWN:
        return sender_is_friend
    return True
