import base64
import hashlib
from cryptography.fernet import Fernet
from app.config import settings


def _get_fernet() -> Fernet:
    """
    Derive a valid 32-byte Fernet key from the configured ENCRYPTION_KEY string
    using SHA-256, then base64url-encode it.  This works with any string key.
    """
    key_bytes = hashlib.sha256(settings.ENCRYPTION_KEY.encode("utf-8")).digest()
    b64_key = base64.urlsafe_b64encode(key_bytes)   # exactly 44 chars, Fernet-compatible
    return Fernet(b64_key)


def encrypt_value(plain_text: str) -> str:
    """Encrypt a string and return a URL-safe base-64 token string."""
    if not plain_text:
        return ""
    f = _get_fernet()
    return f.encrypt(plain_text.encode("utf-8")).decode("utf-8")


def decrypt_value(cipher_text: str) -> str:
    """Decrypt a URL-safe base-64 token and return the plain string."""
    if not cipher_text:
        return ""
    try:
        f = _get_fernet()
        return f.decrypt(cipher_text.encode("utf-8")).decode("utf-8")
    except Exception:
        return ""
