"""Inline generate one SCMHVAS datasheet on AD2 (no X: drive dependency)."""
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)

NODE_SCRIPT = r'''
const db = require('./database/db');
const { loadAllSpecs, getSpecs } = require('./parsers/spec-reader');
const { generateExactDatasheet } = require('./templates/datasheet-exact');

(async () => {
    const sn = process.argv[2];
    const rows = await db.query(
        "SELECT * FROM test_records WHERE serial_number = $1 ORDER BY test_date DESC LIMIT 1",
        [sn]
    );
    if (rows.length === 0) {
        console.error('[FAIL] no record for ' + sn);
        process.exit(1);
    }
    const record = rows[0];
    console.log('[INFO] record: model=' + record.model_number +
                ' log_type=' + record.log_type +
                ' date=' + record.test_date +
                ' status=' + record.overall_result);

    const specMap = loadAllSpecs();
    const specs = getSpecs(specMap, record.model_number);
    console.log('[INFO] specs: ' + (specs ? JSON.stringify(Object.keys(specs)) : 'null'));

    const txt = generateExactDatasheet(record, specs);
    if (!txt) {
        console.error('[FAIL] formatter returned null');
        process.exit(1);
    }
    console.log('[INFO] generated ' + txt.length + ' bytes');
    console.log('----- BEGIN DATASHEET -----');
    console.log(txt);
    console.log('----- END DATASHEET -----');
    await db.close();
})();
'''

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('\\','')

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:
    sftp = c.open_sftp()
    # Script must live inside testdatadb/ so relative requires resolve.
    remote_js = 'C:/Shares/testdatadb/_gen_one.js'
    with sftp.open(remote_js, 'w') as fh:
        fh.write(NODE_SCRIPT)
    sftp.close()

    cmd = f'cd C:\\Shares\\testdatadb; & node ./_gen_one.js {TEST_SN}'
    enc = base64.b64encode(cmd.encode('utf-16-le')).decode()
    stdin, stdout, stderr = c.exec_command(f'powershell -NoProfile -EncodedCommand {enc}', timeout=120)
    out = stdout.read().decode('utf-8','replace')
    err = stderr.read().decode('utf-8','replace')
    rc = stdout.channel.recv_exit_status()
    print(f'[rc={rc}]')
    print(out)
    if err.strip():
        print('--- STDERR ---')
        print(err[:2000])
finally:
    c.close()
