# AUTOGENERATED! DO NOT EDIT! File to edit: 10_cli.ipynb (unless otherwise specified).

__all__ = ['ghapi', 'ghpath', 'ghraw', 'completion_ghapi']

# Cell
from fastcore.utils import *
from fastcore.foundation import *
import ghapi.core as gh,inspect
from .core import *
from collections import defaultdict

# Cell
def _parse_args(a):
    "Extract positional and keyword arguments from `a`=`sys.argv`"
    pos,kw = [],{}
    i=1
    while i<len(a):
        x = a[i]
        if x[:2]=='--':
            k = x[2:]
            if k in ('help','debug'): y = 1
            else:
                i += 1
                y = a[i]
            kw[k] = y
        else: pos.append(a[i])
        i += 1
    return a[0],pos,kw

def _api():
    "Result of `_parse_args` along with `GhApi`"
    cmd,pos,kw = _parse_args(sys.argv)
    token = kw.pop('token',None) or os.getenv('GITHUB_TOKEN')
    api = GhApi(token=token, debug=print_summary if kw.pop('debug',None) else None)
    return cmd,api,pos,kw

def _call_api(f):
    "Call `f`, passing in args parsed from `sys.argv`"
    cmd,api,pos,kw = _api()
    if not pos: return print(f"Usage: `{cmd}` operation <params>")
    call = f(pos, api)
    return call if kw.get('help', None) else call(*pos, **kw)

# Cell
def _ghapi(arg, api):
    for part in arg.pop(0).split('.'): api = getattr(api,part)
    return api

# Cell
#export
def ghapi():
    "Python backend for the `ghapi` command, which calls an endpoint by operation name"
    res = _call_api(_ghapi)
    if isinstance(res, (gh._GhObj,dict,L)): print(res)
    elif res: print(inspect.signature(res))

# Cell
def _ghpath(arg, api): return api[arg.pop(0),arg.pop(0)]

# Cell
#export
def ghpath():
    "Python backend for the `ghpath` command, which calls an endpoint by path"
    print(_call_api(_ghpath) or '')

# Cell
#export
def ghraw():
    "Python backend for the `ghraw` command, which calls a fully-specified endpoint"
    cmd,api,pos,kw = _api()
    if not pos: return print(f"Usage: `{cmd}` operation <params>")
    print(api(*pos, **kw))

# Cell
#export
_TAB_COMPLETION="""
_do_ghapi_completions()
{
    COMP="$(completion-ghapi "${COMP_WORDS[1]}")"
    COMPREPLY=($COMP)
}

complete -F _do_ghapi_completions ghapi
"""

# Cell
#export
def completion_ghapi():
    "Python backend for `completion-ghapi` command"
    if len(sys.argv) == 2 and sys.argv[1] == '--install':
        print(_TAB_COMPLETION)
        return
    *parts,final = (sys.argv[1] if len(sys.argv)>1 else '').split('.')
    call = GhApi()
    for part in parts: call = getattr(call,part)
    if hasattr(call,final): res = [final]
    else: res = [o for o in dir(call) if o.startswith(final) and not o.startswith('_')]
    pre = '.'.join(parts+[final])
    print(' '.join(pre + remove_prefix(o, final) for o in res))