"""Find and pull sample VASLOG / Engineering-Tested TXTs."""
import paramiko, base64, os, posixpath

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_SAMPLES = r'D:\claudetools\projects\dataforth-dos\datasheet-pipeline\scmvas-hvas-research\samples'

os.makedirs(LOCAL_SAMPLES, exist_ok=True)

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

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')

def main():
    c = connect()
    try:
        # 1. Probe NAS share for VASLOG paths. NAS is accessed from AD2 as \\D2TESTNAS\test  mounted somewhere
        print('=== Check C:\\Shares\\test (NAS mirror) for VASLOG ===')
        out, err = ps(c, r'''Get-ChildItem -LiteralPath 'C:\Shares\test' -Directory | Select-Object Name,LastWriteTime | Format-Table -AutoSize | Out-String''')
        print(out)

        print('=== Check NAS-side LOGS/VASLOG via C:\\Shares\\test ===')
        for p in [r'C:\Shares\test\LOGS', r'C:\Shares\test\LOGS\VASLOG']:
            out, err = ps(c, f'''if (Test-Path -LiteralPath '{p}') {{ Get-ChildItem -LiteralPath '{p}' -Force | Select-Object Name,Mode,Length,LastWriteTime | Format-Table -AutoSize | Out-String }} else {{ Write-Host 'MISSING: {p}' }}''')
            print(f'--- {p} ---')
            print(out)

        # 2. Try under TS-3R directory inside the test share if stations upload their logs
        print('=== Search for VASLOG anywhere in test share (recursive, limited) ===')
        out, err = ps(c, r'''Get-ChildItem -LiteralPath 'C:\Shares\test' -Recurse -Directory -Force -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'VASLOG|vaslog' } | Select-Object FullName | Format-List | Out-String''')
        print(out[:2000])

        # 3. Also check NAS directly - see if we have access via UNC
        print('=== NAS UNC probe ===')
        out, err = ps(c, r'''if (Test-Path -LiteralPath '\\D2TESTNAS\test\LOGS\VASLOG') { Get-ChildItem -LiteralPath '\\D2TESTNAS\test\LOGS\VASLOG' -Force | Select-Object Name,Length,LastWriteTime | Format-Table -AutoSize | Out-String } else { Write-Host 'No direct UNC access' }''')
        print(out)

        # 4. Look up all STAGE locations where TS stations push TXT
        print('=== TS station TXT upload points ===')
        out, err = ps(c, r'''Get-ChildItem -LiteralPath 'C:\Shares\test' -Directory -Force | ForEach-Object { $n = $_.Name; try { $c = (Get-ChildItem -LiteralPath $_.FullName -File -Filter '*.txt' -ErrorAction SilentlyContinue).Count; Write-Host "$n : $c txt files" } catch {} }''')
        print(out[:3000])
    finally:
        c.close()

if __name__ == '__main__':
    main()
