# Platform Service Auto-Start

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

# Get binary name from service name
def get-binary-name [service: string] {
    let name = ($service | str replace "_" "-")
    $"provisioning-($name)"
}

# Get config directory for service
def get-service-config-dir [] {
    if ($nu.os-info.name == "macos") {
        $"($env.HOME)/Library/Application Support/provisioning/platform"
    } else {
        $"($env.HOME)/.config/provisioning/platform"
    }
}

# Build environment variables for service
def build-service-env [service: string] {
    let cfg_dir = (get-service-config-dir)
    let base_env = {RUST_LOG: "info"}

    match $service {
        "orchestrator" => {
            $base_env
            | insert PROVISIONING_CONFIG_DIR $cfg_dir
            | insert ORCHESTRATOR_MODE "local"
        }
        "vault_service" => {
            $base_env
            | insert PROVISIONING_CONFIG_DIR $cfg_dir
            | insert VAULT_SERVICE_MODE "local"
        }
        "control_center" => {
            $base_env
            | insert PROVISIONING_CONFIG_DIR $cfg_dir
            | insert CONTROL_CENTER_MODE "local"
        }
        "ai_service" => {
            $base_env
            | insert PROVISIONING_CONFIG_DIR $cfg_dir
            | insert AI_SERVICE_MODE "local"
        }
        "extension_registry" => {
            $base_env
            | insert PROVISIONING_CONFIG_DIR $cfg_dir
            | insert EXTENSION_REGISTRY_MODE "local"
        }
        _ => $base_env
    }
}

# Start a platform service
export def start-service [service: string] {
    let config = (get-deployment-service-config $service)
    let enabled = ($config.enabled? | default false)

    if not $enabled {
        print $"⊘ ($service) is disabled in deployment-mode.ncl"
        return false
    }

    if (check-service-health $service) {
        print $"✓ ($service) is already running"
        return true
    }

    let port = (
        if (($config.server?) != null) {
            $config.server.port
        } else {
            $config.port? | default null
        }
    )

    let binary_name = (get-binary-name $service)
    let binary_path = $"($env.HOME)/.local/bin/($binary_name)"

    if not ($binary_path | path exists) {
        print $"✗ Binary not found: ($binary_path)"
        return false
    }

    let log_dir = $"($env.HOME)/.provisioning/logs"
    ^mkdir -p $log_dir

    let log_file = $"($log_dir)/($service).log"
    let env_vars = (build-service-env $service)

    print $"→ Starting ($service) on port ($port)..."

    let log_dir_expanded = ($log_dir | path expand)
    ^mkdir -p $log_dir_expanded

    let cfg_dir = (get-service-config-dir)
    let log_expanded = ($log_file | path expand)
    let start_cmd = $"env RUST_LOG=info PROVISIONING_CONFIG_DIR='($cfg_dir)' '($binary_path)' > '($log_expanded)' 2>&1 &"

    # Execute the command via shell to handle background execution and redirections
    ^sh -c $start_cmd

    sleep 2sec

    if (check-service-health $service) {
        print $"✓ ($service) started on port ($port)"
        return true
    } else {
        print $"✗ ($service) failed to start - check logs at ($log_file)"
        return false
    }
}

# Stop a platform service
export def stop-service [service: string] {
    print $"Stopping service: ($service)"
}

# Restart a platform service
export def restart-service [service: string] {
    stop-service $service
    sleep 1sec
    start-service $service
}

# Start all enabled services
export def start-required-services [] {
    let enabled_services = (get-enabled-services)

    if ($enabled_services | is-empty) {
        print "⊘ No services enabled in deployment-mode.ncl"
        return
    }

    let count = ($enabled_services | length)
    print $"Starting ($count) enabled service\(s\)..."
    print ""

    let failed = (
        $enabled_services | reduce --fold [] {|item, acc|
            let service = $item.name
            if (start-service $service) {
                $acc
            } else {
                $acc | append $service
            }
        }
    )

    print ""
    if (($failed | length) > 0) {
        let fail_count = ($failed | length)
        print $"⚠ ($fail_count) service\(s\) failed to start:"
        $failed | each {|svc|
            print $"  - ($svc)"
        }
    } else {
        print "✓ All enabled services started successfully"
    }
}

# Get status of all services
export def get-service-status [] {
    get-enabled-services | each {|item|
        let healthy = (check-service-health $item.name)
        {
            service: $item.name
            status: (if $healthy { "running" } else { "stopped" })
        }
    }
}

# Enable auto-start
export def enable-autostart [service: string] {
    print $"Enabled auto-start for: ($service)"
}

# Disable auto-start
export def disable-autostart [service: string] {
    print $"Disabled auto-start for: ($service)"
}
