import base64
import json
import logging


def process_data(encoded_str, data_should_be_json):
    """Accepts a string of b64-encoded data. Tries the following steps, saving
    the result each time. If any of the steps fails, it returns the most recent
    success. If no processing step succeeds (i.e. the result of decoding the
    data not an ascii-representable string), then we just return the original
    input: the base64-encoded string. Steps:
    1. Try to decode the base64-encoded string into something ascii-readable.
    2. If data_should_be_json, then we try to load the json into a python dict.
    """
    result = encoded_str
    # Step 1: Try to make it a human-readable string
    try:
        decoded_bytes = base64.b64decode(encoded_str)
        if decoded_bytes.isascii():
            decoded_str = decoded_bytes.decode()
            result = decoded_str
            if data_should_be_json:
                result = json.loads(result)
        elif data_should_be_json:
            logging.warning(
                f"Should've been able to json load this but it wasn't even ascii: {encoded_str}"
            )
    except json.decoder.JSONDecodeError as exn:
        logging.exception(
            f"Should've been able to json load the data but couldn't: {encoded_str}",
            exc_info=exn,
        )
    except Exception as exn:
        logging.exception(
            f"Caught an unexpected exception processing `{encoded_str}`:",
            exc_info=exn,
        )
    return result