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"]

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

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

cmd_lines = [
    "@echo off",
    "echo START",
    "more C:\\ProgramData\\ssh\\administrators_authorized_keys",
    "echo ---PERMS---",
    "icacls C:\\ProgramData\\ssh\\administrators_authorized_keys",
    "echo ---SSHD_CONFIG---",
    "findstr /i AuthorizedKeysFile C:\\ProgramData\\ssh\\sshd_config",
    "findstr /i Match C:\\ProgramData\\ssh\\sshd_config",
    "echo DONE",
]

body = json.dumps({
    "name": "Pluto SSH diag2", "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"]
print(f"Script: {script_id}")

for attempt in range(30):
    if not is_online(token):
        print(f"[{attempt}] offline...")
        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}")
        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}, exit: {run.get('exit_code')}")
                print("OUTPUT:", repr(run.get("output") or ""))
                print("ERR:", repr(run.get("error_output") or ""))
                exit(0)
            print(f"  [{(i+1)*3}s] {status}...")
    except Exception as e:
        print(f"[{attempt}] error: {e}")
        time.sleep(5)
