#!/usr/bin/env python3
import socket,sys,json,binascii
host=sys.argv[1]; port=int(sys.argv[2]) if len(sys.argv)>2 else 6379

def enc(*args):
    b=b'*'+str(len(args)).encode()+b'\r\n'
    for a in args:
        if isinstance(a,str): a=a.encode()
        b+=b'$'+str(len(a)).encode()+b'\r\n'+a+b'\r\n'
    return b

def read(f):
    line=f.readline()
    if not line: raise EOFError
    t=line[:1]; body=line[1:].rstrip(b'\r\n')
    if t==b'+': return body.decode('utf-8','replace')
    if t==b'-': return {'err':body.decode('utf-8','replace')}
    if t==b':': return int(body)
    if t==b'$':
        n=int(body)
        if n<0: return None
        d=f.read(n); f.read(2); return d
    if t==b'*':
        n=int(body)
        if n<0: return None
        return [read(f) for _ in range(n)]
    return body

def val(x):
    if isinstance(x,bytes):
        try: return x.decode('utf-8')
        except: return 'hex:'+x.hex()
    return x
s=socket.create_connection((host,port),timeout=5); f=s.makefile('rb')
def cmd(*a):
    s.sendall(enc(*a)); return read(f)
for c in [('PING',),('INFO','server'),('CONFIG','GET','dir'),('CONFIG','GET','dbfilename'),('DBSIZE',),('KEYS','*')]:
    try: print('CMD',c,'=>',val(cmd(*c)),flush=True)
    except Exception as e: print('ERR',c,repr(e),flush=True); break
try:
    ks=cmd('KEYS','*')
    if isinstance(ks,list):
        for k in ks[:200]:
            kb=val(k)
            print('KEY',repr(kb),flush=True)
            for c in [('TYPE',k),('TTL',k),('GET',k),('HGETALL',k),('SMEMBERS',k),('LRANGE',k,'0','20')]:
                try:
                    r=cmd(*c)
                    if r not in (None,[]) and not (isinstance(r,dict) and 'err' in r): print(' ',c[0],'=>',repr(val(r))[:4000],flush=True); break
                except Exception as e: pass
except Exception as e: print('DUMPERR',repr(e),flush=True)
