import base64
import hashlib
import os

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


MASKED_SECRET = "\u2022" * 8


def _get_encryption_secret():
    return (
        getattr(settings, "ISTAT_CREDENTIAL_ENCRYPTION_KEY", None)
        or os.environ.get("ISTAT_CREDENTIAL_ENCRYPTION_KEY")
        or settings.SECRET_KEY
    )


def _get_cipher():
    raw_secret = _get_encryption_secret()
    if isinstance(raw_secret, str):
        raw_secret = raw_secret.encode("utf-8")

    derived_key = base64.urlsafe_b64encode(hashlib.sha256(raw_secret).digest())
    return Fernet(derived_key)


def encrypt_istat_secret(value):
    normalized = str(value or "").strip()
    if not normalized:
        return ""
    return _get_cipher().encrypt(normalized.encode("utf-8")).decode("utf-8")


def decrypt_istat_secret(value):
    if not value:
        return ""

    try:
        return _get_cipher().decrypt(value.encode("utf-8")).decode("utf-8")
    except InvalidToken as exc:
        raise ValueError("Unable to decrypt stored ISTAT credentials.") from exc


def mask_istat_secret(value):
    return MASKED_SECRET if value else ""
