import os
import sys 
import tty
import termios
import subprocess
from datetime import datetime

from tnz import *
from quickSearch import *

"""
#var 
    s0 = s1+s2+s3 
        s0  //print_line 
        s1  //prefix 
        s2  //usr input string 
        s3  //history base line 

    c       //char 
    s2_len = 0  reinit ls
    s2_len = -1 redraw ls 

    ci = 0  //cursor position in s2 
    li = 0  //sugg index 
    hi = 0  //history index 

#key_binding 
    key 


    k-H:    ci = 0          //move cursor to start
    k-E:    ci = len(s2)    //move cursor to end     

    k-b:    s2 = s2[:ci-1]+    s2[ci:]; ci -= 1  //remove char
    K-D     s2 = s2[:ci]  +    s2[ci+1:]         //delete char 
    k-p:    s2 = s2[:ci]  +c  +s2[ci:]; ci+=1    //add print char
    k-s:    s2 = s2[:ci]  +' '+s2[ci:]; ci+=1    //add space char

    C-x     s2 = ''
    ctrl+x      cut string 
    arrow-left   ci -= 1
    arrow-right  ci += 1
        


#fn tinput(s1)
    //key


    
    
    
    switch(key_code)

        
    
        k-n: key_enter  

        //tab base 
        k-t:
            sugg_len = len(sugglist)

            (sug_len == 1): s2  = s2_tab(s2)          //auto_complete 
            (li < sug_len): li += 1; print_ls()    //next_sugg
            (sug_len     ): li  = 0; print_ls(li)  //zero_sugg
            else        : sugg(s2,ci )             //init sugg

        //control arrow 
        C-al: 
        c-ar:   //
        C-au:   //pre search word 
        C-ad:   //next search word 
        C-H:    //jump  to start
        C-E:    //jump to end 
        C-x:    //clear line|cut str  

        k-ar and ls_h
        k-ar    //cursor move right 
        k-al    //cursor move left 
        

        //ls_h|ls
        k-au 
        k-ad 
    //reset cursor if ou of range 
    if   ci < 0: ci=0
    elif ci == len(s2): 
"""

"""
    
    k-  key     t|n|sb
    a-  arrow_key [u|d|l|r]
    p-  print_key 
    F   Function
    S-  shift 
    C-  ctrl_key  

"""

#tinput global 
terminal_size   = os.get_terminal_size()
t_width  = terminal_size.columns
t_height = terminal_size.lines

suggDict={
    '!':[
        'f'  ,'F'  ,'b'
        'x'  ,'y'  ,'w'   , 'h' , 
        'x!' ,'y!' ,'w!'  , 'h!', 
        'Mr' ,'Br' ,'Pd'  , 'Rd',
        '_'  ,'ly' , 'aId', 'bId',
    ]

}
arg_query = ''
arg_view  = ''
arg_path  = ''

#LS const list, ls active list 
LS_TYPE          = ''   #line|ls|col 
LS  , ls  , li   = [], [], 0        #list sugg 
LS_H, ls_h, hi   = [], [], 0        #list history
LS_C, ls_c, li_c = [], [], 0        #list of cmd 

CWD         = os.getcwd()
LOG_FILE    = 'dsh.log'
HOME_DIR    = '/home/rpi'
ZFS_DIR     = '/home/rpi/ZFS'
ZHIST       = None #z-history
#PHIST      = None #open path|link history 
PHIST       = None #path history use in >cd or recent file 
PHIST_PATH  = ''

d        = {
    '.dir': 'pcmanfm ',
    '/': 'pcmanfm ', 
    '.jpg':'',
    
    '.link': 'chromium ', 
    'http'  :'chromium ', 
    'https' :'chromium ', 
    'http'  :'chromium --incognito', 
    'https' :'chromium --incognito', 

}

