"""Focused VASLOG probe."""
import paramiko, base64, os

import subprocess, yaml as _yaml

HOST='192.168.0.6'; USER='sysadmin'

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

PWD = _pwd()
LOCAL = r'D:\claudetools\projects\dataforth-dos\datasheet-pipeline\scmvas-hvas-research\samples'
os.makedirs(LOCAL, exist_ok=True)

def ps(c, cmd, to=300):
    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', errors='replace'), stderr.read().decode('utf-8', errors='replace')

c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, username=USER, password=PWD, timeout=30, look_for_keys=False, allow_agent=False)

queries = [
    ('TS-3R root',       r'Get-ChildItem -LiteralPath "C:\Shares\test\TS-3R" -Force | Select Name,Mode,LastWriteTime | Format-Table -AutoSize | Out-String'),
    ('TS-3R\\LOGS',      r'if (Test-Path "C:\Shares\test\TS-3R\LOGS") { Get-ChildItem "C:\Shares\test\TS-3R\LOGS" -Force | Select Name,Mode,LastWriteTime | Format-Table -AutoSize | Out-String } else { "MISS" }'),
    ('TS-3R VASLOG',     r'if (Test-Path "C:\Shares\test\TS-3R\LOGS\VASLOG") { Get-ChildItem "C:\Shares\test\TS-3R\LOGS\VASLOG" -Force | Select Name,Mode,Length,LastWriteTime | Format-Table -AutoSize | Out-String } else { "MISS VASLOG" }'),
    ('Corrected HVAS',   r'Get-ChildItem "C:\Shares\test\Corrected HVAS Files" -Force -ErrorAction SilentlyContinue | Select Name,Mode,Length,LastWriteTime | Format-Table -AutoSize | Out-String'),
    ('STAGE sample',     r'Get-ChildItem "C:\Shares\test\STAGE" -Filter *.TXT -File -ErrorAction SilentlyContinue | Select -First 20 Name,Length | Format-Table -AutoSize | Out-String'),
    ('Recurse VASLOG',   r'Get-ChildItem "C:\Shares\test" -Recurse -Directory -Force -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "VASLOG|HVAS" } | Select FullName | Format-List | Out-String'),
]

try:
    for label, q in queries:
        print(f'\n=== {label} ===')
        out, err = ps(c, q)
        print(out[:3000])
        if err: print('[stderr]', err[:500])
finally:
    c.close()
