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(token):
    try:
        req = urllib.request.Request(BASE + "/agents/" + AGENT_ID,
            headers={"Authorization": "Bearer " + token})
        a = json.loads(urllib.request.urlopen(req).read())
        return a.get("status") == "online"
    except: return False

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

KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKSqf2/phEXUK8vd5GhMIDTEGSk0LvYk92sRdNiRrjKi guru@gururmm-build"
cmd_lines = [
    "@echo off",
    'md "C:\\Users\\Administrator\\.ssh" 2>nul',
    'echo ' + KEY + ' >> "C:\\Users\\Administrator\\.ssh\\authorized_keys"',
    'icacls "C:\\Users\\Administrator\\.ssh" /inheritance:r /grant "SYSTEM:(OI)(CI)F" /grant "Administrators:(OI)(CI)F" 2>nul',
    'icacls "C:\\Users\\Administrator\\.ssh\\authorized_keys" /inheritance:r /grant "SYSTEM:F" /grant "Administrators:F" 2>nul',
    'echo SUCCESS',
    'type "C:\\Users\\Administrator\\.ssh\\authorized_keys"',
]

body = json.dumps({
    "name": "Add build server SSH key", "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 created: {script_id}")

# Wait for agent to be online then dispatch with retries
for attempt in range(20):
    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)
        resp = json.loads(urllib.request.urlopen(req).read())
        run_id = resp["id"]
        print(f"[{attempt}] Dispatched: {run_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"):
                print(f"Status: {status}, exit: {run.get('exit_code')}")
                out = run.get("output") or ""
                err = run.get("error_output") or ""
                if out: print("STDOUT:", out[:600])
                if err: print("STDERR:", err[:300])
                exit(0)
            print(f"  [{(i+1)*3}s] {status}...")
    except Exception as e:
        print(f"[{attempt}] Error: {e}")
        time.sleep(5)

print("Gave up after 20 attempts")