def get_key():
    key_code = ''
    char = sys.stdin.read(1)
    #print(f"27: \033[2K\rHex code1: {char.encode('utf-8').hex()}")
    #print('59:', char)
    if   char == '\x1c': sys.exit()        #kill()       # ctrl+\
    elif char == '\x18': key_code = 'C-x'  # ctrl-x     
    elif char == '\x09': key_code = 'k-t'  # \t tab
    elif char == '\x0d': key_code = 'k-n'  # \n new line
    elif char == ' '   : key_code = 'k-s'  # \s space
    elif char in ['\x08','\x7f'] : key_code = 'k-b'  # \b Backspace
        
            
    elif char == '\x1b':  # Escape
        char = sys.stdin.read(2)
        if char in ['[2', '[3', '[5', '[6']:
            c = sys.stdin.read(1)
            if c == ';':
                char += c+sys.stdin.read(2)
            #print('73:', char)

        if char == '[1':   char += sys.stdin.read(3)
        #print('  >>75:', char)

        """num pad use for better 
            789  home  up  insert
            456  left  0   right
            123  end   down delete
            also reserve in E7 coding
        """
        #keys 
        if   char == '[2': key_code = 'k-I' #Insert
        elif char == '[3': key_code = 'k-D'  #Delete
        elif char == '[5': key_code = 'p-U'  #page up
        elif char == '[6': key_code = 'p-D'  #page down
        elif char == '[H': key_code = 'k-H'  # Home
        elif char == '[F': key_code = 'k-E'  # End
        
        #arrow keys 
        elif char == '[A': key_code = 'a-u'  #arrow-up
        elif char == '[B': key_code = 'a-d'  #arrow-down 
        elif char == '[C': key_code = 'a-r'  #arrow-right
        elif char == '[D': key_code = 'a-l'  #arrow-left

        #ctrl-arrow keys 
        elif char == '[1;5H': key_code = 'C-H'  #home
        elif char == '[1;5F': key_code = 'C-E'  #end
        elif char == '[3;5~': key_code = 'C-D'  #arrow-up
        elif char == '[1;5A': key_code = 'C-u'  #arrow-up
        elif char == '[1;5B': key_code = 'C-d'  #arrow-down 
        elif char == '[1;5C': key_code = 'C-r'  #arrow-right
        elif char == '[1;5D': key_code = 'C-l'  #arrow-left
        
        

        #shift-arrow keys 
        elif char == '[1;2A': key_code = 'S-u'  #shift-arrow-up
        elif char == '[1;2B': key_code = 'S-d'  #shift-arrow-down 
        elif char == '[1;2C': key_code = 'S-r'  #shift-arrow-right
        elif char == '[1;2D': key_code = 'S-l'  #shift-arrow-left
        elif char == '[OM'  : key_code = 'S-n' # shift+\n use for muliline
            
        #F1 keys 
        elif char == '[OP': key_code = 'F1' # F1
        elif char == '[OQ': key_code = 'F2' # F2
        elif char == '[OR': key_code = 'F4' # F3
        elif char == '[OS': key_code = 'F4' # F4
            
        else: key_code == 'k-e' 

    else:
        key_code = f'{char}_'

    #print('160:', key_code)
    return  key_code


def hist_load( s2=''):
    global LS_H 
    global ls_h 

    # create  file if not exit 
    if not os.path.isfile(LOG_FILE):
        # Create the file
        with open(LOG_FILE, 'w') as file:
            pass
        return 

    #content = file_('read',log_file)
    with open( LOG_FILE, 'r') as file:
        content = file.read()


        #read line in reverse order 
    for line in reversed(content.split('\n')):
        item = line.split(';', 1)[-1].strip()
        #if line already load than escape  
        if item and item  not in LS_H:
            LS_H.append(item)
            
            #max ls_h length 
        if len(LS_H)>1024: return


def hist_append( s2=''):
    global LS_H

    #-view data also add in log entry 
    log_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"{log_time};  {s2}\n"
    #file_('append', log_file, log_entry)   #save in log file 
        
    with open( LOG_FILE, 'a') as file:
        file.write(log_entry)
    LS_H.insert(0, s2)


