# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05a_conda.ipynb (unless otherwise specified).

__all__ = ['write_conda_meta']

# Cell
from .imports import *
from .export import *

import urllib.request, json
from copy import deepcopy
import yaml

# Cell
def _get_conda_meta():
    cfg = Config()
    name,ver = cfg.get('lib_name'),cfg.get('version')
    url = cfg.get('doc_host') or cfg.get('git_url')

    reqs = ['pip', 'python', 'packaging']
    if cfg.get('requirements'): reqs += cfg.get('requirements').split()
    if cfg.get('conda_requirements'): reqs += cfg.get('conda_requirements').split()

    pypi_t = urllib.request.urlopen(f'https://pypi.org/pypi/{name}/{ver}/json').read()
    pypi = json.loads(pypi_t)
    rel = [o for o in pypi['urls'] if o['packagetype']=='sdist'][0]

    # Work around conda build bug - 'package' and 'source' must be first
    d1 = {
        'package': {'name': name, 'version': ver},
        'source': {'url':rel['url'], 'sha256':rel['digests']['sha256']}
    }

    d2 = {
        'build': {'number': '0', 'noarch': 'python',
                  'script': '{{ PYTHON }} -m pip install . -vv'},
        'requirements': {'host':reqs, 'run':reqs},
        'test': {'imports': [name]},
        'about': {
            'license': 'Apache Software',
            'license_family': 'APACHE',
            'home': url, 'doc_url': url, 'dev_url': url,
            'summary': cfg.get('description')
        },
        'extra': {'recipe-maintainers': [cfg.get('user')]}
    }
    return name,d1,d2

# Cell
def write_conda_meta(path='conda'):
    "Writes a `meta.yaml` file to the `conda` directory of the current directory"
    name,d1,d2 = _get_conda_meta()
    path = Path(path)
    p = path/name
    p.mkdir(exist_ok=True, parents=True)
    yaml.SafeDumper.ignore_aliases = lambda *args : True
    with (p/'meta.yaml').open('w') as f:
        yaml.safe_dump(d1, f)
        yaml.safe_dump(d2, f)