"""Actually export one SCMHVAS datasheet and pull it back for visual check."""
import base64, subprocess, yaml, paramiko, os

TEST_SN = '179379-1'
LOCAL_OUT = r'D:\claudetools\projects\dataforth-dos\datasheet-pipeline\scmvas-hvas-research\samples\live-export'
os.makedirs(LOCAL_OUT, exist_ok=True)

def pwd():
    r = subprocess.run(['sops','-d','D:/vault/clients/dataforth/ad2.sops.yaml'],
                       capture_output=True, text=True, timeout=30, check=True)
    return yaml.safe_load(r.stdout)['credentials']['password'].replace('\\','')

def ps(c, cmd, to=120):
    enc = base64.b64encode(cmd.encode('utf-16-le')).decode()
    stdin, stdout, stderr = c.exec_command(f'powershell -NoProfile -EncodedCommand {enc}', timeout=to)
    return stdout.read().decode('utf-8','replace'), stderr.read().decode('utf-8','replace'), stdout.channel.recv_exit_status()

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('192.168.0.6', username='sysadmin', password=pwd(), timeout=30, look_for_keys=False, allow_agent=False)
try:
    print(f'=== Live export for {TEST_SN} ===')
    out, err, rc = ps(c, f'cd C:\\Shares\\testdatadb; & node database/export-datasheets.js --serial {TEST_SN}', to=120)
    print(f'[rc={rc}]')
    print('--- STDOUT ---')
    print(out)
    if err.strip():
        print('--- STDERR ---')
        print(err[:2000])

    print(f'\n=== SFTP pull X:\\For_Web\\{TEST_SN}.TXT ===')
    sftp = c.open_sftp()
    try:
        src = f'X:/For_Web/{TEST_SN}.TXT'
        dst = os.path.join(LOCAL_OUT, f'{TEST_SN}.TXT')
        sftp.get(src, dst)
        print(f'[OK] pulled {src} -> {dst}')
        print(f'[INFO] size={os.path.getsize(dst)} bytes')
    finally:
        sftp.close()
finally:
    c.close()
