"""Diagnose: why is KSampler on CPU?"""
import paramiko

k = paramiko.Ed25519Key.from_private_key_file(r'C:\Users\fabia\.ssh\id_ed25519')
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('192.168.178.150', username='fabian', pkey=k, timeout=10)
sftp = c.open_sftp()

print("=== LOG (meaningful) ===")
with sftp.open('/tmp/comfyui.log', 'r') as f:
    log = f.read().decode(errors='replace')
for line in log.split('\n'):
    s = line.strip()
    if not s or 'FETCH' in s or 'startup tasks' in s or 'DEPRECATION' in s:
        continue
    print(s)

print("\n=== LAUNCHER ===")
for p in ['/tmp/run_comfyui.sh', '/home/fabian/start_comfyui.sh']:
    try:
        with sftp.open(p, 'r') as f:
            print(f"--- {p} ---")
            print(f.read().decode())
            break
    except: pass

print("\n=== PROCESS ===")
chan = c.get_transport().open_session()
chan.settimeout(10)
chan.exec_command('/bin/bash -c "ps aux | grep main.py | grep -v grep"')
o = b""
while True:
    try:
        ch = chan.recv(65536)
        if not ch: break
        o += ch
    except: break
chan.close()
print(o.decode(errors='replace'))

print("=== GPU SPEED TEST ===")
ts = '#!/bin/bash\nexport HSA_OVERRIDE_GFX_VERSION=10.1.0\nexport HIP_VISIBLE_DEVICES=0\nexport HSA_ENABLE_SDMA=0\nsource ~/comfyui-env/bin/activate\npython3 -c "\nimport torch,time\nprint(\"CUDA:\",torch.cuda.is_available())\nif torch.cuda.is_available():\n  print(\"Dev:\",torch.cuda.get_device_name(0))\n  x=torch.randn(2048,2048,device=\"cuda\",dtype=torch.float16)\n  torch.cuda.synchronize()\n  t=time.time()\n  for _ in range(10): y=x@x\n  torch.cuda.synchronize()\n  gt=time.time()-t\n  x2=torch.randn(2048,2048,dtype=torch.float16)\n  t=time.time()\n  for _ in range(10): y=x2@x2\n  ct=time.time()-t\n  print(f\"GPU:{gt:.3f}s CPU:{ct:.3f}s Ratio:{ct/gt:.1f}x\")\n"\n'
with sftp.open('/tmp/gtest.sh', 'w') as f:
    f.write(ts)
sftp.close()
chan = c.get_transport().open_session()
chan.settimeout(60)
chan.exec_command('/bin/bash /tmp/gtest.sh')
o = b""
while True:
    try:
        ch = chan.recv(65536)
        if not ch: break
        o += ch
    except: break
chan.close()
print(o.decode(errors='replace'))

c.close()
