import os

from typing import FrozenSet, Optional, Mapping


class DebOptionsAndProfiles:
    """Accessor to common environment related values

    >>> env = DebOptionsAndProfiles(environ={'DEB_BUILD_PROFILES': 'noudeb nojava'})
    >>> 'noudeb' in env.deb_build_profiles
    True
    >>> 'nojava' in env.deb_build_profiles
    True
    >>> 'nopython' in env.deb_build_profiles
    False
    >>> sorted(env.deb_build_profiles)
    ['nojava', 'noudeb']
    """

    def __init__(self, *, environ=None):
        if environ is None:
            environ = dict(os.environ)
        self.environ = environ
        self._deb_build_profiles = self._parse_set_from_environ("DEB_BUILD_PROFILES")
        self._deb_build_options = self._parse_dict_from_environ("DEB_BUILD_OPTIONS")

    @staticmethod
    def instance():
        global _INSTANCE
        if _INSTANCE is None:
            _INSTANCE = DebOptionsAndProfiles()
        return _INSTANCE

    def _parse_set_from_environ(self, env_name, default_value=""):
        return frozenset(x for x in self.environ.get(env_name, default_value).split())

    def _parse_dict_from_environ(self, env_name, default_value="") -> Mapping[str, str]:
        res = {}
        for kvish in self.environ.get(env_name, default_value).split():
            if "=" in kvish:
                key, value = kvish.split("=", 1)
                res[key] = value
            else:
                res[kvish] = None
        return res

    @property
    def deb_build_profiles(self) -> FrozenSet[str]:
        """A set-like view of all build profiles active during the build

        >>> env = DebOptionsAndProfiles(environ={'DEB_BUILD_PROFILES': 'noudeb nojava'})
        >>> 'noudeb' in env.deb_build_profiles
        True
        >>> 'nojava' in env.deb_build_profiles
        True
        >>> 'nopython' in env.deb_build_profiles
        False
        >>> sorted(env.deb_build_profiles)
        ['nojava', 'noudeb']

        """
        return self._deb_build_profiles

    @property
    def deb_build_options(self) -> Mapping[str, Optional[str]]:
        """A set-like view of all build profiles active during the build

        >>> env = DebOptionsAndProfiles(environ={'DEB_BUILD_OPTIONS': 'nostrip parallel=4'})
        >>> 'nostrip' in env.deb_build_options
        True
        >>> 'parallel' in env.deb_build_options
        True
        >>> 'noautodbgsym' in env.deb_build_options
        False
        >>> env.deb_build_options['nostrip'] is None
        True
        >>> env.deb_build_options['parallel']
        '4'
        >>> env.deb_build_options['noautodbgsym']
        Traceback (most recent call last):
            ...
        KeyError: 'noautodbgsym'
        >>> sorted(env.deb_build_options)
        ['nostrip', 'parallel']

        """
        return self._deb_build_options


_INSTANCE = None
