# scope_guard.py: keep a support chatbot on topic and on budget. Runs before (and after) the expensive model.
import re, time
from collections import defaultdict, deque

MAX_OUT_TOKENS = 300      # cap 1: every reply is short
PER_SESSION = 20          # cap 2: messages per chat session
PER_IP_PER_MIN = 10       # cap 3: messages per IP per minute
CODE = re.compile(r"```|\b(def|leetcode|python|javascript|typescript|sql|regex|algorithm|linked list|binary tree"
                  r"|coding|compile|debug)\b|\b(write|fix|give me) (a |the |some |me )?(code|script|function|program)", re.I)
REFUSAL = "I can only help with your order, the menu, delivery and refunds."

_ip_hits, _session_turns = defaultdict(deque), defaultdict(int)

def check_in(message, ip, session, classify):
    """Return None to pass, or (http_status, reason) to refuse before the model is called."""
    now, hits = time.time(), _ip_hits[ip]
    while hits and now - hits[0] > 60:
        hits.popleft()
    if len(hits) >= PER_IP_PER_MIN:
        return 429, "rate limit: ip"
    hits.append(now)
    _session_turns[session] += 1
    if _session_turns[session] > PER_SESSION:
        return 429, "rate limit: session"
    if CODE.search(message):
        return 403, "off topic: code"            # free check: no model call at all
    if not classify(message):                    # cheap check: a small model answers yes/no
        return 403, "off topic: classifier"
    return None

def check_out(reply, n_tokens):
    """The signals to alert on: code or a long answer in a 'support' chat."""
    signals = [s for s, hit in (("code block", "```" in reply or bool(CODE.search(reply))),
                                ("long reply", n_tokens >= MAX_OUT_TOKENS)) if hit]
    return signals
