# disable ~/.python_history
del sys.__interactivehook__
# ----------------------------------------------------------------------------
import logging

try:
    # if rich is in the current venv/whatever...
    from rich import pretty
    # ...install its pretty printer.
    pretty.install()
except ModuleNotFoundError:
    # just carry on if rich isn't installed.
    pass

def dev_log_all():
    """Set up the REPL to log everything down to DEBUG level."""
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    stream = logging.StreamHandler(sys.stdout)
    stream.setLevel(logging.DEBUG)
    log.addHandler(stream)
# ----------------------------------------------------------------------------
try:
    from ptpython.repl import embed
except ImportError:
    print("ptpython is not available: falling back to standard prompt")
else:
    sys.exit(embed(globals(), locals()))
# ----------------------------------------------------------------------------
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Set an environment variable to point to it:  "export PYTHONSTARTUP=foo"
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full
# path to your home directory.

# Default imports for easier repl usage
import glob, fnmatch, re, os.path, pathlib, sys, subprocess  # noqa

def _main():
    import atexit
    import readline

    path = os.path.expanduser("~/.pyhistory")
    if os.path.exists(path):
        readline.read_history_file(path)

    try:
        import __builtin__
    except ImportError:
        import builtins as __builtin__

    setattr(__builtin__, "true", True)
    setattr(__builtin__, "false", False)
    setattr(__builtin__, "null", None)

    def save_history():
        import readline

        readline.write_history_file(path)

    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind(r"\C-a: beginning-of-line")
    readline.parse_and_bind(r"\C-e: end-of-line")
    atexit.register(save_history)

if __name__ == "__main__":
    _main()
# ----------------------------------------------------------------------------
# https://overflow.adminforge.de/exchange/unix/questions/630642/change-location-of-python-history#740971
# xdg-ninja uses (pasting here for convenience):
# export environment variable:
#   export PYTHONSTARTUP="/etc/python/pythonrc"
# create /etc/python/pythonrc:

import os
import atexit
import readline
from pathlib import Path

if readline.get_current_history_length() == 0:
    state_home = os.environ.get("XDG_STATE_HOME")
    if state_home is None:
        state_home = Path.home() / ".local" / "state"
    else:
        state_home = Path(state_home)

    history_path = state_home / "python_history"
    if history_path.is_dir():
        raise OSError(f"'{history_path}' cannot be a directory")

    history = str(history_path)

    try:
        readline.read_history_file(history)
    except OSError:  # Non existent
        pass

    def write_history():
        try:
            readline.write_history_file(history)
        except OSError:
            pass

    atexit.register(write_history)
# ----------------------------------------------------------------------------
import os
import atexit
import readline

history = os.path.join(os.path.expanduser('~'), '.local/state/python_history')
try:
    readline.read_history_file(history)
except OSError:
    pass

def write_history():
    try:
        readline.write_history_file(history)
    except OSError:
        pass

atexit.register(write_history)
# ----------------------------------------------------------------------------
import readline
import os

HISTORY_FILE = os.path.expanduser('~/.repl_history')
if os.path.exists(HISTORY_FILE):
    readline.read_history_file(HISTORY_FILE)

while True:
    try:
        line = input('> ')
        readline.write_history_file(HISTORY_FILE)
        print(sum([int(n) for n in line.split()]))
    except ValueError as e:
        print('error:', e)
    except (KeyboardInterrupt, EOFError):
        break
# ----------------------------------------------------------------------------
# # from pprint import pprint as p
# import pprint
# import json
# import urllib as u
# import base64
# import datetime
# import itertools
# import pdb
# import random
# import string
# import time
# # import yaml
# # from dateutil.tz import tzutc
# # import tzutc
# # true = True
# # false = False
# # null = None

# coloured prompt for older Python versions
if os.getenv("TERM") in (
    "xterm-256color",
    "screen-256color",
    "tmux-256color",
    "xterm",
    "screen",
    "tmux",
    "rxvt",
    "putty",
    "Eterm",
    "vt100",
):
    if sys.version_info < (3, 13):
        try:
            import readline
        except ImportError:
            pass
        else:
            sys.ps1 = "\001\033[0;32m\002>>> \001\033[0m\002"
            sys.ps2 = "\001\033[0;32m\002... \001\033[0m\002"
    else:
        # to change the colors for CPython 3.13+ I must not use \001 \002 or
        # it will crash: https://github.com/python/cpython/issues/118835
        sys.ps1 = "\033[0;32m>>> "
        sys.ps2 = "\033[0;32m... "
# ----------------------------------------------------------------------------
import importlib
def reimport(module_name):
    # import importlib
    """
    re imports a module.
    """
    importlib.reload(sys.modules[module_name])


if "XDG_DATA_HOME" in os.environ:
    history = os.path.join(
        os.path.expanduser(os.environ["XDG_DATA_HOME"]), "python", "python_history"
    )
elif "PYTHONHISTFILE" in os.environ:
    history = os.path.expanduser(os.environ["PYTHONHISTFILE"])

else:
    history = os.path.join(os.path.expanduser("~"), ".python_history")

# history = os.path.abspath(history)
# _dir, _ = os.path.split(history)
# os.makedirs(_dir, exist_ok=True)

try:
    import readline
except ImportError:
    sys.stdout.write("Module readline not available.\n")
else:
    import rlcompleter

    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind(r"\C-a: beginning-of-line")
    readline.parse_and_bind(r"\C-e: end-of-line")
    readline.parse_and_bind(r'"\C-xd": dump-functions')
    del readline, rlcompleter
# ----------------------------------------------------------------------------
# histfile = os.path.join(os.environ["XDG_STATE_HOME"], "python_history")
# try:
#     readline.read_history_file(histfile)
# except FileNotFoundError:
#     pass
# atexit.register(readline.write_history_file, histfile)
# atexit.register(readline.write_history_file, history)
# ----------------------------------------------------------------------------
def init_history(self, histfile):
    readline.parse_and_bind("tab: complete")
    if hasattr(readline, "read_history_file"):
        try:
            readline.read_history_file(histfile)
        except FileNotFoundError:
            pass
        atexit.register(self.save_history, histfile)

try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(100)
except FileNotFoundError:
    pass
atexit.register(readline.write_history_file, histfile)

class CustomCompleter(rlcompleter.Completer):
    def complete(self, text, state):
        if text == "":
            # You could replace \t to 4 or 8 spaces if you prefer indent via spaces
            return ['    ', None][state]
        else:
            return rlcompleter.Completer.complete(self,text,state)

# you could change this line to bind another key instead tab.
readline.set_completer(CustomCompleter().complete)
readline.parse_and_bind("tab: complete")
del CustomCompleter
