"""Sample a few skipped records to understand why they didn't render."""
import base64, subprocess, yaml, paramiko

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

(async () => {
    const rows = await db.query(
        "SELECT id, serial_number, model_number, raw_data FROM test_records " +
        "WHERE overall_result='PASS' AND forweb_exported_at IS NULL " +
        "AND (model_number LIKE 'SCMVAS%' OR model_number LIKE 'SCMHVAS%') " +
        "ORDER BY test_date DESC LIMIT 5"
    );
    const specMap = loadAllSpecs();
    for (const r of rows) {
        console.log('====================');
        console.log('SN:' + r.serial_number + '  model:' + r.model_number);
        console.log('raw_data length: ' + (r.raw_data||'').length);
        console.log('first 200 chars: ' + JSON.stringify((r.raw_data||'').slice(0, 200)));
        const specs = getSpecs(specMap, r.model_number);
        console.log('specs: ' + (specs ? 'stub' : 'null'));
        try {
            const txt = generateExactDatasheet(r, specs);
            console.log('formatter output length: ' + (txt ? txt.length : 'null'));
            if (txt) console.log('snippet: ' + txt.slice(0, 200));
        } catch (e) {
            console.log('formatter threw: ' + e.message);
        }
    }
    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('\\','')

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:
    sftp = c.open_sftp()
    remote = 'C:/Shares/testdatadb/_inspect.js'
    with sftp.open(remote,'w') as fh: fh.write(NODE_SCRIPT)
    sftp.close()

    out, err, rc = ps(c, r'cd C:\Shares\testdatadb; & node ./_inspect.js')
    print(out)
    if err.strip() and 'CLIXML' not in err:
        print('STDERR:', err[:500])

    sftp = c.open_sftp()
    try: sftp.remove(remote)
    except Exception: pass
    sftp.close()
finally:
    c.close()
