#!/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."""

# yapf: disable

# Standard library imports
import json
import os.path as osp

# yapf: enable

PIP = True
try:
    import pip
except ImportError:
    PIP = False
except Exception:
    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 pip.get_installed_distributions():
            name = package.project_name
            version = package.version
            full_name = "{0}-{1}-pip".format(name.lower(), version)
            pip_packages[full_name] = {'version': version}
    data = json.dumps(pip_packages)
    print(data)


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