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

AGENT_ID = "5316f56f-a1b3-4ac5-97ac-71ddf6a74d2e"

def run_and_wait(name, shell, body_lines):
    body = json.dumps({
        "name": name, "shell": shell,
        "supported_platforms": ["windows"],
        "script_body": "\r\n".join(body_lines),
        "default_timeout_seconds": 30, "category": "infrastructure"
    }).encode()
    req = urllib.request.Request(BASE + "/scripts", data=body, headers=auth)
    sid = json.loads(urllib.request.urlopen(req).read())["id"]

    run_body = json.dumps({"agent_id": AGENT_ID, "timeout_seconds": 30}).encode()
    req = urllib.request.Request(BASE + "/scripts/" + sid + "/run", data=run_body, headers=auth)
    resp = json.loads(urllib.request.urlopen(req).read())
    run_id = resp["id"]

    for i in range(15):
        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"):
            return status, run.get("exit_code"), run.get("output",""), run.get("error_output",""), run
        print(f"  [{(i+1)*3}s] {status}...")
    return "timeout", None, "", "", {}

KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKSqf2/phEXUK8vd5GhMIDTEGSk0LvYk92sRdNiRrjKi guru@gururmm-build"

# Use cmd to: create dir, write key, fix perms
cmd_lines = [
    "@echo off",
    "md \"C:\\Users\\Administrator\\.ssh\" 2>nul",
    "echo " + KEY + " > \"C:\\Users\\Administrator\\.ssh\\authorized_keys\"",
    "icacls \"C:\\Users\\Administrator\\.ssh\\authorized_keys\" /inheritance:r /grant \"SYSTEM:F\" /grant \"Administrators:F\"",
    "echo DONE",
    "type \"C:\\Users\\Administrator\\.ssh\\authorized_keys\"",
]

print("Adding SSH key via cmd...")
status, code, out, err, raw = run_and_wait("Add SSH key cmd", "cmd", cmd_lines)
print(f"Status: {status}, exit: {code}")
print("Output:", repr(out)[:300] if out else "(empty)")
print("Error: ", repr(err)[:300] if err else "(empty)")
print("Raw keys:", [k for k in raw.keys()])
