# Enhanced configuration management for provisioning tool

export def load-config [
    config_path: string
    --validate = true
] {
    if not ($config_path | path exists) {
        print $"🛑 Configuration file not found: ($config_path)"
        return {}
    }

    let result = (do { open $config_path } | complete)
    if $result.exit_code != 0 {
        print $"🛑 Error loading configuration from ($config_path): ($result.stderr)"
        {}
    } else {
        let config = $result.stdout
        if $validate {
            validate-config $config
        }
        $config
    }
}

export def validate-config [
    config: record
] {
    let required_fields = ["version", "providers", "servers"]
    let config_keys = ($config | columns)

    mut missing_fields = []
    for field in $required_fields {
        let has_field = ($config_keys | any {|col| $col == $field})
        if not $has_field {
            $missing_fields = ($missing_fields | append $field)
        }
    }

    if ($missing_fields | length) > 0 {
        print "🛑 Missing required configuration fields:"
        for field in $missing_fields {
            print $"  - ($field)"
        }
        return false
    }
    true
}

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

export def get-config-value [
    config: record
    path: string
    default_value?: any
] {
    let path_parts = ($path | split row ".")

    mut current = $config
    for part in $path_parts {
        let cols = ($current | columns)
        let has_part = ($cols | any {|col| $col == $part})

        if not $has_part {
            return ($default_value | default null)
        }

        $current = ($current | get $part)

        if ($current | is-empty) {
            return ($default_value | default null)
        }
    }

    $current
}

export def set-config-value [
    config: record
    path: string
    value: any
] {
    let path_parts = ($path | split row ".")

    if ($path_parts | length) == 1 {
        $config | 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 $config $parent_path {})
        let updated_parent = ($parent | upsert $key $value)
        set-config-value $config $parent_path $updated_parent
    }
}

export def save-config [
    config: record
    config_path: string
    --backup = true
] {
    if $backup and ($config_path | path exists) {
        let backup_path = $"($config_path).backup.(date now | format date '%Y%m%d_%H%M%S')"
        let backup_result = (do { cp $config_path $backup_path } | complete)
        if $backup_result.exit_code != 0 {
            print $"⚠️  Warning: Could not create backup: ($backup_result.stderr)"
        } else {
            print $"💾 Backup created: ($backup_path)"
        }
    }

    let save_result = (do { $config | to yaml | save $config_path } | complete)
    if $save_result.exit_code != 0 {
        print $"🛑 Error saving configuration: ($save_result.stderr)"
        false
    } else {
        print $"✅ Configuration saved to: ($config_path)"
        true
    }
}
