import subprocess
import os 

from tinput import tinput_init, tinput 
from tnz import * 

HOME_PATH = os.path.expanduser("~")
DSH_PATH  = os.path.dirname(os.path.abspath(__file__))





def exeCmd(s2='' ):

    global cwd 

    interactive_cmd = ['nano', 'vim', 'top', 'htop', 'koed', 'less']
    tokens      =  tnz_cstr(s2)
    _type, cmd  = tokens[0]
    args        = [_[1] for _ in tokens  ]


    ################################################
    #this protect again accidentally delete system 
    if cmd in ['rm','rmdir']:
        print('02.92: Error/exeCmd(): this cmd block to protect accidentally delete system ')
        return 
    
    #check cmd in alias
    #if alias_cmd := d('get', '$alias/'+cmd):
    #    print('02.97: : ALIAS_CMD:',  alias_cmd)
    #    s2 = alias_cmd +' '+ arg_str 
    

    
    
    
    
    print('75:', s2 )
    print('76:', cmd, tokens )
    
    if   s2[0] == '=' : return eval(s2[1:].replace('^','**')) #utility/calc 

    #path 
    elif _type == '/' : return cd(cmd)              #change dir 
    elif cmd == '~'   : return cd('~')              #change dir 
    elif cmd == 'cd'  : return cd(args[-1])          #change dir 
    elif cmd == 'pwd' : return os.getcwd()         #present working dir 
    elif cmd == 'cwd' : return os.getcwd()         #current working dir     

    #elif cmd == 'qr'      : return k_qr(s2[3:])        #create qr win 
    #elif cmd == 'd'       : return d(  *raw_args[1:])  #d( get|set|has|list, key, value)     
    #elif cmd == 'mktpp'   : return tpp(*raw_args)      #tpp(mktpp, key, value)
    #elif cmd == 'tpp'     : return tpp(*raw_args)      #tpp(flag, key, value)
    #elif cmd == 'share'   : return shareFile(s2[6:])   #share file by internet 
    elif cmd == 'tnz'     : return tnz_fprint(args[-1], tokens) #print txt
    #elif cmd == 'dir'     : args = [d('get', '.dir'), args[-1]]     
    

    try:
            
        #tokens = parse_s2(cmd_str or s2, 'cmd')
        #print(f"02.210: {args}")
        
        if args[0] in interactive_cmd:  ## Run non-interactive commands
            subprocess.run(args)

        elif args[-1] == '&' :  #run in background
            process = subprocess.Popen(
                args[:-1], 
                stdout=subprocess.PIPE, 
                stderr=subprocess.PIPE
            )        
        
        else:   # Run non-interactive commands
            result = subprocess.run(args, check=True, text=True, capture_output=True)
            return result.stdout
                

    except KeyboardInterrupt:
        print("\nProcess interrupted.")

    except subprocess.CalledProcessError as e:
        print(f"02.229: Error in command: {tokens}\nReturn code: {e.returncode}\nOutput: {e.output}\nError: {e.stderr}")
        return None  # or return a default value/message
    
    except Exception as e:
        print(f"02.232: Unexpected error in command: {tokens}\nError: {e}")
        return None  # or return a default value/message    
    

kv = {
    'log_file': HOME_PATH+ '/v2sys/data/dsh.log',
    'zhist'   : HOME_PATH+ '/v2sys/data/dsh-zhist.zls',
    'PHIST'   : HOME_PATH+ '/v2sys/data/dsh-phist.zls',
    'LS_C'    : [],

}
tinput_init(kv)
while 1: 


    s2 = tinput('> ')
    if not s2: continue 
    r = exeCmd(s2)
    if r:
        
        print('108: output:', '*'*32)
        print(r)