#!/usr/bin/env python3
"""Coolify API helper - runs on the remote server. Token bound to team 1."""
import json, sys, urllib.request

BASE = "http://localhost:8000/api/v1"
TOKEN = "3|gTHVGM97WUNZmrjUYjAS7xiLrKZrkNWmNwBRbv9f6e36272c"

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=120) 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)

if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "apps"
    if cmd == "apps":
        s, r = api("GET", "/applications")
        print(f"STATUS: {s}")
        print(json.dumps(r, indent=2))
    elif cmd == "switch-dockerfile":
        data = {
            "build_pack": "dockerfile",
            "dockerfile_location": "/Dockerfile",
            "ports_exposes": "80",
        }
        s, r = api("PATCH", "/applications/bjcuhkadno0onqp2dltlfuek", data)
        print(f"STATUS: {s}")
        print(json.dumps(r, indent=2))
    elif cmd == "deploy":
        s, r = api("POST", f"/deploy?uuid={sys.argv[2]}&force=false")
        print(f"STATUS: {s}")
        print(json.dumps(r, indent=2))
    elif cmd == "get":
        s, r = api("GET", f"/applications/{sys.argv[2]}")
        print(f"STATUS: {s}")
        print(json.dumps(r, indent=2))
