import urllib.request, json, time

BASE = "http://localhost:3001/api"
AGENT_ID = "5316f56f-a1b3-4ac5-97ac-71ddf6a74d2e"

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

token = get_token()
auth = {"Authorization": "Bearer " + token, "Content-Type": "application/json"}

cmd_lines = [
    "@echo off",
    "echo === administrators_authorized_keys content ===",
    "type C:/ProgramData/ssh/administrators_authorized_keys",
    "echo === icacls permissions ===",
    "icacls C:/ProgramData/ssh/administrators_authorized_keys",
    "echo === sshd_config AuthorizedKeysFile lines ===",
    "findstr /i \"AuthorizedKeysFile Match\" C:/ProgramData/ssh/sshd_config",
    "echo === sshd service status ===",
    "sc query sshd",
]

body = json.dumps({
    "name": "Pluto SSH diagnostic", "shell": "cmd",
    "supported_platforms": ["windows"],
    "script_body": "\r\n".join(cmd_lines),
    "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"]

def is_online(tok):
    try:
        req = urllib.request.Request(BASE + "/agents/" + AGENT_ID,
            headers={"Authorization": "Bearer " + tok})
        return json.loads(urllib.request.urlopen(req).read()).get("status") == "online"
    except: return False

run_id = None
for attempt in range(30):
    if not is_online(token):
        print(f"[{attempt}] offline, waiting...")
        time.sleep(5)
        continue
    try:
        run_body = json.dumps({"agent_id": AGENT_ID, "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(f"Dispatched: {run_id}")
        break
    except Exception as e:
        print(f"[{attempt}] dispatch error: {e}")
        time.sleep(5)

if not run_id:
    print("Failed to dispatch"); exit(1)

for i in range(20):
    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(f"Status: {status}")
        out = run.get("output") or ""
        err = run.get("error_output") or ""
        if out: print(out[:2000])
        if err: print("ERR:", err[:500])
        break
    print(f"  [{(i+1)*3}s] {status}...")
