# Platform Service Health Checks

# Selective imports (ADR-025 Phase 3 Layer 2).
use lib_provisioning/platform/target.nu [get-deployment-service-config get-enabled-services]

# Check if service is healthy at its port
export def check-service-health [service: string] {
    let config = (get-deployment-service-config $service)
    let enabled = ($config.enabled? | default false)

    if not $enabled {
        return false
    }

    # Extract port
    let port = (
        if (($config.server?) != null) {
            $config.server.port
        } else if (($config.port?) != null) {
            $config.port
        } else {
            return false
        }
    )

    # Check using platform-specific command — always filter by port to avoid full scan
    if ($nu.os-info.name == "macos") {
        let result = (do { ^lsof -i $":($port)" -P -n } | complete)
        ($result.exit_code == 0) and ($result.stdout | str contains "LISTEN")
    } else {
        let result = (do { ^ss -tlnp $"sport = :($port)" } | complete)
        if ($result.exit_code == 0) {
            ($result.stdout | lines | skip 1 | length) > 0
        } else {
            # fallback: netstat with port grep
            let r2 = (do { ^netstat -tlnp } | complete)
            ($r2.exit_code == 0) and ($r2.stdout | str contains $":($port) ")
        }
    }
}

# Check all enabled services
export def check-all-services [] {
    let services = (get-enabled-services)

    $services | each {|item|
        let healthy = (check-service-health $item.name)
        {
            name: $item.name
            status: (if $healthy { "healthy" } else { "unhealthy" })
            priority: $item.priority
        }
    }
}

# Get health status for all services
export def check-required-services [] {
    check-all-services
}

# Wait for service to become healthy
export def wait-for-service [service: string, --timeout_seconds: int = 30] {
    let max_attempts = 60
    let attempt_list = (seq 1 $max_attempts)

    let results = (
        $attempt_list | each {|_attempt|
            if (check-service-health $service) {
                "healthy"
            } else {
                sleep 500ms
                "checking"
            }
        }
    )

    ($results | any {|status| $status == "healthy"})
}
