# WARNING: this file is automatically generated, changes will be overwritten
import os
import sys
import logging
logger = logging.getLogger()
if "ipykernel_launcher" not in sys.argv[0]:
  logger.warning("get_ipython() CALLS WILL RETURN '' (empty)")
  class get_ipython():
    @classmethod
    def system(one,two=None,three=None,four=None):
      return os.system(two)
    @classmethod
    def run_cell_magic(one,two=None,three=None,four=None):
      return ''
    @classmethod
    def getoutput(one,two):
      return ''
    @classmethod
    def run_line_magic(one,two,three):
      return ''
# rel: https://docs.python.org/3/library/argparse.html
# rel: https://docs.python.org/3/library/inspect.html
def argparse_from_signature(function_name, parser):
  '''uses a function signature to create argparse arguments'''
  for param,val in inspect.signature(function_name).parameters.items():
    argpd = {}
    choices = list(typing.get_args(val.annotation))
    # auto-convert float and int from cmdline
    if val.annotation==int: argpd['type']=int
    elif val.annotation==float: argpd['type']=float
    elif len(choices)>0:
      argpd['choices']=choices
    # set any defaults we know of from the signature
    if val.default!=val.empty: 
      argpd['default']=val.default
      argpd['help']='(default: %(default)s)'

    if 'variadic' in val.kind.description: argpd['nargs']='*' #variadic keyword|positional
    # if positional *and* no default then do "required" logic
    if 'positional' in val.kind.description and val.default==val.empty: parser.add_argument(val.name,**argpd)
    else: parser.add_argument('-'+val.name[0].lower(), '--'+val.name.lower(), **argpd)
  return parser

def setup_cmdline_args():
  '''automatic command line arg system using `config_dict()` 
  kwargs must be named "kwargs" to parse'''
  global c

  parser = argparse.ArgumentParser(
    description=__doc__+'\n(abbreviations e.g., --abbr: ON)',
    # width for Jupyter, avoid one word per line
    formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=79)
  )
  parser = argparse_from_signature(config_dict, parser)
  # caps to avoid collisions
  rdefault = 0 if '-R' in str(sys.argv) else 2
  vdefault = 0 if '-V' in str(sys.argv) else 5
  parser.add_argument('-R', '--runlevel', action='count', default=rdefault, help='repeatable, -RRR is runlevel=3 default:%(default)s')
  parser.add_argument('-V', '--verbose', action='count', default=vdefault, help='repeatable, -VVVVV is verbosity=5 default:%(default)s (1:critical,2:error,3:warning,4:info,5:debug)')
  parser.add_argument("-v", "--version", action="version",version = f"{parser.prog} version 1.0.0")
  
  args = vars(parser.parse_args())
  # keyword arg fun! split : and = delimited list items into a dict, works with JSON input
  if 'kwargs' in args and args['kwargs'] != None:
    eq2 = [i.replace(':','=') for i in args['kwargs']]
    args=dict(**args, **dict(i.split('=') for i in eq2))
    # del args['kwargs']
  c = config_dict(**args) # run args through usual config_dict: win.
  return c
def get_json_for_python_export():
  activenb = _message.blocking_request('get_ipynb', request='', timeout_sec=5)['ipynb']
  activenb['cells'] = activenb['cells']
  out_cells = []
  collecting = True
  for cell in activenb['cells']:
    if cell['cell_type']=='markdown' and cell['source'][0][0]=='#' and cell['source'][0][1]!='#' and cell['source'][0].replace('#','').strip() not in skip_headers:
      print('Collecting cells under header:',cell['source'][0])
      collecting = True
    if cell['cell_type']=='markdown' and cell['source'][0][0]=='#' and cell['source'][0][1]!='#' and cell['source'][0].replace('#','').strip() in skip_headers:
      print('Skipping cells under header:',cell['source'][0])
      collecting = False
    if collecting == True:
      out_cells.append(cell)
  activenb['cells']=out_cells
  return activenb
# get_active_notebook_json()
