"""Select one installed package without conflating multiarch records."""

def select_installed(text, requested, native):
    name, separator, arch = requested.partition(':')
    target = arch if separator else native
    matches = []
    for line in text.splitlines():
        fields = line.split('\t')
        if len(fields) != 4:
            raise ValueError('Malformed dpkg record')
        canonical, version, actual_arch, status = fields
        if canonical.split(':')[0] != name:
            raise ValueError('Unexpected package name')
        if actual_arch not in {target, 'all'}:
            continue
        if status != 'install ok installed' or not version:
            raise ValueError('Package is not completely installed')
        matches.append((canonical, {'version': version, 'arch': actual_arch}))
    if len(matches) != 1:
        raise ValueError('Expected exactly one matching package architecture')
    return matches[0]
