from cryptography.fernet import Fernet, InvalidToken

from app.core.config import CREDENTIAL_ENCRYPTION_KEY


def _get_fernet() -> Fernet:
    if not CREDENTIAL_ENCRYPTION_KEY:
        raise ValueError(
            "CREDENTIAL_ENCRYPTION_KEY is not set. "
            "Generate one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
        )
    return Fernet(CREDENTIAL_ENCRYPTION_KEY.encode())


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


def decrypt_secret(encrypted: str) -> str:
    try:
        return _get_fernet().decrypt(encrypted.encode("utf-8")).decode("utf-8")
    except InvalidToken as exc:
        raise ValueError("Failed to decrypt stored credential") from exc
