import logging
import re
# pyrefly: ignore [missing-import]
from telethon import events
from config import ADMIN_IDS, COMMAND_PREFIX
from database.manager import DatabaseManager

db = DatabaseManager()
logger = logging.getLogger("Middleware")

def is_admin(user_id):
    return user_id in ADMIN_IDS

async def permission_check(event):
    """
    Production-level permission checker.
    Filters: Bots, Non-commands/Non-UIDs, Banned users.
    """
    try:
        sender = await event.get_sender()
        if not sender or sender.bot:
            return False

        user_id = event.sender_id
        text = event.raw_text.strip()
        
        # Check if user is banned
        user = await db.get_user(user_id)
        if user and user.get('status') == 'banned':
            return False

        # 1. Allow if starts with Prefix
        if text.startswith(COMMAND_PREFIX):
            return True
        
        # 2. Allow if message is purely numeric (UID)
        if text.isdigit() and 5 <= len(text) <= 15:
            return True

        # 3. Allow if it's the "prefix" keyword (case insensitive)
        if text.lower() == "prefix":
            return True

        # 4. Allow if it is a math calculation
        if '**' not in text and re.match(r'^[\d\s\+\-\*\/\.]+$', text) and any(op in text for op in "+-*/") and any(c.isdigit() for c in text):
            return True

    except Exception as e:
        logger.error(f"Error in permission_check: {e}")
        
    return False

async def get_target_user(event):
    """Helper to get user_id from a reply safely."""
    try:
        if event.is_reply:
            reply = await event.get_reply_message()
            if reply:
                return reply.sender_id, reply
    except Exception as e:
        logger.error(f"Error in get_target_user: {e}")
    return None, None