def sugg(s2,  ci=None):
    global LS 
    global ls
    global LS_TYPE

    r = []
    
    tokens = tnz_cstr(s2)
    if not tokens:
        return r 
    _    , cmd    = tokens[0] 
    _type, _value = tokens[-1]
    if _type == ' ':
        _type  =  '->'      #list of next token
        _value =  tokens[-2][1]
        

    #print_arr('240:', tokens, '\r\n')
    #print('240:', _type,  _value, end='\r\n')
    #print('\r234: sugg',_type, _value,'\r' )
    #if _type=='>': 
    #    r = (subprocess.run(['compgen', '-c'], capture_output=True, text=True, check=True)).stdout.splitlines()
    
    #list of entry 
    
    if _type=='/':
        #get ls of entry in dirPath 
        if _value.endswith('/'): 
            #print('247:')
            #s = _value.split('/')[-1]
           
            if _value[0] == '~': path = HOME_DIR + _value[1:]
            else               : path = _value

            if os.path.isdir(path):

                ls0, ls1 = [], []
                for _ in os.listdir(path):
                    if os.path.isdir(path+'/'+ _): ls0.append(_+'/')
                    else                         : ls1.append(_)
                r = sorted(ls0) + sorted(ls1)
            LS =  r    
        

            #print('276:', s)

    elif _value.startswith('t/'): LS = qs_sugg(PHIST, '.zt',      _value, -1)
    elif _value.startswith('@') : LS = qs_sugg(PHIST, 'd'  , 'z/'+_value, -1)
    elif _type == '>'           : LS  = LS_C

    elif _type == '~' : 
        
        if cmd=='cd' : _type = 'd'
        if cmd=='tnz': _type = '.'
        if cmd=='zz' : _type = '.'
        #print('309:', cmd, _type, _value)
        LS = qs_sugg(PHIST, _type, _value[1:], -1)

    #elif _value.startswith('u/'):   v = s2[2:]
    #elif _value.startswith('u/'):   v = s2[2:]
    #elif _value.startswith('u/'):   v = s2[2:]
    
    #elif s2.startswith('open '): LS = PHIST.sugg(_value); ls = LS
    #elif s2.startswith('z ')   : LS = ZHIST.sugg(_value); ls = LS
        
            
    elif _value == 'z!':
        
        z = globals().get('z')
        print('288:', z)
        if not z: return
        LS = [k for k in Z.keys() if k[0]=='!']
    
    elif _type == '&':
        LS = [
            '&page'  , '&pageSize',
            '&print' , '&sort',
            '&import', '&export', '&save',
        ]
          
    #print('344:', LS)
    LS_TYPE = 'ls'
    #if LS empty than clear screan
    #if len(LS)==0: ls = []; print('\033[J' ,end='', flush=True )
    return LS


def print_ls( ci, dir='a-d'):
    global k_win 

    if not ls: return   ## Exit early if list is empty
    
    
    lines    = ls    
    list_len = len(lines)
    max_show = min(t_height - 2, 24, list_len)      #set max suggestion list show 
    
    # Update current index (ci) only if a new index (li) is provided
    # Calculate start index (si) ensuring it doesn't go below 0
    # This creates a "scrolling" effect as ci increases
    # Calculate end index (ei) based on the start and the view limit
    ci = li if li else ci
    si = max(0, ci - max_show + 1)
    ei = si+max_show
    


    content = []

    #header line show 
    if 'H' in arg_view:
        content.append(lines[0])
        si += 1
        ci +=1
        
        ei = si+max_show-1

    #wrap line width so layout
    for line in lines[si:ei]:
        if len(line) > t_width-5:
            content.append(line[:t_width-5])
        else:
            content.append(line)
    #print('266',content)



    tnz_config = {'ln':si, 'la':ci+1,'LF':'\r\n', 'config':'l_'}
    s = tnz_frame(tnz_str('\n'.join(content)), tnz_config , -1 )

    
    print((
        f'\033[{t_width-30}C\033[J'     #clear screan
        #'\033[7m' if 'H' in arg_view else ''
        f'\r\n{s}\033[0m'                          #print_str
        #f'\r\n[{ci+1}/{list_len}] '         #show number of item 
        f'\033[{max_show+1}A'           #cursor move up
        f'\n\r\033[{t_width-30}C'       #cursor move right 
    ),end='' ) #,'\033[D')
    return max_show


