"""
Fernet encryption utilities for API key storage.

Keys are encrypted at rest using Fernet symmetric encryption.
The encryption key is derived from Django's SECRET_KEY.
"""
import base64
import hashlib

from cryptography.fernet import Fernet
from django.conf import settings


def _get_fernet_key():
    """
    Derive a Fernet-compatible key from Django's SECRET_KEY.

    :returns: Fernet instance ready for encrypt/decrypt operations.
    :rtype: cryptography.fernet.Fernet
    """
    secret = settings.SECRET_KEY.encode("utf-8")
    digest = hashlib.sha256(secret).digest()
    key = base64.urlsafe_b64encode(digest)
    return Fernet(key)


def encrypt_value(plaintext: str) -> str:
    """
    Encrypt a plaintext string.

    :param plaintext: The value to encrypt.
    :returns: Base64-encoded encrypted string.
    """
    f = _get_fernet_key()
    return f.encrypt(plaintext.encode("utf-8")).decode("utf-8")


def decrypt_value(encrypted: str) -> str:
    """
    Decrypt an encrypted string.

    :param encrypted: Base64-encoded encrypted value.
    :returns: Original plaintext string.
    """
    f = _get_fernet_key()
    return f.decrypt(encrypted.encode("utf-8")).decode("utf-8")
