"""کمک‌توابع بررسی دسترسی صفحات — پورت‌شده از core/permissions.py دسکتاپ."""
from functools import wraps

from flask import abort
from flask_login import current_user

from config import PAGE_PERMISSIONS


def can_access(page_key: str) -> bool:
    if not current_user.is_authenticated:
        return False
    if current_user.is_admin():
        return True
    return page_key in current_user.permission_keys()


def require(page_key: str):
    def decorator(view_fn):
        @wraps(view_fn)
        def wrapped(*args, **kwargs):
            if not can_access(page_key):
                abort(403)
            return view_fn(*args, **kwargs)
        return wrapped
    return decorator


def allowed_page_keys() -> set:
    if current_user.is_authenticated and current_user.is_admin():
        return {key for key, _ in PAGE_PERMISSIONS}
    if current_user.is_authenticated:
        return current_user.permission_keys()
    return set()


def page_label(page_key: str) -> str:
    for key, label in PAGE_PERMISSIONS:
        if key == page_key:
            return label
    return page_key
