import os
from pathlib import PurePath

import certifi

from clarabot_nano.utility.path.common import validate_name


def _parse_dir_name_override() -> str:
    if name := os.environ.get("CBNANO_USER_DIR_OVERRIDE"):
        p = PurePath(name)
        if not p.is_absolute() and len(p.parts) == 1 and (name := p.parts[0]):
            validate_name(name)
            return name
    return "clarabot"


class CommonConfigConstants(object):
    USER_DATA_PATH_PARTS = (_parse_dir_name_override(), "nano")
    SERVER_DOMAIN = "nano.clarabot.com"
    SERVER_PATH = "/api/"
    AIOHTTP_CLIENT_SESSION_OPTS = {"cafile": certifi.where()}
    DEVELOPMENT = False  # informative flag; set at startup

    # @classmethod
    # def url_for(cls, path="", scheme="https"):
    #     return f"{scheme}://{cls.SERVER_DOMAIN}{cls.SERVER_PATH}{path}"


class LocalSecrets(object):
    """
    To provide the Nano complete control over the active encryption keys, those are derived using these "secret"
    values that are completely up to the machine running Nano.
    They also improve security because they provide additional entropy.
    """

    # used by the server handlers
    SERVER_REQUEST_KEY_IKM = 0  # ikm for deriving a deterministic nonce for the request_key encryption
    SERVER_CACHE_KEY_ENCRYPTION = 1  # used for securing cacheable request_keys
    SERVER_TRANSFER_KEY_ENCRYPTION = 2  # used for securing not cacheable request_keys
    SERVER_CACHE_KEY_IKM = 3  # ikm for deriving a deterministic part_key for cacheable responses
    SERVER_TRANSFER_KEY_IKM = 4  # ikm for deriving a deterministic part_key for not cacheable responses

    # local consistency check of the secrets
    FINGERPRINT = 5  # must be the last index so [-1] is a synonym for it

    # different lengths for optimizing KDF
    LENGTH_32_BEFORE = SERVER_CACHE_KEY_ENCRYPTION


class NanoServeAPI(object):
    """
    Types of APIs (versioned) that are served for a room.
    """

    DRIVE_V1 = 1
    DRIVE_V2 = 2  # FS-PEEK, transfer continuation
    DRIVE_V3 = 3  # FS-THMB, "img0" in FS-PEEK and SEARCH

    # The API versions advertised by this Nano.
    DRIVE_CURRENT = DRIVE_V3
