"""Module to check if the user is allowed to use the device."""

import os
import glob
import re


def sanitize_username(username):
    """Sanitize the username."""
    return re.sub(r"[^a-zA-Z0-9_\-]", "_", username).lower()


def user_allowed_to_use_device(device, username):
    """Check if the user is allowed to use the device."""
    base_path = os.path.join(
        os.getcwd(), "configs", "CDMs", "users_uploaded", sanitize_username(username)
    )

    # Get filenames with extensions
    pr_files = [
        os.path.basename(f) for f in glob.glob(os.path.join(base_path, "PR", "*.prd"))
    ]
    wv_files = [
        os.path.basename(f) for f in glob.glob(os.path.join(base_path, "WV", "*.wvd"))
    ]

    # Combine all filenames
    all_files = pr_files + wv_files

    # Check if filename matches directly or by adding extensions
    possible_names = {device, f"{device}.prd", f"{device}.wvd"}

    return any(name in all_files for name in possible_names)
