"""my user utilities; installed at builtins.__ so they can be accessed without importing anything

__.pdb() calls pdb.set_trace()

The following modules can be accessed at __.$module_name:

- inspect
- json
- os
- pprint
- re
- sys
"""
import builtins
import inspect
import json
import os
import os.path
import pprint
import pdb as pdb_
import re
import sys
import code
import rlcompleter
import traceback
import warnings
import threading
import time

builtins.__ = sys.modules[__name__]

pdb = pdb_.set_trace
def exit(n=42):
    os._exit(n)

_local_file = "_/usercustomize_local.py"

if(os.path.exists(_local_file)):
    print(f"Loading {_local_file}", file=sys.stderr)
    sys.path.append("_")
    import usercustomize_local

# TODO: add something for monkeypatching

# this is slow, so just launch a thread to do it ten seconds later
def configure_pandas():
    time.sleep(10)
    try:
        import pandas
        pandas.set_option('display.max_rows', 250)
        pd.set_option('display.float_format',str)
    except:
        pass
pandas_thread = threading.Thread(target=configure_pandas, daemon=True)
pandas_thread.start()

try:
    import readline
    def console():
        """
        Opens interactive console with current execution state.
        Call it with: `console.open(globals(), locals())`
        """
        frame = inspect.stack()[1].frame
        context = frame.f_globals.copy()
        context.update(frame.f_locals)
        readline.set_completer(rlcompleter.Completer(context).complete)
        readline.parse_and_bind("tab: complete")
        shell = code.InteractiveConsole(context)
        # the invisible characters here seem to mess up certain
        # operations
        # sys.ps1 = '\u001b[34;1m>>> \u001b[0m'
        sys.ps1 = '>>> '
        shell.interact(banner="<<--------------CONSOLE---------------->>", exitmsg="bye")
except:
    pass

# thanks https://stackoverflow.com/questions/22373927/get-traceback-of-warnings
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):

    log = file if hasattr(file,'write') else sys.stderr
    traceback.print_stack(file=log)
    log.write(warnings.formatwarning(message, category, filename, lineno, line))

warnings.showwarning_orig = warnings.showwarning
warnings.showwarning = warn_with_traceback
