import json
from datetime import datetime


def mfa_from_str(json_str: str, *, include_expiration=False) -> dict:
    """Create credentials dict from credentials as a json string.

    This function is a thin wrapper around json.loads

    Args:
        json_str (str): String containing a json object. e.g.
            '''
            {
                "Credentials": {
                    "AccessKeyId": "FAKEACCESSKEY",
                    "SecretAccessKey": "Fake+Secret9Access-Key",
                    "SessionToken": "f4k3-SE5510N_t0k3n",
                    "Expiration": "2019-07-30T00:14:27Z"
                }
            }
            '''
        include_expiration (bool, optional): Whether to include expiration in
            returned json. Defaults to False.

    Returns:
        dict: with types as
            {
                "aws_access_key_id": str,
                "aws_secret_access_key": str,
                "aws_session_token": str,
                "expiration": datetime,
            }

    Example:
        >>> import dynatrace_locksmith as ls
        >>> creds = ls.mfa_from_str(json_str)
        >>> creds
        {
            "Credentials": {
                "AccessKeyId": "1234567890",
                "SecretAccessKey": "qwertyuiop",
                "SessionToken": "asdfghjklzxcvbnm",
                "Expiration": "2018-11-02T05:15:21Z"
            }
        }

        >>> session = boto3.Session(**creds)
    """
    if not isinstance(json_str, str):
        raise TypeError("json_str must be a str")
    if not isinstance(include_expiration, bool):
        raise TypeError("include_expiration must be a bool")

    creds = json.loads(json_str)["Credentials"]
    creds["aws_access_key_id"] = creds.pop("AccessKeyId")
    creds["aws_secret_access_key"] = creds.pop("SecretAccessKey")
    creds["aws_session_token"] = creds.pop("SessionToken")

    expiration = creds.pop("Expiration")
    if include_expiration:
        creds["expiration"] = datetime.strptime(
            expiration.replace("Z", "+0000"), "%Y-%m-%dT%H:%M:%S%z"
        )

    return creds