#!/usr/bin/env python3
"""Register the existing Coolify SSH key as a private key, then create the server."""
import json, sys, urllib.request

BASE = "http://localhost:8000/api/v1"
TOKEN = "1|R7Oc2iF7Qa9gA4bPHz12mUYoezfQyJkDzWMYLXpCf7791ab3"

def api(method, path, data=None):
    url = BASE + path
    body = json.dumps(data).encode() if data is not None else None
    req = urllib.request.Request(url, data=body, method=method)
    req.add_header("Authorization", f"Bearer {TOKEN}")
    req.add_header("Accept", "application/json")
    if body:
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return resp.status, json.loads(resp.read().decode())
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read().decode())
        except Exception:
            return e.code, e.read().decode()
    except Exception as e:
        return 0, str(e)

# Read the SSH private key
with open("/data/coolify/ssh/keys/ssh_key@diav8nyxsvi3fi5aignprnyz") as f:
    private_key = f.read()

# Register private key
data = {
    "name": "coolify-localhost",
    "description": "Coolify localhost SSH key",
    "private_key": private_key,
    "is_git_related": False,
}
s, r = api("POST", "/security/keys", data)
print(f"KEY STATUS: {s}")
print(json.dumps(r, indent=2))
key_uuid = r.get("uuid") if isinstance(r, dict) else None
print(f"KEY_UUID: {key_uuid}")
