"""Create a lab VM with pulumi-vsphere VirtualMachine."""

from __future__ import annotations

import os
import uuid

import pulumi
import pulumi_vsphere as vsphere

user = os.environ.get("VSPHERE_USER", "administrator@vsphere.local")
password = os.environ.get("VSPHERE_PASSWORD", "VMware1!")
server = os.environ.get("VSPHERE_SERVER", "api-gateway")
datacenter_name = os.environ.get("VSPHERE_DATACENTER", "Datacenter")
datastore_name = os.environ.get("VSPHERE_DATASTORE", "datastore1")
cluster_name = os.environ.get("VSPHERE_CLUSTER", "Cluster")
network_name = os.environ.get("VSPHERE_NETWORK", "VM Network")
run_id = os.environ.get("TEST_RUN_ID") or uuid.uuid4().hex[:8]
vm_name = os.environ.get("VSPHERE_LAB_VM_NAME", f"pulumi-lab-{run_id}")

provider = vsphere.Provider(
    "vsphere",
    user=user,
    password=password,
    vsphere_server=server,
    allow_unverified_ssl=True,
)
invoke_opts = pulumi.InvokeOptions(provider=provider)
res_opts = pulumi.ResourceOptions(provider=provider)

dc = vsphere.get_datacenter_output(name=datacenter_name, opts=invoke_opts)
ds = vsphere.get_datastore_output(
    name=datastore_name,
    datacenter_id=dc.id,
    opts=invoke_opts,
)
cluster = vsphere.get_compute_cluster_output(
    name=cluster_name,
    datacenter_id=dc.id,
    opts=invoke_opts,
)
network = vsphere.get_network_output(
    name=network_name,
    datacenter_id=dc.id,
    opts=invoke_opts,
)

vm = vsphere.VirtualMachine(
    "lab-vm",
    name=vm_name,
    resource_pool_id=cluster.resource_pool_id,
    datastore_id=ds.id,
    num_cpus=1,
    memory=1024,
    guest_id="otherGuest64",
    wait_for_guest_net_timeout=0,
    wait_for_guest_ip_timeout=0,
    network_interfaces=[
        vsphere.VirtualMachineNetworkInterfaceArgs(network_id=network.id),
    ],
    disks=[
        vsphere.VirtualMachineDiskArgs(label="disk0", size=16),
    ],
    opts=res_opts,
)

pulumi.export("lab_vm_id", vm.id)
pulumi.export("lab_vm_name", vm.name)
pulumi.export("resource_pool_id", cluster.resource_pool_id)
pulumi.export("datastore_id", ds.id)
pulumi.export("network_id", network.id)
