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 wait_run(run_id, label):
    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"{label} -> {status} (exit {run.get('exit_code')})")
            out = run.get("output", "") or ""
            err = run.get("error_output", "") or ""
            if out: print("STDOUT:", out[:500])
            if err: print("STDERR:", err[:500])
            return status
        print(f"  [{(i+1)*3}s] {status}...")
    return "timeout"

# Step 1: cmd echo test — simplest possible script
body = json.dumps({
    "name": "cmd echo test", "shell": "cmd",
    "supported_platforms": ["windows"],
    "script_body": "echo hello_from_pluto",
    "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())
print("CMD echo run:", resp.get("id"), resp.get("status"))
wait_run(resp["id"], "cmd echo")
