"""Module to handle the user info request."""

import os
import glob
import logging
import re
from flask import Blueprint, request, jsonify, session
from custom_functions.database.user_db import (
    fetch_api_key,
    fetch_styled_username,
    fetch_username_by_api_key,
)

user_info_bp = Blueprint("user_info_bp", __name__)


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


@user_info_bp.route("/userinfo", methods=["POST"])
def user_info():
    """Handle the user info request."""
    username = session.get("username")
    if not username:
        try:
            headers = request.headers
            api_key = headers["Api-Key"]
            username = fetch_username_by_api_key(api_key)
        except Exception as e:
            logging.exception("Error retrieving username by API key, %s", {e})
            return jsonify({"message": "False"}), 400

    safe_username = sanitize_username(username)

    try:
        base_path = os.path.join(
            os.getcwd(), "configs", "CDMs", "users_uploaded", safe_username
        )
        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"))
        ]

        return jsonify(
            {
                "Username": username,
                "Widevine_Devices": wv_files,
                "Playready_Devices": pr_files,
                "API_Key": fetch_api_key(username),
                "Styled_Username": fetch_styled_username(username),
            }
        )
    except Exception as e:
        logging.exception("Error retrieving device files, %s", {e})
        return jsonify({"message": "False"}), 500
