"""Run export-datasheets.js --dry-run --serial for a known SCMHVAS record.

Pick a serial that's guaranteed in the DB (from HVAS-M01.DAT samples we
pulled earlier: 179379-1 SCMHVAS-M0100).
"""
import base64, subprocess, yaml, paramiko

TEST_SERIALS = ['179379-1', '179379-2', '168630-9']

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:
    # Confirm serials are in the DB
    print('=== DB presence check ===')
    serials_list = "','".join(TEST_SERIALS)
    sql = f"SELECT serial_number, model_number, log_type, test_date, overall_result, forweb_exported_at FROM test_records WHERE serial_number IN ('{serials_list}') ORDER BY serial_number;"
    out, err, rc = ps(c, f'cd C:\\Shares\\testdatadb; & node -e "const db=require(\'./database/db\');(async()=>{{const r=await db.query(`{sql}`);console.log(JSON.stringify(r,null,2));await db.close();}})();"')
    print(out[:3000])
    if err: print('STDERR:', err[:500])

    # Dry-run export for first serial
    sn = TEST_SERIALS[0]
    print(f'\n=== Dry-run export for {sn} ===')
    out, err, rc = ps(c, f'cd C:\\Shares\\testdatadb; & node database/export-datasheets.js --dry-run --serial {sn}', to=120)
    print(out[:3000])
    if err: print('STDERR:', err[:500])
finally:
    c.close()
