import urllib.request, json, sys

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

# PowerShell: ensure .ssh dir exists, add key if not already present
ps = "\n".join([
    "$d = 'C:\\Users\\Administrator\\.ssh'",
    "$f = $d + '\\authorized_keys'",
    "if (!(Test-Path $d)) { New-Item -ItemType Directory -Force $d | Out-Null }",
    "$k = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKSqf2/phEXUK8vd5GhMIDTEGSk0LvYk92sRdNiRrjKi guru@gururmm-build'",
    "if (!(Test-Path $f) -or !(Select-String -Path $f -SimpleMatch 'AAAAC3NzaC1lZDI1NTE5AAAAIKSqf2' -Quiet 2>$null)) {",
    "    Add-Content -Path $f -Value $k",
    "    icacls $f /inheritance:r /grant 'SYSTEM:F' /grant 'Administrators:F' | Out-Null",
    "    'Key added'",
    "} else { 'Key already present' }",
])

body = json.dumps({
    "name": "Add build server SSH key",
    "description": "Authorizes gururmm-build ed25519 key for Administrator SSH",
    "shell": "powershell",
    "supported_platforms": ["windows"],
    "script_body": ps,
    "default_timeout_seconds": 30,
    "category": "infrastructure"
}).encode()
req = urllib.request.Request(BASE + "/scripts", data=body, headers=auth)
script = json.loads(urllib.request.urlopen(req).read())
script_id = script["id"]
print("Script ID:", script_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 = json.loads(urllib.request.urlopen(req).read())
print("Run ID:", run.get("id"))
print("Status:", run.get("status"))
