#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""敏感信息加解密（数据库连接密码等）"""
import base64
import hashlib
import logging

from app.config import settings

logger = logging.getLogger(__name__)

_fernet = None


def _get_fernet():
    global _fernet
    if _fernet is not None:
        return _fernet
    try:
        from cryptography.fernet import Fernet
    except ImportError as exc:
        raise RuntimeError("cryptography package is required for secret encryption") from exc

    secret = getattr(settings, "DB_CONN_SECRET_KEY", None) or settings.JWT_SECRET_KEY
    key = base64.urlsafe_b64encode(hashlib.sha256(secret.encode("utf-8")).digest())
    _fernet = Fernet(key)
    return _fernet


def encrypt_secret(value: str) -> str:
    if not value:
        return ""
    return _get_fernet().encrypt(value.encode("utf-8")).decode("utf-8")


def decrypt_secret(value: str) -> str:
    if not value:
        return ""
    try:
        return _get_fernet().decrypt(value.encode("utf-8")).decode("utf-8")
    except Exception as exc:
        logger.warning("Failed to decrypt secret: %s", exc)
        return ""
