"""Restart testdatadb service on AD2 and verify it comes back up healthy."""
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('=== Restart testdatadb ===')
    out, err, rc = ps(c, r'Restart-Service testdatadb -Force; Start-Sleep -Seconds 3; Get-Service testdatadb | Select Name,Status | Format-Table -AutoSize | Out-String', to=60)
    print(out)

    print('=== Service port probe (common node app ports) ===')
    out, err, rc = ps(c, r'foreach ($p in @(3000,3001,3002,8000,8001,8002,8080,5000)) { $r = Test-NetConnection -ComputerName localhost -Port $p -InformationLevel Quiet -WarningAction SilentlyContinue; if ($r) { Write-Host "[OPEN] $p" } }')
    print(out)

    print('=== Listening ports on AD2 matching node ===')
    out, err, rc = ps(c, r'Get-NetTCPConnection -State Listen | ForEach-Object { $proc = Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue; if ($proc -and $proc.Name -match "node") { "{0,-8} {1}" -f $_.LocalPort, $proc.Path } } | Sort-Object -Unique')
    print(out)
finally:
    c.close()
