"Access to DEB_BUILD_OPTIONS and DEB_BUILD_OPTIONS from the environment."

import functools
import os
from collections.abc import Mapping


@functools.cache
def _parse_profiles(value: str) -> frozenset[str]:
    return frozenset(value.split())


@functools.cache
def _parse_deb_build_options(value: str) -> Mapping[str, str | None]:
    res: dict[str, str | None] = {}
    for kvish in value.split():
        if "=" in kvish:
            key, value = kvish.split("=", 1)
            res[key] = value
        else:
            res[kvish] = None
    return res


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

    >>> env = DebBuildOptionsAndProfiles(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: Mapping[str, str] | None = None) -> None:
        """Provide a view of the options.

        :param environ: Alternative to os.environ. Mostly useful for testing purposes
        """
        self._env = os.environ if environ is None else environ

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

        >>> env = DebBuildOptionsAndProfiles(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 _parse_profiles(self._env.get("DEB_BUILD_PROFILES", ""))

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

        >>> env = DebBuildOptionsAndProfiles(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 _parse_deb_build_options(self._env.get("DEB_BUILD_OPTIONS", ""))
