"""Pull the plain-decimal-derived datasheet (SN 66260-12) for visual check."""
import base64, os, subprocess, yaml, paramiko

LOCAL_OUT = r'D:\claudetools\projects\dataforth-dos\datasheet-pipeline\scmvas-hvas-research\samples\backfill-verify'
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=60):
    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, banner_timeout=45, look_for_keys=False, allow_agent=False)
try:
    tmp_dir = 'C:/Users/sysadmin/Documents/verify'
    ps(c, f'New-Item -ItemType Directory -Force -Path "{tmp_dir}" | Out-Null')
    sn = '66260-12'
    ps(c, fr'Copy-Item -LiteralPath "\\ad2\webshare\For_Web\{sn}.TXT" -Destination "{tmp_dir}\{sn}.TXT" -Force')
    sftp = c.open_sftp()
    local = os.path.join(LOCAL_OUT, f'{sn}-plain.TXT')
    sftp.get(f'{tmp_dir}/{sn}.TXT', local)
    sftp.close()
    with open(local, 'rb') as f: data = f.read()
    print(f'size={len(data)} bytes')
    print(data.decode('utf-8','replace'))
    ps(c, fr'Remove-Item -LiteralPath "{tmp_dir}" -Recurse -Force')
finally:
    c.close()
