# Show details for a specific infrastructure
# INFRA_NAME env var must be set by caller
# Sourced by bash after lib_minimal.nu is loaded — not meant to be run standalone

let infra_name = ($env.INFRA_NAME? | default "")
if ($infra_name | is-empty) {
    print "No infrastructure specified. Use: prvng infra info <name>"
    exit 1
}

let ws_result = (workspace-active)
let ws_name = if (is-ok $ws_result) { $ws_result.ok } else { "" }
if ($ws_name | is-empty) {
    print 'No active workspace'
    exit 1
}

let user_config = (get-user-config-path)
if not ($user_config | path exists) {
    print 'Config not found'
    exit 1
}

let config = (open $user_config)
let ws = ($config | get --optional workspaces | default [] | where { $in.name == $ws_name } | first)
if ($ws | is-empty) {
    print 'Workspace not found'
    exit 1
}

let infra_path = ($ws.path | path join 'infra' | path join $infra_name)
if not ($infra_path | path exists) {
    print $"Infrastructure '($infra_name)' not found in workspace '($ws_name)'"
    exit 1
}

# Servers
let sf_direct = ($infra_path | path join 'servers.ncl')
let sf_defs   = ($infra_path | path join 'defs' | path join 'servers.ncl')
let sf = if ($sf_direct | path exists) { $sf_direct } else { $sf_defs }
let servers = if ($sf | path exists) {
    open $sf --raw
    | split row "\n"
    | where {|l| $l =~ 'hostname\s*=\s*"' }
    | each {|l|
        let parts = ($l | split row '"')
        if ($parts | length) >= 2 { $parts | get 1 } else { "" }
    }
    | where {|h| $h | is-not-empty }
} else { [] }

# Known config files
let config_files = ['servers.ncl' 'firewalls.ncl' 'settings.ncl' 'main.ncl']
    | where {|f| ($infra_path | path join $f) | path exists }

# Taskservs dirs
let taskservs_path = ($infra_path | path join 'taskservs')
let taskservs = if ($taskservs_path | path exists) {
    ls $taskservs_path | where type == 'dir' | each {|d| $d.name | path basename }
} else { [] }

let default_infra = ($ws | get --optional default_infra | default "")
let is_default = $infra_name == $default_infra

print $"🏗️  Infrastructure: ($infra_name)(if $is_default { ' ★ (default)' } else { '' })"
print $"   Workspace: ($ws_name)"
print ""

if ($servers | is-empty) {
    print "🖥️  Servers: (none defined)"
} else {
    print $"🖥️  Servers (($servers | length)):"
    $servers | each {|s| print $"   • ($s)" } | ignore
}

print ""

if ($config_files | is-not-empty) {
    print $"📄 Config: ($config_files | str join ', ')"
}

if ($taskservs | is-not-empty) {
    print $"⚙️  Taskservs: ($taskservs | str join ', ')"
}
