# VM Host Management Commands
#
# Commands for checking and preparing hosts for VM management.
# Rule 1: Single purpose functions, Rule 2: Explicit types
# Error handling: Result pattern (hybrid, no try-catch)

use lib_provisioning/result.nu *
use lib_provisioning/vm/ {
    "detect-hypervisors"
    "check-vm-capability"
    "prepare-host-for-vms"
    "get-host-hypervisor-status"
    "ensure-vm-support"
}

export def "vm hosts check" [
    host: string = "local"         # Host to check (default: local)
]: record {
    """
    Check VM capabilities on a host.

    Examples:
        # Check local host
        provisioning vm hosts check

        # Check local host explicitly
        provisioning vm hosts check local

        # Check remote host
        provisioning vm hosts check upcloud-server-01
    """

    check-vm-capability $host
}

export def "vm hosts prepare" [
    host: string = "local"         # Host to prepare
    --auto-install = true          # Auto-install missing hypervisors
    --check-only = false           # Only check, don't install
]: record {
    """
    Prepare a host for VM management.

    Detects and optionally installs hypervisors.

    Examples:
        # Check host readiness
        provisioning vm hosts prepare local --check-only

        # Prepare host with auto-install
        provisioning vm hosts prepare local

        # Prepare remote host
        provisioning vm hosts prepare upcloud-01
    """

    prepare-host-for-vms $host --auto-install=$auto_install --check-only=$check_only
}

export def "vm hosts list" []: table {
    """
    List all hosts with VM capability information.

    Shows hosts and their hypervisor support.
    """

    # Guard: Query capability once with try-wrap instead of two try-catch blocks
    let cap_result = (try-wrap { check-vm-capability "local" })

    # Extract status and hypervisor with safe fallbacks
    let status = (
        if (is-ok $cap_result) {
            let cap = $cap_result.ok
            if $cap.primary_backend == "none" { "not-ready" } else { "ready" }
        } else {
            "error"
        }
    )

    let hypervisor = (
        if (is-ok $cap_result) {
            $cap_result.ok.primary_backend
        } else {
            "unknown"
        }
    )

    [
        {
            name: "local"
            type: "local"
            status: $status
            hypervisor: $hypervisor
        }
    ]
}

export def "vm hosts status" []: table {
    """Get detailed hypervisor status for all hosts"""

    get-host-hypervisor-status "local"
}

export def "vm hosts ensure" [
    host: string = "local"         # Host to ensure VM support
]: record {
    """
    Ensure a host has VM support.

    Installs hypervisors if needed and verifies readiness.

    Examples:
        # Ensure local host has VM support
        provisioning vm hosts ensure

        # Ensure remote host
        provisioning vm hosts ensure upcloud-server-01
    """

    ensure-vm-support $host
}
