#!/usr/bin/env python3
"""Create the Coolify server pointing to localhost."""
import json, sys, urllib.request

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

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)

data = {
    "name": "ionos-87-106-131-211",
    "ip": "host.docker.internal",
    "user": "root",
    "port": 22,
    "private_key_uuid": KEY_UUID,
    "proxy_type": "traefik",
}
s, r = api("POST", "/servers", data)
print(f"STATUS: {s}")
print(json.dumps(r, indent=2))
