#!/usr/bin/env python3
"""Create the CSC Eifelgreen application in Coolify."""
import json, sys, urllib.request

BASE = "http://localhost:8000/api/v1"
TOKEN = "2|IqbpR94lOiexx5gXHV3BO31utUhuqwi9Y5T2lLCe1505d5d4"

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 GitHub token from env
gh_token = sys.argv[2] if len(sys.argv) > 2 else ""

# Create public application (works for private repos if token in URL)
data = {
    "project_uuid": "thuyxeybqpsqybkh6ggfsand",
    "server_uuid": "kmmkw8wkbdv7thewyr62h3zc",
    "environment_name": "production",
    "git_repository": f"https://x-access-token:{gh_token}@github.com/qartex/csc-webseite-2026.git",
    "git_branch": "main",
    "build_pack": "nixpacks",
    "domains": "http://87.106.131.211",
    "name": "csc-eifelgreen",
    "is_auto_deploy_enabled": True,
    "is_force_https_enabled": False,
    "install_command": "npm ci",
    "build_command": "npm run build",
    "start_command": "npm run start",
    "ports_exposes": "3000",
}
s, r = api("POST", "/applications/public", data)
print(f"STATUS: {s}")
print(json.dumps(r, indent=2))
