# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/pgp/pgp.ipynb.

# %% auto 0
__all__ = ['pgpy_encrypt', 'decrypt_gpg_file']

# %% ../nbs/pgp/pgp.ipynb 4
import datetime as dt
import json

import pgpy

import domolibrary_extensions.utils.utils as dxeu
import domolibrary_extensions.utils.convert as dxec

# %% ../nbs/pgp/pgp.ipynb 6
def pgpy_encrypt(gpg_keyring_path, data, output_path: str = None):
    key, _ = pgpy.PGPKey.from_file(gpg_keyring_path)

    message = pgpy.PGPMessage.new(data)
    enc_message = bytes(key.pubkey.encrypt(message))

    if not output_path:
        return enc_message

    dxeu.upsert_folder(output_path)

    output_path = dxec.change_suffix(filename=output_path, new_extension=".gpg")
    with open(output_path, "+wb") as f:
        f.write(enc_message)

    return f"output key to {output_path}"

# %% ../nbs/pgp/pgp.ipynb 8
def decrypt_gpg_file(
    gpg_keyring_path,
    gpg_password,
    msg_blob=None,  # encrypted binary blob
    file_path=None,  # path to a encrypted file
):
    emsg = None
    if file_path:
        emsg = pgpy.PGPMessage.from_file(file_path)

    if msg_blob:
        emsg = pgpy.PGPMessage.from_blob(msg_blob)

    key, _ = pgpy.PGPKey.from_file(gpg_keyring_path)

    obj = {
        "_decrypted_date": dt.datetime.now().strftime("%Y-%m-%d %H:%m"),
        "_file_path": file_path,
    }

    with key.unlock(gpg_password):
        data = key.decrypt(emsg).message

    try:
        data = json.loads(data)

    except ValueError as e:
        data = {"message": data}

    obj.update(**data)

    return obj
