import json
import itertools
import apt

def add_debian_packages(packages):
    c = apt.Cache()

    for pkg in packages:
        for pkg_name in pkg['pypi_name'].lower(), pkg['name'].lower():
            if pkg_name.startswith('python-'):
                pkg_name = pkg_name[len('python-'):]
            for prefix in 'python-', 'python3-':
                debian_pkg = c.get(prefix + pkg_name)
                if debian_pkg:
                    l = pkg.setdefault('debian_pkg', [])
                    if debian_pkg.name not in l:
                        l.append(debian_pkg.name)


def get_affiliated(packages, coordinated=False):
    def flt(pkg):
        if coordinated:
            return pkg['coordinated']
        else:
            return True
    return sorted(itertools.chain(
        *([p for p in pkg.get('debian_pkg', [])
           if p.startswith("python3-")]
          for pkg in packages
          if (pkg['name'] != 'astropy core package'
              and flt(pkg)))))


with open('affiliated.json') as fp:
    registry = json.load(fp)

packages = registry['packages']
add_debian_packages(packages)

with open('debian/python3-astropy-affiliated.substvars', 'at') as fp:
    affiliated = ','.join(get_affiliated(packages, False))
    fp.write(f'astropy:Affiliated={affiliated}\n')

with open('debian/python3-astropy-coordinated.substvars', 'at') as fp:
    coordinated = ','.join(get_affiliated(packages, True))
    fp.write(f'astropy:Coordinated={coordinated}\n')