def s2_tab(s2, key=''):
    #sugges base word complete
    global li
    global ls
    global sugg_live
    

    #print('404:', s2 )
    #next word_complter
    if key=='C-r':
        _    = ls[li]
        i    = next((i+1 for i in range(len(s2), len(_)) if not _[i].isalnum()), len(_))
        _    = _[:i]

    else:
        _ = ls[li]


    args = s2.split()
    #if is_path(args[-1]) and args[-1][0] != '@' :
    #    args[-1] = f"{args[-1].rsplit('/', 1)[0]}/{_.lstrip('p/')}"
    #else:
    #    args[-1] = _


    li        = 0
    sugg_live = 0
    ls = []

    result = ' '.join(args) 
    #print('427:', result )

    return  result


def exec(cmd_str):
    try:
        #print('461:', cmd_str)
        # Run the command
        result = subprocess.run(cmd_str, shell=True, check=True, text=True, capture_output=True)    
        # Print the output
        #print("\r\nOutput:\r")
        #print(result.stdout)
        # Print any errors
        if not  result.stderr:
            return result.stdout
            #print("490: Errors:")
            #print(result.stderr)
         

    except subprocess.CalledProcessError as e:
        print(f"477: ERROR in cmd_str(): {e}")

    return None 


def tinput_init(kv={}):
    global LOG_FILE
    global LS_C  
    global ZHIST
    global PHIST
    global PHIST_PATH
    #global Z 
    #global z 

    LOG_FILE   = kv.get('log_file', 'tinput.log')
    LS_C       = kv.get('LS_C', [])   #list of cmds 
    zhistFile  = kv.get('zhist', 'zhist.zls')
    PHIST_PATH = kv.get('PHIST', 'PHIST.zls')
    #Z, z     = kv.get('Z', []), kv.get('z', [])   
    #for k,v in globals().items():
    #    print(f'439: {k:14}: {v}')

    print('459: LOG_FILE :', LOG_FILE)
    print('459: LS_C     :', LS_C)
    print('459: zhistFile:', zhistFile)

    hist_load()
    #ZHIST =  hscore(zhistFile)
    PHIST =  qs_load(PHIST_PATH)


