# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_spec.ipynb.

# %% auto #0
__all__ = ['docs_url', 'pat', 'build_eps', 'update_version']

# %% ../nbs/00_spec.ipynb #4ea88bd2
from fastcore.all import *
from nbdev.config import set_version, get_config

import os, pprint, re

# %% ../nbs/00_spec.ipynb #2487fb8f
_lu_type = dict(zip(
    'NA string object array boolean number integer'.split(),
    map(PrettyString,'object str dict list bool int int'.split())
))

# %% ../nbs/00_spec.ipynb #aa97b461
def _find_data(v, encoding='application/json'):
    'Finds the properties in a schema'
    schema = nested_idx(v, *f'requestBody content {encoding} schema'.split())
    if not schema: return {}
    if 'properties' in schema: return schema['properties']
    if 'oneOf' in schema:
        for o in schema['oneOf']:
            if 'properties' in o: return o['properties']
    return {}

# %% ../nbs/00_spec.ipynb #0bef93c9
def _deets(k,v):
    'Extracts the type and default value from a schema'
    return {'name': k, 'description': v.get('description', ''),
        'annotation': _lu_type[v.get('type', 'NA')], 'default' : v.get('default', None)}

# %% ../nbs/00_spec.ipynb #05f1c67c
def _info(desc):
    # handle both json and form-urlencoded
    data = _find_data(desc, 'application/json') | _find_data(desc, 'application/x-www-form-urlencoded')
    data = [_deets(*o) for o in data.items()]

    params = desc.get('parameters',None)
    qparams = [{'name': p['name'], 'description': p.get('description', ''), 'annotation': 'str'}
               for p in params if p.get('in')=='query'] if params else []
    return {'data': data, 'op_id': desc.get('operationId',''),
            'qparams': qparams, 'summary': desc.get('summary','')}

# %% ../nbs/00_spec.ipynb #c527196d
docs_url = 'https://docs.stripe.com/api'

# %% ../nbs/00_spec.ipynb #f997d803
def _slug(has_pparams, is_plural, verb):
    'Return the slug for a verb'
    match (has_pparams, is_plural, verb):
        case (_, False, 'get'): return 'retrieve'
        case (True, _, 'post'): return 'update'
        case (False, _, 'get'): return 'list'
        case (False, _, 'post'): return 'create'
        case _: return 'delete'

# %% ../nbs/00_spec.ipynb #7919c0fc
pat = r'/\{[^}]+\}'
def _durl(path, verb):
    'Return the doc url for a path and verb if it exists else None'
    has_pparams = '{' in path
    p = re.sub(pat, '', path)
    is_plural = p.endswith('s')
    if not is_plural: p += 's'
    res = p.split('/')[-1]
    slug = _slug(has_pparams, is_plural, verb)
    return f'{docs_url}/{res}/{slug}'

# %% ../nbs/00_spec.ipynb #cb78877a
def build_eps(url):
    "Build module metadata.py from an Open API spec and optionally filter by a path `pre`"
    spec = urlsend(url, 'GET', return_json=True)
    _funcs = [{'path': p, 'verb': v, **_info(desc), 'doc_url': _durl(p, v)}
              for p, vs in spec['paths'].items() for v, desc in vs.items()]
    return _funcs

# %% ../nbs/00_spec.ipynb #0af7536e
@call_parse
def update_version():
    'Update the version to the latest version of the Stripe API and the endpoints file.'
    stripe_spec = urlsend(stripe_openapi_url, 'GET', return_json=True)
    stripe_version = stripe_spec['info']['version'].split('.')[0].replace('-', '.')

    cfg = get_config()
    if cfg.version.rsplit('.', 1)[0] == stripe_version: return
    set_version(cfg.lib_path, stripe_version + '.0')
    eps = build_eps(stripe_openapi_url)
    (cfg.config_path/'faststripe/endpoints.py').write_text(f'eps = {pprint.pformat(eps, width=360)}')
    print(f"Updated version to {get_config().version}")
