"""Version 2 of patch in bug #1120283 for python-debian.

A new debian.deb822 will hopefully one day replace this file.
"""

import collections.abc

from debian.debian_support import DpkgArchTable
from debian.deb822 import PkgRelation


def holds_on_arch(
    relation: "PkgRelation.ParsedRelation",
    arch: str,
    table: DpkgArchTable,
) -> bool:
    """Is relation active on the given architecture?

    >>> table = DpkgArchTable.load_arch_table()
    >>> rel = PkgRelation.parse_relations("foo [armel linux-any]")[0][0]
    >>> holds_on_arch(rel, "amd64", table)
    True
    >>> holds_on_arch(rel, "hurd-i386", table)
    False
    """
    archs = relation["arch"]
    return archs is None or table.architecture_is_concerned(
        arch, tuple(("" if a.enabled else "!") + a.arch for a in archs)
    )


def holds_with_profiles(
    relation: "PkgRelation.ParsedRelation",
    profiles: collections.abc.Container[str],
) -> bool:
    """Is relation active under the given profiles?

    >>> relation = PkgRelation.parse_relations("foo <a !b> <c>")[0][0]
    >>> holds_with_profiles(relation, ("a", "b"))
    False
    >>> holds_with_profiles(relation, ("c", ))
    True
    """
    restrictions = relation["restrictions"]
    return restrictions is None or any(
        all(term.enabled == (term.profile in profiles) for term in restriction_list)
        for restriction_list in restrictions
    )
