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

# cmd.exe test - simpler than powershell, check env
ps = "echo %USERNAME% %TEMP% %USERPROFILE%"

body = json.dumps({
    "name": "CMD env debug",
    "shell": "cmd",
    "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("Exit code:", run.get("exit_code"))
        print("STDOUT:", repr(run.get("output", "")))
        print("STDERR:", repr(run.get("error_output", "")))
        break
    print(f"[{(i+1)*3}s] {status}...")
