# Nested Infrastructure CLI Commands (Phase 4)
#
# User-facing commands for nested VMs, volumes, networking, and deployments.

use lib_provisioning/vm/ {
    "volume-create" "volume-list" "volume-info" "volume-attach" "volume-detach"
    "volume-snapshot" "volume-restore" "volume-delete" "volume-stats"
    "network-create" "network-list" "network-info" "network-connect" "network-disconnect"
    "network-policy-create" "network-policy-list" "network-stats" "vlan-create" "vlan-list"
    "nested-vm-create" "nested-vm-list" "nested-vm-info" "nested-vm-delete"
    "container-create" "container-list" "container-delete" "nesting-stats"
    "deployment-create" "deployment-deploy" "deployment-list" "deployment-info"
    "deployment-delete" "deployment-scale" "deployment-health"
}

# ═════════════════════════════════════════════════════════════════════════
# VOLUME MANAGEMENT COMMANDS
# ═════════════════════════════════════════════════════════════════════════

export def "volume create" [
    name: string                                 # Volume name
    size_gb: int                                 # Size in GB
    --type: string = "local"                     # Type (local/nfs/cifs)
    --mount-path: string = ""                    # Mount path
    --readonly = false                           # Read-only
]: table {
    """
    Create a storage volume.

    Examples:
        provisioning volume create data 100 --type local --mount-path /data
        provisioning volume create shared 500 --type nfs --mount-path /mnt/shared
    """

    let result = (volume-create $name $size_gb --type=$type --mount-path=$mount_path --readonly=$readonly)

    if $result.success {
        print $"✓ Volume '($name)' created"
        print $"  Size: ($result.size_gb)GB"
        print $"  Path: ($result.volume_path)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "volume list" []: table {
    """List all volumes."""
    volume-list
}

export def "volume info" [name: string]: record {
    """Get volume information."""
    volume-info $name
}

export def "volume attach" [
    volume_name: string
    vm_name: string
    --mount-path: string = ""
]: table {
    """Attach volume to VM."""
    let result = (volume-attach $volume_name $vm_name --mount-path=$mount_path)
    [$result]
}

export def "volume snapshot" [
    volume_name: string
    snapshot_name: string
    --description: string = ""
]: table {
    """Create volume snapshot."""
    let result = (volume-snapshot $volume_name $snapshot_name --description=$description)
    [$result]
}

# ═════════════════════════════════════════════════════════════════════════
# NETWORKING COMMANDS
# ═════════════════════════════════════════════════════════════════════════

export def "network create" [
    name: string                                 # Network name
    subnet: string                               # Subnet CIDR
    --type: string = "bridge"                    # Type
    --gateway: string = ""                       # Gateway
]: table {
    """
    Create a virtual network.

    Examples:
        provisioning network create frontend 192.168.1.0/24
        provisioning network create backend 192.168.2.0/24 --type vlan
    """

    let result = (network-create $name $subnet --type=$type --gateway=$gateway)

    if $result.success {
        print $"✓ Network '($name)' created"
        print $"  Subnet: ($result.subnet)"
        print $"  Gateway: ($result.gateway)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "network list" []: table {
    """List all networks."""
    network-list
}

export def "network connect" [
    network_name: string
    vm_name: string
    --static-ip: string = ""
]: table {
    """Connect VM to network."""
    let result = (network-connect $network_name $vm_name --static-ip=$static_ip)
    [$result]
}

export def "vlan create" [
    vlan_id: int
    name: string
    subnet: string
]: table {
    """Create a VLAN."""
    let result = (vlan-create $vlan_id $name $subnet)
    [$result]
}

export def "vlan list" []: table {
    """List all VLANs."""
    vlan-list
}

export def "policy create" [
    name: string
    --direction: string = "both"
    --protocol: string = "tcp"
    --source: string = "any"
    --destination: string = "any"
    --action: string = "allow"
]: table {
    """Create network policy."""
    let result = (network-policy-create $name --direction=$direction --protocol=$protocol --source=$source --destination=$destination --action=$action)
    [$result]
}

# ═════════════════════════════════════════════════════════════════════════
# NESTED VM COMMANDS
# ═════════════════════════════════════════════════════════════════════════

export def "nested-vm create" [
    name: string
    parent_vm: string
    --cpu: int = 2
    --memory: int = 2048
    --disk: int = 20
    --networks: list<string> = []
    --volumes: list<string> = []
    --auto-start = false
]: table {
    """
    Create a nested VM inside another VM.

    Examples:
        provisioning nested-vm create app-01 web-server --cpu 4 --memory 4096
        provisioning nested-vm create db-01 web-server --networks backend --volumes data
    """

    let result = (
        nested-vm-create $name $parent_vm \
            --cpu=$cpu --memory=$memory --disk=$disk \
            --networks=$networks --volumes=$volumes --auto-start=$auto_start
    )

    if $result.success {
        print $"✓ Nested VM '($name)' created"
        print $"  Parent: ($result.parent_vm)"
        print $"  CPU: ($result.cpu) cores"
        print $"  Memory: ($result.memory_mb)MB"
        print $"  Nesting Depth: ($result.nesting_depth)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "nested-vm list" [--parent: string = ""]: table {
    """List nested VMs."""
    nested-vm-list $parent
}

export def "container create" [
    name: string
    image: string
    parent_vm: string
    --tag: string = "latest"
    --cpu-millicores: int = 1000
    --memory-mb: int = 512
    --networks: list<string> = []
    --volumes: list<string> = []
]: table {
    """
    Create a container inside a nested VM.

    Examples:
        provisioning container create web-app nginx app-01
        provisioning container create api-server myapp:v1.0 app-01 --cpu-millicores 2000 --memory-mb 1024
    """

    let result = (
        container-create $name $image $parent_vm \
            --tag=$tag --cpu-millicores=$cpu_millicores --memory-mb=$memory_mb \
            --networks=$networks --volumes=$volumes
    )

    if $result.success {
        print $"✓ Container '($name)' created"
        print $"  Image: ($result.image)"
        print $"  Parent VM: ($result.parent_vm)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "container list" [--parent: string = ""]: table {
    """List containers."""
    container-list $parent
}

# ═════════════════════════════════════════════════════════════════════════
# MULTI-TIER DEPLOYMENT COMMANDS
# ═════════════════════════════════════════════════════════════════════════

export def "deployment create" [
    name: string
    --tiers: list<string>
    --replicas: int = 1
    --version: string = "1.0.0"
]: table {
    """
    Create a multi-tier application deployment.

    Examples:
        provisioning deployment create myapp --tiers web app db --replicas 3
        provisioning deployment create ecommerce --tiers frontend backend database --replicas 2 --version 1.2.0
    """

    let result = (
        deployment-create $name \
            --tiers=$tiers --replicas=$replicas --version=$version
    )

    if $result.success {
        print $"✓ Deployment '($name)' created"
        print $"  Version: ($result.version)"
        print $"  Tiers: ($result.tiers | str join ', ')"
        print $"  Replicas: ($result.replicas)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "deployment deploy" [
    name: string
    --check = false
]: table {
    """
    Deploy a multi-tier application.

    Examples:
        provisioning deployment deploy myapp
        provisioning deployment deploy myapp --check  # Dry-run
    """

    let result = (deployment-deploy $name --check=$check)

    if $check {
        print "Deployment configuration:"
        print $result.would_deploy | to json
        return [$result]
    }

    if $result.success {
        print $"✓ Deployment '($name)' deployed"
        print $"  Instances: ($result.instances_deployed)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "deployment list" []: table {
    """List deployments."""
    deployment-list
}

export def "deployment info" [name: string]: record {
    """Get deployment information."""
    deployment-info $name
}

export def "deployment scale" [
    name: string
    tier: string
    replicas: int
]: table {
    """
    Scale a deployment tier.

    Examples:
        provisioning deployment scale myapp web 5  # Scale web tier to 5 replicas
        provisioning deployment scale myapp db 2   # Scale db tier to 2 replicas
    """

    let result = (deployment-scale $name $tier $replicas)

    if $result.success {
        print $"✓ Scaled '($tier)' to ($replicas) replicas"
        print $"  Previous: ($result.previous_replicas)"
        print $"  New: ($result.new_replicas)"
    } else {
        print $"✗ Failed: ($result.error)"
    }

    [$result]
}

export def "deployment health" [name: string]: record {
    """Check deployment health."""
    let health = (deployment-health $name)

    if $health.success {
        print $"Deployment Health: '($name)'"
        print $"  Instances: ($health.total_instances)"
        print $"  Healthy: ($health.healthy)"
        print $"  Unhealthy: ($health.unhealthy)"
        print $"  Health %: ($health.health_percent)%"
    }

    $health
}

export def "nested-infrastructure-stats" []: record {
    """
    Show nested infrastructure statistics.

    Comprehensive view of all nested components.
    """

    let nesting = (nesting-stats)
    let volumes = (volume-stats)
    let networks = (network-stats)
    let deployments = (deployment-list)

    print "Nested Infrastructure Statistics"
    print "════════════════════════════════════════"
    print ""
    print "Nesting:"
    print $"  Nested VMs: ($nesting.nested_vms)"
    print $"  Containers: ($nesting.containers)"
    print $"  Max Depth: ($nesting.max_nesting_depth)"
    print ""
    print "Storage:"
    print $"  Total Volumes: ($volumes.total_volumes)"
    print $"  Total Size: ($volumes.total_size_gb)GB"
    print $"  Utilization: ($volumes.utilization_percent)%"
    print ""
    print "Networking:"
    print $"  Networks: ($networks.total_networks)"
    print $"  Policies: ($networks.total_policies)"
    print $"  Connections: ($networks.total_connections)"
    print ""
    print "Deployments:"
    print $"  Total: ($deployments | length)"
    print ""

    {
        nesting: $nesting
        volumes: $volumes
        networks: $networks
        deployments: ($deployments | length)
    }
}
