# Enhanced configuration management for provisioning tool

export def load-config [
    config_path: string
    --validate = true
]: record {
    if not ($config_path | path exists) {
        print $"🛑 Configuration file not found: ($config_path)"
        return {}
    }
    
    try {
        let config = (open $config_path)
        if $validate {
            validate-config $config
        }
        $config
    } catch {|err|
        print $"🛑 Error loading configuration from ($config_path): ($err.msg)"
        {}
    }
}

export def validate-config [
    config: record
]: bool {
    let required_fields = ["version", "providers", "servers"]
    let missing_fields = ($required_fields | where {|field| 
        ($config | get -o $field | is-empty)
    })
    
    if ($missing_fields | length) > 0 {
        print "🛑 Missing required configuration fields:"
        $missing_fields | each {|field| print $"  - ($field)"}
        return false
    }
    true
}

export def merge-configs [
    base_config: record
    override_config: record
]: record {
    $base_config | merge $override_config
}

export def get-config-value [
    config: record
    path: string
    default_value?: any
]: any {
    let path_parts = ($path | split row ".")
    let mut current = $config
    
    for part in $path_parts {
        if ($current | get -o $part | is-empty) {
            return $default_value
        }
        $current = ($current | get $part)
    }
    
    $current
}

export def set-config-value [
    config: record
    path: string
    value: any
]: record {
    let path_parts = ($path | split row ".")
    let mut result = $config
    
    if ($path_parts | length) == 1 {
        $result | upsert $path_parts.0 $value
    } else {
        let key = ($path_parts | last)
        let parent_path = ($path_parts | range 0..-1 | str join ".")
        let parent = (get-config-value $result $parent_path {})
        let updated_parent = ($parent | upsert $key $value)
        set-config-value $result $parent_path $updated_parent
    }
}

export def save-config [
    config: record
    config_path: string
    --backup = true
]: bool {
    if $backup and ($config_path | path exists) {
        let backup_path = $"($config_path).backup.(date now | format date '%Y%m%d_%H%M%S')"
        try {
            cp $config_path $backup_path
            print $"💾 Backup created: ($backup_path)"
        } catch {|err|
            print $"⚠️  Warning: Could not create backup: ($err.msg)"
        }
    }
    
    try {
        $config | to yaml | save $config_path
        print $"✅ Configuration saved to: ($config_path)"
        true
    } catch {|err|
        print $"🛑 Error saving configuration: ($err.msg)"
        false
    }
} 