import urllib.request, json, time

BASE = "http://localhost:3001/api"

req = urllib.request.Request(BASE + "/auth/login",
    data=json.dumps({"email":"claude-api@azcomputerguru.com","password":"ClaudeAPI2026!@#"}).encode(),
    headers={"Content-Type":"application/json"})
token = json.loads(urllib.request.urlopen(req).read())["token"]
auth = {"Authorization": "Bearer " + token, "Content-Type": "application/json"}

# Simple diagnostic script
ps = "\n".join([
    "whoami",
    "$env:USERNAME",
    "Get-ExecutionPolicy",
    "Test-Path 'C:\\Users\\Administrator\\.ssh'",
    "Get-Service -Name sshd | Select-Object Status",
])

body = json.dumps({
    "name": "SSH diagnostics",
    "shell": "powershell",
    "supported_platforms": ["windows"],
    "script_body": ps,
    "default_timeout_seconds": 30,
    "category": "infrastructure"
}).encode()
req = urllib.request.Request(BASE + "/scripts", data=body, headers=auth)
script_id = json.loads(urllib.request.urlopen(req).read())["id"]

run_body = json.dumps({"agent_id": "5316f56f-a1b3-4ac5-97ac-71ddf6a74d2e", "timeout_seconds": 30}).encode()
req = urllib.request.Request(BASE + "/scripts/" + script_id + "/run", data=run_body, headers=auth)
run_id = json.loads(urllib.request.urlopen(req).read())["id"]
print("Run ID:", run_id)

for i in range(12):
    time.sleep(3)
    req = urllib.request.Request(BASE + "/script-runs/" + run_id, headers={"Authorization": "Bearer " + token})
    run = json.loads(urllib.request.urlopen(req).read())
    status = run.get("status")
    if status in ("completed", "failed", "timed_out"):
        print("Status:", status)
        print("Output:", run.get("output", ""))
        print("Error:", run.get("error_output", ""))
        print("Exit code:", run.get("exit_code"))
        break
    print(f"[{(i+1)*3}s] still {status}...")
