 # -*- mode: python -*-
$XONSH_SHOW_TRACEBACK=True
from datetime import datetime
from xonsh.prompt import gitstatus
from glob import glob
import re, json
import geoip2.database
import requests

# try:
#     _MY_IP = requests.get('https://api.ipify.org').text
# except requests.HTTPError:
#     print('Failed to retrieve public IP')
#     _MY_IP = None

# __open_weather_url = 'https://api.openweathermap.org/data/2.5/weather'
# if _MY_IP:
#     georeader = geoip2.database.Reader('/usr/share/GeoIP/GeoLite2-City.mmdb')
#     _MY_LOCATION = georeader.city(_MY_IP)
#     _MY_WEATHER = requests.get('{}?lat={}&lon={}'.format(
#         __open_weather_url,
#         _MY_LOCATION.location.latitude,
#         _MY_LOCATION.location.longitude)).json

_ORIG_PATH = list($PATH)
_ORIG_PROMPT = $PROMPT
$XONSH_HISTORY_SIZE='500000000000 commands'
$XONSH_SHOW_TRACEBACK=True
$XONSH_AUTO_PAIR=True
$XONSH_DATETIME_FORMAT='%Y-%m-%dT%H:%M:%S'
$CASE_SENSITIVE_COMPLETIONS = False
$PATH.append('/home/tmacey/.local/bin')
$PATH.append('/home/tmacey/.cargo/bin')
$ALTERNATE_EDITOR=""
$EDITOR="emacsclient -t"                  # $EDITOR opens in terminal
$VISUAL="emacsclient -c -a emacs"         # $VISUAL opens in GUI mode
$THREAD_SUBPROCS=False

GEM_DIR = $(ruby -e 'puts Gem.user_dir').strip('\n')
$PATH.insert(0, f'{GEM_DIR}/bin')
$GEM_PATH=GEM_DIR
$GEM_HOME=GEM_DIR

if glob('/tmp/ssh-*/agent.*'):
    $SSH_AUTH_SOCK=glob('/tmp/ssh-*/agent.*')[0]
else:
    $[ssh-agent]
    $SSH_AUTH_SOCK=glob('/tmp/ssh-*/agent.*')[0]

__identities_loaded = $(ssh-add -l)
if __identities_loaded.strip()  == 'The agent has no identities.':
    print("Adding ssh identities")
    $[ssh-add ~/.ssh/id_rsa]
    $[ssh-add ~/.ssh/odl_rsa]
    $[ssh-add ~/.ssh/odl_app]

def _current_time():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

__return_code_map = {
    1: 'Error',
    2: 'Misuse of shell builtins',
    126: 'Command invoked cannot execute',
    127: 'Command not found',
    128: 'Invalid argument to "exit"',
    255: "Exit status out of range"
}
__kill_codes = re.findall(r'\d{1,2} \w+', $(kill -L))
for code in __kill_codes:
    code_val, code_name = code.split(' ')
    __return_code_map[128 + int(code_val)] = "Process terminated by SIG{}".format(code_name)

def _return_code_output():
    try:
        return_code = __xonsh__.history.rtns[-1]
        if len(__xonsh__.history.rtns) > 1:
            previous_return = __xonsh__.history.rtns[-2]
        else:
            previous_return = 0
    except IndexError:
        return ''
    if return_code != 0:
        code_description = __return_code_map.get(return_code, '')
        prompt_string = '{{BOLD_RED}}(╯°□°）╯︵ ┻━┻ {} {} '.format(return_code, code_description)
    elif return_code == 0 and previous_return != 0:
        prompt_string = '{BOLD_GREEN}┬─┬ノ( ◕◡◕ ノ)'
    else:
        prompt_string = ''
    return prompt_string


$PROMPT_FIELDS['current_time'] = _current_time
$PROMPT_FIELDS['gitstatus'] = gitstatus.gitstatus
$PROMPT_FIELDS['exit_status'] = _return_code_output
$PROMPT_FIELDS['prompt_end'] = '\u21C9'
$PROMPT = ('\n\u256D-{env_name:{} }{BOLD_YELLOW}{user}{WHITE}@{BOLD_RED}{hostname}{BOLD_BLUE} '
           '{cwd} {branch_color}{gitstatus}{RESET} '
           '\n\u2570-{BOLD_BLACK}{BACKGROUND_WHITE} {current_time} {RESET} '
           '{BOLD_BLUE}{exit_status}{prompt_end}{RESET} ')

def ssh_host_completer(prefix, line, begidx, endidx, ctx):
    if not line.startswith('ssh ') or re.search(r' ?-{1,2}\w*?$', line):
        return None
    hostlist = []
    host_prefix = prefix.split('@')[-1]
    with open("{}/.ssh/known_hosts".format($HOME), 'r') as known_hosts:
        for hostline in known_hosts:
            namelist = hostline.split(' ')[0]
            hostlist += namelist.split(',')
    prefix_length = len(host_prefix)
    return (set([target for target in hostlist if host_prefix in target]), prefix_length)

completer add ssh ssh_host_completer

def _to_bytes(what):
   if isinstance(what, bytes):
       return bytes
   else:
       return str.encode(what)

def _write_bytes(what):
   sys.stdout.buffer.write(what)

def compute_pulumi_saas_cost():
     resources = json.loads($(pulumi -C /home/tmacey/code/mit/ops/infra/ol_infrastructure/src/ol_infrastructure/applications/edxapp/ stack ls -a -j))
     count = 0
     for x in resources:
         count += x.get("resourceCount", 0)
     print((count * 24 * 30 - 150000) * 0.00025)


aliases['hex_encode'] = lambda a,i=None: _write_bytes(binascii.hexlify(_to_bytes(i.strip() or a[0])) + b'\n')
aliases['hex_decode'] = lambda a,i=None: _write_bytes(binascii.unhexlify(_to_bytes(i.strip() or a[0])) + b'\n')
aliases['cat'] = 'bat'
aliases['et'] = "emacsclient -t -nw"
aliases['pyright-install'] = "/usr/bin/npm -g --prefix /home/tmacey/.emacs.d/.cache/lsp/npm/pyright install pyright"

xontrib load vox
#xontrib load pyenv
xontrib load avox_poetry
