#!/usr/bin/env python3
"""Minimal SOAP /sdk smoke (RetrieveServiceContent + Login envelope)."""

from __future__ import annotations

import ssl
import sys
import urllib.error
import urllib.request

BASE = sys.argv[1] if len(sys.argv) > 1 else "https://localhost"

CONTENT = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:urn="urn:vim25">
  <soapenv:Body>
    <urn:RetrieveServiceContent>
      <urn:_this type="ServiceInstance">ServiceInstance</urn:_this>
    </urn:RetrieveServiceContent>
  </soapenv:Body>
</soapenv:Envelope>
"""

LOGIN = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:urn="urn:vim25">
  <soapenv:Body>
    <urn:Login>
      <urn:_this type="SessionManager">SessionManager</urn:_this>
      <urn:userName>administrator@vsphere.local</urn:userName>
      <urn:password>VMware1!</urn:password>
    </urn:Login>
  </soapenv:Body>
</soapenv:Envelope>
"""


def _post(path: str, body: str) -> tuple[int, str]:
    req = urllib.request.Request(
        f"{BASE}{path}",
        data=body.encode(),
        method="POST",
        headers={"Content-Type": "text/xml; charset=utf-8", "SOAPAction": '""'},
    )
    ctx = ssl._create_unverified_context() if BASE.startswith("https://") else None  # noqa: S323
    with urllib.request.urlopen(req, context=ctx) as resp:  # noqa: S310
        return int(resp.status), resp.read().decode()


def main() -> int:
    status, body = _post("/sdk", CONTENT)
    print("RetrieveServiceContent", status, "ServiceContent" in body)
    if "ServiceContent" not in body:
        return 1
    status, body = _post("/sdk", LOGIN)
    login_ok = "LoginResponse" in body or "UserSession" in body or "key>" in body
    print("Login", status, login_ok)
    if not login_ok:
        print(body[:400], file=sys.stderr)
        return 1
    wsdl = urllib.request.Request(f"{BASE}/sdk/vimService.wsdl")
    ctx = ssl._create_unverified_context() if BASE.startswith("https://") else None  # noqa: S323
    with urllib.request.urlopen(wsdl, context=ctx) as resp:  # noqa: S310
        print("wsdl", resp.status, len(resp.read()))
    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
