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

# %% auto 0
__all__ = ['PGP_Key_ValidationError', 'PGP_Content_ValidationError', 'generate_pgpy_key', 'pgpy_encrypt', 'decrypt_pgp_file']

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

import pgpy

import domolibrary_extensions.utils.utils as deut
import domolibrary_extensions.utils.convert as decv
import domolibrary_extensions.client as decl

# %% ../nbs/pgp/pgp.ipynb 6
class PGP_Key_ValidationError(decl.BaseError_Validation):
    def __init__(self, message):
        super().__init__(message)


class PGP_Content_ValidationError(decl.BaseError_Validation):
    def __init__(self, message):
        super().__init__(message)

# %% ../nbs/pgp/pgp.ipynb 7
def generate_pgpy_key(pgp_keyring_path=None, pgp_blob=None):
    pgp_key = None

    if not pgp_key and pgp_keyring_path:
        pgp_key, _ = pgpy.PGPKey.from_file(pgp_keyring_path)

    if not pgp_key and pgp_blob:
        pgp_key, _ = pgpy.PGPKey.from_blob(pgp_blob)

    if not pgp_key:
        raise PGP_Key_ValidationError("unable to generate pgpy key")

    return pgp_key

# %% ../nbs/pgp/pgp.ipynb 8
def pgpy_encrypt(
    data, pgp_keyring_path=None, pgp_blob=None, pgp_key=None, output_path: str = None
):
    pgp_key = pgp_key or generate_pgpy_key(
        pgp_keyring_path=pgp_keyring_path, pgp_blob=pgp_blob
    )

    if not pgp_key:
        raise PGP_Key_ValidationError("unable to generate pgpy key")

    if isinstance(data, dict):
        data = json.dumps(data)

    message = pgpy.PGPMessage.new(data)
    # message = pgpy.PGPMessage.new("This is a brand spankin' new message!")

    enc_message = bytes(pgp_key.pubkey.encrypt(message))

    if not output_path:
        return enc_message

    deut.upsert_folder(output_path)

    output_path = decv.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 10
def decrypt_pgp_file(
    pgp_password,
    pgp_keyring_path=None,
    pgp_blob=None,
    pgp_key=None,
    msg_blob=None,  # encrypted binary blob
    file_path=None,  # path to a encrypted file
    export_path=None,
):
    if not msg_blob and not file_path:
        raise PGP_Content_ValidationError(
            "must pass `msg_blob` or `file_path` to encrypted content"
        )

    pgp_key = pgp_key or generate_pgpy_key(
        pgp_keyring_path=pgp_keyring_path, pgp_blob=pgp_blob
    )

    if not pgp_key:
        raise PGP_Key_ValidationError("unable to generate pgpy key")

    emsg = None
    if file_path:
        emsg = pgpy.PGPMessage.from_file(file_path)

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

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

    with pgp_key.unlock(pgp_password):
        data = pgp_key.decrypt(emsg).message

    try:
        data = json.loads(data)

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

    obj.update(**data)

    if not export_path:
        return obj

    export_path = decv.change_suffix(export_path, ".key")
    deut.upsert_folder(export_path)
    with open(export_path, "w+", encoding="utf-8") as f:
        f.write(json.dumps(obj))

    return f"key exported to {export_path}"
