"""Post-deploy health check for testdatadb on AD2.

Restart the Windows service, then curl the API and confirm it returns 200.
Log any startup errors.
"""
import base64, subprocess, yaml, paramiko

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:
    print('=== service list ===')
    out, err, rc = ps(c, 'Get-Service | Where-Object { $_.Name -match "testdata|testdb" } | Select Name,Status,DisplayName | Format-Table -AutoSize | Out-String')
    print(out)

    print('=== node syntax-check the 5 deployed files ===')
    out, err, rc = ps(c, r'''
$files = @(
  'C:\Shares\testdatadb\parsers\spec-reader.js',
  'C:\Shares\testdatadb\parsers\vaslog-engtxt.js',
  'C:\Shares\testdatadb\templates\datasheet-exact.js',
  'C:\Shares\testdatadb\database\import.js',
  'C:\Shares\testdatadb\database\export-datasheets.js'
)
foreach ($f in $files) {
  $r = & node --check $f 2>&1
  if ($LASTEXITCODE -eq 0) { Write-Host "[OK]   $f" } else { Write-Host "[FAIL] $f : $r" }
}
''')
    print(out)
    if err: print('STDERR:', err[:500])

    print('=== quick require-load test (no handlers invoked) ===')
    out, err, rc = ps(c, r'''
$script = @'
try {
  require("C:/Shares/testdatadb/parsers/spec-reader.js");
  console.log("[OK] spec-reader");
  require("C:/Shares/testdatadb/parsers/vaslog-engtxt.js");
  console.log("[OK] vaslog-engtxt");
  require("C:/Shares/testdatadb/templates/datasheet-exact.js");
  console.log("[OK] datasheet-exact");
} catch (e) { console.log("[FAIL] " + e.message); process.exit(1); }
'@
$script | Out-File -FilePath $env:TEMP\loadtest.js -Encoding ascii
& node $env:TEMP\loadtest.js
''')
    print(out)
    if err: print('STDERR:', err[:500])
finally:
    c.close()
