import requests
from pip.whitelist import whitelist

def get_metadata(package_name):
    url = 'https://pypi.org/pypi/' + package_name + '/json'
    return requests.get(url).json()['info']

def get_license(metadata):
    licenses = set()
    if type(metadata['license']) is str:
        licenses.add(metadata['license'])
    for line in metadata['classifiers']:
        if 'License ::' in line:
            licenses.add(line.upper())
            break
    return licenses 

def get_dependencies(metadata):
    dependencies = metadata['requires_dist']
    if dependencies is None:
        return set()
    return {dep.split(' ')[0].split('[')[0].split('>')[0].split(';')[0] for dep in dependencies if not '; extra' in dep}

def is_free_license(licenses):
    has_license = False
    for license in licenses:
        if not license == '' or license == 'UNKNOWN':
            has_license = True
            if not license in whitelist:
                return False
    return has_license

def freedom_status(package_name):
    metadata = get_metadata(package_name)
    license = get_license(metadata)
    if not is_free_license(license):
        return "non-free"
    dependencies = get_dependencies(metadata)
    for dep in dependencies:
        if freedom_status(dep) != 'free':
            return 'contrib'
    return "free"

