import base64
from datetime import datetime
from typing import Optional, Tuple, Union

from clarabot_crypto.group_config.chain import BlockName
from clarabot_crypto.license.file import LicenseFile


def block_name_to_config_format(block_name: BlockName) -> str:
    return block_name


def block_name_from_config_format(block_name: BlockName) -> Optional[BlockName]:
    """
    Errors are ignored so config blockchain verification will fall back to unverified and the Nano will still work.
    """
    if block_name.find("|") > 0:
        return block_name
    # convert older "id_hash" to new "name" format
    try:
        id_, _, hash_ = block_name.partition(":")
        return f"{id_}|{base64.urlsafe_b64encode(base64.b64decode(hash_)).decode('ascii')}"
    except Exception:
        pass


def get_local_license_validity(vendor: str, lic: Union[None, str, bytes, LicenseFile]) -> Union[str, Tuple[str, float]]:
    if lic is None:
        return "missing"
    elif isinstance(lic, LicenseFile):
        pass
    elif isinstance(lic, (str, bytes)):
        try:
            lic = LicenseFile.loads(lic)
        except Exception:
            return "invalid"
    else:
        return "invalid"
    if not lic.has_vendor(vendor):
        return "vendor mismatch"
    if not lic.is_valid():
        return "expired"
    return "valid", datetime(lic.until.year, lic.until.month, lic.until.day).timestamp()
