"""Count the backlog for task #12 backfill + confirm X: access context."""
import base64, subprocess, yaml, paramiko

NODE_SCRIPT = r'''
const db = require('./database/db');
(async () => {
    const total = await db.queryOne(
        "SELECT COUNT(*) c FROM test_records WHERE overall_result='PASS' AND forweb_exported_at IS NULL"
    );
    console.log('Total PASS backlog: ' + total.c);

    const vaslog = await db.queryOne(
        "SELECT COUNT(*) c FROM test_records WHERE overall_result='PASS' AND forweb_exported_at IS NULL AND log_type='VASLOG'"
    );
    console.log('  of which VASLOG (production .DAT):  ' + vaslog.c);

    const vaslog_eng = await db.queryOne(
        "SELECT COUNT(*) c FROM test_records WHERE overall_result='PASS' AND forweb_exported_at IS NULL AND log_type='VASLOG_ENG'"
    );
    console.log('  of which VASLOG_ENG (Eng .txt):     ' + vaslog_eng.c);

    const scmvas = await db.queryOne(
        "SELECT COUNT(*) c FROM test_records WHERE overall_result='PASS' AND forweb_exported_at IS NULL " +
        "AND (model_number LIKE 'SCMVAS%' OR model_number LIKE 'SCMHVAS%' OR model_number LIKE 'VAS-M%' OR model_number LIKE 'HVAS-M%')"
    );
    console.log('SCMVAS/SCMHVAS/VAS-M/HVAS-M backlog: ' + scmvas.c);

    const bymodel = await db.query(
        "SELECT model_number, log_type, COUNT(*) c FROM test_records WHERE overall_result='PASS' AND forweb_exported_at IS NULL " +
        "AND (model_number LIKE 'SCMVAS%' OR model_number LIKE 'SCMHVAS%' OR model_number LIKE 'VAS-M%' OR model_number LIKE 'HVAS-M%') " +
        "GROUP BY model_number, log_type ORDER BY c DESC"
    );
    console.log('By model:');
    for (const r of bymodel) console.log('  ' + r.model_number.padEnd(18) + ' ' + (r.log_type||'').padEnd(12) + ' ' + r.c);

    await db.close();
})().catch(e => { console.error('FAIL: ' + e.message); process.exit(1); });
'''

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, banner_timeout=45, look_for_keys=False, allow_agent=False)
try:
    sftp = c.open_sftp()
    remote = 'C:/Shares/testdatadb/_backlog_probe.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 ./_backlog_probe.js')
    print(out)
    if err.strip() and 'CLIXML' not in err:
        print('STDERR:', err[:500])

    # Check X: access path resolution from service account's perspective
    print('\n=== X: drive / UNC resolution ===')
    out, err, rc = ps(c, r'Get-PSDrive -Name X -ErrorAction SilentlyContinue | Format-Table Name,Root -AutoSize; Get-SmbMapping | Where-Object { $_.LocalPath -match "X:" } | Format-Table -AutoSize')
    print(out)

    # Check testdatadb service account identity
    print('=== testdatadb service identity ===')
    out, err, rc = ps(c, r'Get-WmiObject -Class Win32_Service -Filter "Name=''testdatadb''" | Select Name,StartName,State,PathName | Format-List')
    print(out)

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