def key_enter(s2 ):
    global LS
    global ls 
    global CWD 

    #tokens = tnz(s2)
    tokens  = tnz(s2)+[[' ', ' ']]
    if len(tokens)<2: return s2
    #print_arr('433:', tokens)
    ctokens = []
    si      = 0

    #init cmd tokens 
    for i in range(0, len(tokens)):
        
        if i!=0 and tokens[i][0] in '=&' : 
            value  = ''.join([_[1] for _ in tokens[si:i]]) 
            ctokens.append([_type, value])    
            #_type, _value = tokens[i] 
            #r.append([_type, value])
            si=i

            #if _type  == '/' and tokens[i-2] == '.' : ctokens.append(['.', tokens[i-1]])

        elif tokens[i][0] == ' ' : 
            _type, _value = tokens[si] 
            
            value  = ''.join([_[1] for _ in tokens[si:i]]) 
            #print('446:', si,i, _type,_value,  value)
            if si == 0 and _type == 'w': _type = '>' 
            elif _type  == '-' : _type = '-'
            elif _value == '--': _type = '--'
            elif _type  == '/' : _type = '/'
            elif _type  == '&' : _type = '&'
            elif _type  == '=' : _type = '='
            elif _type  == 's' : _type = 's'
        
            if _type != ' ':
                 ctokens.append([_type, value])
            #if _type  == '/' and tokens[i-2] == '.' : ctokens.append(['.', tokens[i-1]])


            ctokens.append([' ', tokens[i][1]])
            si=i+1
    

    _type0, cmd           = ctokens[0] 
    _type_nth, _value_nth = ctokens[-2]


    rel_path = '' 
    abs_path = ''               #absloute path set 
    abs_dir  = ''
    pathType = ''
    ###################################################
    #get abs_path 
    if 1: 
        #print('\r553:', _type_nth, _value_nth)
        #print('\r553:', ctokens[-2])

        # # # # if _type0 == '~' or _type0 == '/': cmd = 'cd'
        if   _value_nth == '~': abs_path =HOME_DIR; path = '~'
        elif _type_nth  == '/':
            rel_path = _value_nth
            if rel_path[0] == '~'       : abs_path =HOME_DIR+rel_path[1:]
            elif rel_path.startswith('..'): abs_path =os.path.abspath(rel_path)
            elif rel_path.startswith('.') : abs_path =os.path.abspath(rel_path)
            else                          : abs_path =rel_path
            
        if os.path.isdir(abs_path) : pathType= 'd'
        if os.path.isfile(abs_path): pathType= '.'


    hist_append(s2)
    if pathType:
        qs_update(PHIST, pathType, abs_path, PHIST_PATH)
        #PHIST.update(path)

    if pathType == 'd':
        abs_dir=abs_path
        #add in history 
    print('\r')
    

    if 0: #debug info
        print('\r543:',  _type0, cmd     )
        print('\r543:',  _type_nth, _value_nth )    
        print('\r572:  rel_path:', rel_path )
        print('\r572:  abs_path:', abs_path )
        print('\r572:  abs_dir :', abs_dir   )


    ###################################################
    
    #auto-complete 
    if li < len(ls) and s2[0] != '^' : s2 = s2.rsplit(' ')[0]+' '+ls[li];     

    elif s2[0] == '=' : print('\r\n', eval(s2[1:].replace('^','**')), end='\r\n'); s2='' #utility/calc 
    
    elif s2[0] == '^': 
        v = s2[1:].strip()

        #read txt file 
        if os.path.isfile(v): 
            with open(v, 'r') as file:
                r = file.read()          
        else:
            r = exec(v)

        if r: 
            lines = r.split('\n')
            #print('594:', r.replace('\n', '\r\n'))
            #print_arr('597:', lines, '\r\n')
            #print('594:', lines)
            LS, ls  = lines, lines  
            LS_TYPE = 'line'
            print_ls(0)           

    
    elif cmd == 'q'     : sys.exit();#exit progrram 
    elif cmd == 'tnz'   : tnz_fprint(abs_path); s2=''
    elif cmd == 'hist'  : tnz_fprint(LOG_FILE); s2=''
    elif cmd == 'db'    : print_kv('617:', PHIST, '\r\n')
    elif cmd == 'pwd'   : s = os.getcwd(); print('\r',s, '\r'); return ''
    elif cmd == 'cd':
        if abs_dir: 
            os.chdir(abs_dir); 
            CWD = os.getcwd()
        return ''
    

    elif cmd == 'open':

        if abs_dir:cmd = d.get('/')
        #PHIST.update(rel_path) #history 
        cmd += ' ' + abs_path 
        try:
            # Start the command in the background
            process = subprocess.Popen(cmd, shell=True)
            return process
        except FileNotFoundError:
            print("Command not found. Please check the command and try again.")
        except Exception as e:
            print(f"An error occurred while starting the command: {e}")
        


    else:
        return None

    return s2 



