#!/usr/bin/env python3
"""Smoke the native vSphere REST surface against a running simulator."""

from __future__ import annotations

import json
import sys
import urllib.error
import urllib.request
from base64 import b64encode

BASE = sys.argv[1] if len(sys.argv) > 1 else "https://localhost"
USER = "administrator@vsphere.local"
PASSWORD = "VMware1!"


def _req(
    method: str, path: str, *, headers: dict[str, str] | None = None, data: bytes | None = None
):
    request = urllib.request.Request(
        f"{BASE}{path}",
        data=data,
        method=method,
        headers=headers or {},
    )
    ctx = None
    if BASE.startswith("https://"):
        import ssl

        ctx = ssl._create_unverified_context()  # noqa: S323 - lab self-signed
    with urllib.request.urlopen(request, context=ctx) as response:  # noqa: S310
        body = response.read()
        return response.status, dict(response.headers), body


def main() -> int:
    basic = b64encode(f"{USER}:{PASSWORD}".encode()).decode()
    status, headers, body = _req(
        "POST",
        "/api/session",
        headers={"Authorization": f"Basic {basic}"},
    )
    print("session", status, body.decode())
    session = json.loads(body.decode())
    sess_headers = {"vmware-api-session-id": session}
    status, _, vms = _req("GET", "/api/vcenter/vm", headers=sess_headers)
    print("vms", status, vms.decode())
    status, _, hosts = _req("GET", "/api/vcenter/host", headers=sess_headers)
    print("hosts", status, hosts.decode())
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except urllib.error.URLError as error:
        print(f"failed: {error}", file=sys.stderr)
        raise SystemExit(1) from error
