#!/usr/bin/env python3
"""Proxmox API helper — avoids bash ! quoting issues in interactive shells."""
import json, os, ssl, sys, urllib.request

def main():
    # Load config
    script_dir = os.path.dirname(os.path.abspath(__file__))
    env_file = os.path.join(os.path.dirname(script_dir), "env")
    if os.path.exists(env_file):
        for line in open(env_file):
            line = line.strip()
            if line.startswith("export "):
                line = line[7:]
            if "=" in line and not line.startswith("#"):
                k, v = line.split("=", 1)
                os.environ[k] = v

    yaml_file = os.path.join(script_dir, "proxmox.yaml")
    cfg = {}
    if os.path.exists(yaml_file):
        for line in open(yaml_file):
            line = line.strip()
            if ": " in line and not line.startswith("#"):
                k, v = line.split(": ", 1)
                cfg[k] = v.strip("'\"")

    host = cfg.get("host", "")
    node = cfg.get("node", "pve")
    token_id = cfg.get("api_token_id", "")
    secret = os.environ.get("PROXMOX_TOKEN_SECRET", "")

    if not host or not token_id or not secret:
        print("Error: missing host/token_id/secret", file=sys.stderr)
        sys.exit(1)

    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    method = "GET"
    endpoint = sys.argv[1] if len(sys.argv) > 1 else f"/nodes/{node}/qemu"
    if len(sys.argv) > 2:
        method = sys.argv[2]
    data = sys.argv[3].encode() if len(sys.argv) > 3 else None

    url = f"https://{host}:8006/api2/json{endpoint}"
    req = urllib.request.Request(url, method=method, data=data)
    req.add_header("Authorization", f"PVEAPIToken={token_id}={secret}")
    if data:
        req.add_header("Content-Type", "application/json")

    try:
        resp = urllib.request.urlopen(req, context=ctx)
        print(resp.read().decode())
    except urllib.error.HTTPError as e:
        print(json.dumps({"error": str(e), "code": e.code}))
        sys.exit(1)

if __name__ == "__main__":
    main()
