# -*- coding: utf-8 -*-
# Copyright (c) 2017 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

from datetime import datetime, timezone
from typing import Mapping, Optional, SupportsFloat

import jwt
import pyfaaster.aws.tools as faaster_aws_tools

from czc.constants import FEATURE_NAME
from czc.date import timestamp_to_utc_datetime

logger = faaster_aws_tools.setup_logging(FEATURE_NAME)


def decode(token: str, keyset: Mapping) -> Optional[Mapping]:
    instance = jwt.JWT()
    for k in keyset.get('keys', []):
        try:
            decoded = instance.decode(token, jwt.jwk_from_dict(k))
            return decoded
        except Exception:
            logger.warning(f'Unable to decode token: {token} with key: {k}')
    return None


def is_expired(decoded: Mapping[str, SupportsFloat]) -> bool:
    if 'exp' not in decoded:
        return True

    expiration = timestamp_to_utc_datetime(decoded['exp'])
    current = datetime.now(tz=timezone.utc)

    return current > expiration


# Legacy API
def decode_token(token: str, keyset_dict: Mapping) -> Optional[Mapping]:
    return decode(token, keyset_dict)


token_expired = is_expired
