import base64
from typing import Optional

try:
    from Crypto.Cipher import DES
    _HAS_CRYPTO = True
except ImportError:
    try:
        from Cryptodome.Cipher import DES
        _HAS_CRYPTO = True
    except ImportError:
        _HAS_CRYPTO = False

_DES_KEY = b"38346591"

_QUALITY_MAP = {
    "12kbps": "_12",
    "48kbps": "_48",
    "96kbps": "_96",
    "160kbps": "_160",
    "320kbps": "_320",
}


def decrypt_media_url(encrypted_url: str) -> Optional[str]:
    if not _HAS_CRYPTO:
        raise ImportError(
            "pycryptodome is required for media URL decryption. "
            "Install it with: pip install pycryptodome"
        )
    if not encrypted_url:
        return None
    try:
        encrypted_bytes = base64.b64decode(encrypted_url)
        cipher = DES.new(_DES_KEY, DES.MODE_ECB)
        decrypted = cipher.decrypt(encrypted_bytes)
        decrypted_url = decrypted.decode("utf-8").rstrip("\x00\x01\x02\x03\x04\x05\x06\x07\x08")
        return decrypted_url
    except Exception:
        return None


def get_direct_url(encrypted_url: str, quality: str = "320kbps") -> Optional[str]:
    decrypted = decrypt_media_url(encrypted_url)
    if not decrypted:
        return None
    if quality in _QUALITY_MAP:
        decrypted = decrypted.replace("_96", _QUALITY_MAP[quality])
    return decrypted.replace("http:", "https:")


def get_all_quality_urls(encrypted_url: str) -> dict:
    decrypted = decrypt_media_url(encrypted_url)
    if not decrypted:
        return {}
    urls = {}
    for label, suffix in _QUALITY_MAP.items():
        url = decrypted.replace("_96", suffix).replace("http:", "https:")
        urls[label] = url
    return urls
