#!/usr/bin/env python

# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016-2017 Anaconda, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------

"""List pip pacakges in a given conda environments."""

import json
import os.path as osp

PIP = True
try:
    from pip._internal.utils.misc import get_installed_distributions
except ImportError:
    PIP = False
except Exception:  # pylint: disable=broad-except
    PIP = False


PIP_LIST_SCRIPT = osp.realpath(__file__).replace('.pyc', '.py')


def main():
    """Use pip to find pip installed packages in a given prefix."""
    pip_packages = {}
    if PIP:
        for package in get_installed_distributions():
            name = package.project_name
            version = package.version
            full_name = f'{name.lower()}-{version}-pip'
            pip_packages[full_name] = {'version': version}
    data = json.dumps(pip_packages)
    print(data)


if __name__ == '__main__':  # pragma: no cover
    try:
        main()
    except Exception as inst:  # pylint: disable=broad-except
        # Something went wrong, so the package list is the empty list
        print('{}')