def tinput(s1=""): #ls_h = [],
    #print('147:', home_path)
    global LS 
    global ls
    global li  
    global ls_h 
    cwd  =  ''
    fd   = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    
    #load ls_h
    
    #print('628:', LS_H, ls_h )
    #print(f"\033[K\r"+s1, end="")
    
    
    
    s1 = f'{CWD.split('/')[-1]} > '
    print(f"\033[2K\r\033[1m\033[38;2;1;191;191m{s1}\033[0m",end='')
    
    ls_h = LS_H 
    
    try:
        tty.setraw(sys.stdin.fileno())
        #s  string 
        #s1 = '>'     #star str 
        sugg_live = 0
        s2, s3 = '', ''  #input string, end str
        ci, hi = 0 , 0   #cursor index |#ls_h index
        s2_len = 0
        #ls_h = []
        while 1:
            key_code   = get_key()
            if key_code == "": continue
            
            # key-home | key-end 
            elif key_code == 'k-H':  ci = 0
            elif key_code == 'k-E':  ci = len(s2)   

            # key-backspace | key-delete
            elif key_code == 'k-b' and ci > 0      : s2 = s2[:ci-1] + s2[ci:]; ci -= 1
            elif key_code == 'k-D' and ci < len(s2): s2 = s2[:ci] + s2[ci+1:]
            
            #######################################
            #  key-print char
            #######################################
            

            #key-add_char
            elif key_code[1] == '_'  : s2 = s2[:ci]+key_code[0]+s2[ci:]; ci+=1
            elif key_code    == 'k-s': s2 = s2[:ci]+' '        +s2[ci:]; ci+=1
            
            
            elif key_code == 'k-n':
                #r = key_enter(s2)
                #auto-complete token
                
                r = key_enter(s2)
                
                if r ==None:
                    #z-history 
                    if s2.startswith('z '):
                        v =s2.split(' ')[-1]
                        PHIST.update(v)
                    
                    #print('\r')
                    return s2 

                elif len(r)!=s2_len: 
                    s2       = r 
                    LS,ls,li = [],[],0
                



                #print('\r',end='')
            
            #########################################
            #key-tab                                #
            #########################################
            #key-tab ls show 
            elif key_code == 'k-t' and not ls:  #and len(ls):
                
                ls,li = sugg(s2,  ci), 0

                #ls = LS
                print_ls(0)
                
            elif key_code == 'k-t' and ls:  #and len(ls):
                #auto complete 
                if   len(ls) ==1: s2 = s2_tab(s2); ci = len(s2)    
                
                #next sugg 
                elif li<len(ls) : li += 1; 
                else            : li =0  ; 
                

            

            #######################################   
            # key-ctrl          
            #######################################
            #move ls next and previos dir 
            elif key_code in ['C-l', 'C-r'] and s2.startswith('ls ') and ls:


                if key_code == 'C-l': 
                    s2_len=0
                    os.chdir('..')
                    print('\r8.93', os.getcwd())
                    
                else: 
                    print('8.93:')

            #sugg[li].next_word
            elif key_code == 'C-r' and ls:
                
                s2 = s2_tab(s2, 'C-r')
                ci = len(s2)
            #s3.next_word 
            elif key_code == 'C-r' and s3:    
                i    = next((i+1 for i in range(ci, len(s3)) if not s3[i].isalnum()), len(s3))
                s2 = s3[:i]
                ci = len(s2)
                li = 0
            
            
            #s2.next_word  #s2.pre_word
            elif key_code == 'C-l' and ci >0 : ci = next((i+1 for i in range(ci-2, -1, -1) if not s2[i].isalnum()), 0)
            elif key_code == 'C-r'           : ci = next((i+1 for i in range(ci, len(s2)) if not s2[i].isalnum()), len(s2))
            elif key_code == 'C-x': ci,s2,s3 = 0,'','' #clear line 
            #sugg[0] li move to home | li move to end

            #find pre word 
            #elif key_code == 'C-u' and ls and match_lines: 
            #    for v in match_lines[::-1]:
            #        if v < li: 
            #            li=v 
            #            break
            #    print_ls(li)  
            #find next word 
            #elif key_code == 'C-d' and ls and match_lines:                
            #    for v in match_lines:
            #        if v > li: 
            #            li = v 
            #            break
            #    print_ls(li)  
            elif key_code == 'C-H' and ls: print_ls(li:= 0)
            elif key_code == 'C-E' and ls: print_ls( li:= len(ls)-1)
            
            

            #elif key_code.startswith('C-') and ls: 
            #    if key_ctrl(key_code, s2) == 'redraw': s2_len+=1

            #######################################
            # key-arror  
            #######################################       
            
            elif key_code == 'a-r' and len(s2) < len(s3): ci = len(s2:=s3) #h_sugg base complete
            elif key_code == 'a-r' and ci  < len(s2)    : ci += 1 #cursor move right
            elif key_code == 'a-l' and ci > 0           : ci -= 1 #cursor move left 
            
            #sugg  up|down 
            elif key_code == 'a-u' and ls and li>-1       :  li-= 1; 
            elif key_code == 'a-d' and ls and li<len(ls)-1:  li+= 1; 
                
            #ls_h up|down 
            elif key_code == 'a-u' and ls_h and hi < len(ls_h): hi += 1; 
            elif key_code == 'a-d' and ls_h and hi > 0        : hi -= 1; 



            #rename file
            #elif key_code == 'F2' and  and s2.startswith('ls ')
            #    path = ls[li].split()[-1]
            if s2.endswith(' '): ls, li, sugg_live = [], 0, 0
            if len(s2) == 0: hi=-1
            
            ls_h = [_ for _ in LS_H if _.startswith(s2)] if s2 else LS_H
            s3   = ls_h[hi] if -1 < hi < len(ls_h) and not s2.startswith('^') else ''
            
            #list search 
            if LS and s2:
                #print('820:')
                v      = (s2.split(' ')[-1]).lower()
                if LS_TYPE == 'ls' and key_code not in ['a-u', 'a-d', 'k-t']:
                    
                    

                    ls,li  = [], 0 
                    for s in LS:
                        if all(token in v.lower() for token in v.split('&')):
                            ls.append(s)
                
                #print('825:',ls, li )
                print_ls(li)  
            
            
            #print s2 
            if  s2_len != len(s2):
                
                #history sugg
                #ls_h = [item for item in LS_H if item.lower().startswith(s2.lower())]
                #if ls_h: s3 = ls_h[0]
                #else   : s3 = s2
                
                #print('\r163:', s2)
                if s2_len == 99: 
                    ci = len(s2)
                
                s2_len = len(s2)
                
                #ci reset if out of range 
                if ci > s2_len: ci = s2_len

                
                #print('614:', LS_H, ls_h)
                
                s1  = f'{CWD.split('/')[-1]} > '
                s0  = ""
                s0 += f"\033[2K\r\033[1m\033[38;2;1;191;191m{s1}\033[0m"            #clear line
                s0 += f"{tnz_frame(tnz_cstr(s2) , {'config':''},-1)}\033[0m"
                s0 += f"\033[37;2;200;200;200m"
                s0 += f"\033[{len(s1)+ci+1}G{s3[s2_len:]}"  #ls_h sugg
                s0 += f"\033[{len(s1)+ci+1}G\033[0m" #set cursor pos
                s0 +=  '\033[J' if len(s2)==0 else '' #Erases everything below the cursor
                print(s0, end="")           
            else:
                print(f"\r\033[{len(s1)+ci+1}G", end='') #set cursor pos

            #Erases everything below the cursor
            if len(s2)==0 or s2[-1] == ' ': print('\033[J' ,end='', flush=True )  
            
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)


def test():
    while 1:
        s = tinput('>')
        print(s)
    
#test()
