# app/services/validator.py

import app.core.context as _ctx
from app.db import database as db

FALLBACK = (
    "I can only help with ZeroInfinity Technologies support questions. "
    "Can I help you with your account, a technical issue, or billing?"
)

FIXED_REPLIES = {
    "who am i": "You're a ZeroInfinity Technologies customer. I'm here to help you with your account, billing, or technical support needs.",
    "who are you": "I'm ZeroInfinity Technologies' virtual support assistant. I can help you with accounts, billing, technical issues, and general support questions.",
    "hello": "Hello! How can I assist you with ZeroInfinity Technologies today?",
    "hi": "Hi! How can I assist you with ZeroInfinity Technologies today?",
    "how are you": "I'm just a virtual assistant, but I'm here to help you with your ZeroInfinity Technologies questions!",
}

def _clean(text: str) -> str:
    return ''.join(c for c in text.lower().strip() if c not in '?!')

def validate(message: str) -> tuple[bool, str | None]:
    msg = _clean(message)
    print(f"[validator] cleaned='{msg}'")

    # Load live context from DB each call so admin changes take effect immediately
    try:
        context = db.get_context()
        allowed_topics  = context["allowed_topics"]
        blocked_phrases = context["blocked_phrases"]
    except Exception:
        # Fall back to module defaults if DB is unavailable
        allowed_topics  = _ctx.ALLOWED_TOPICS
        blocked_phrases = _ctx.BLOCKED_PHRASES

    # Exact match only — no more substring false positives
    if msg in FIXED_REPLIES:
        print(f"[validator] FIXED_REPLY exact match: '{msg}'")
        return False, FIXED_REPLIES[msg]

    for phrase in blocked_phrases:
        if phrase in msg:
            print(f"[validator] BLOCKED by phrase: '{phrase}'")
            return False, FALLBACK

    matched = [t for t in allowed_topics if t in msg]
    print(f"[validator] ALLOWED matches: {matched}")
    if not matched:
        print(f"[validator] REJECTED — no allowed topic found")
        return False, FALLBACK

    return True, None