"""Optional pyvmomi SmartConnect smoke (skipped when package uninstalled)."""

from __future__ import annotations

import os

import pytest

pytest.importorskip("pyVim")
pytest.importorskip("pyVmomi")

from pyVim.connect import Disconnect, SmartConnect  # type: ignore[import-untyped]
from pyVmomi import vim  # type: ignore[import-untyped]

pytestmark = pytest.mark.compatibility


def test_pyvmomi_inventory_and_power() -> None:
    host = os.getenv("VSPHERE_HOST", "simulator")
    port = int(os.getenv("VSPHERE_PORT", "8080"))
    try:
        si = SmartConnect(
            host=host,
            user="administrator@vsphere.local",
            pwd="VMware1!",
            port=port,
            disableSslCertValidation=True,
        )
    except Exception as error:
        pytest.skip(f"SmartConnect failed: {error}")
    try:
        content = si.RetrieveContent()
        assert content.about.name
        container = content.viewManager.CreateContainerView(
            content.rootFolder, [vim.VirtualMachine], True
        )
        vms = list(container.view)
        assert len(vms) >= 5
        target = next((vm for vm in vms if vm.name == "app-01"), vms[0])
        if target.runtime.powerState != vim.VirtualMachinePowerState.poweredOn:
            task = target.PowerOn()
            assert task is not None
    finally:
        Disconnect(si)
