# Configuration merging helper functions
# NUSHELL 0.109 COMPLIANT - Using reduce --fold (Rule 3), no mutable variables

# Deep merge two configuration records (right takes precedence)
# Uses reduce --fold instead of mutable variables (Nushell 0.109 Rule 3)
export def deep-merge [
    base: record
    override: record
]: record -> record {
    $override | columns | reduce --fold $base {|key, result|
        let override_value = ($override | get $key)
        let base_result = (do { $base | get $key } | complete)
        let base_value = if $base_result.exit_code == 0 { $base_result.stdout } else { null }

        if ($base_value | is-empty) {
            # Key doesn't exist in base, add it
            ($result | insert $key $override_value)
        } else if (($base_value | describe) | str starts-with "record") and (($override_value | describe) | str starts-with "record") {
            # Both are records, merge recursively (Nushell Rule 1: type detection via describe)
            ($result | upsert $key (deep-merge $base_value $override_value))
        } else {
            # Override the value
            ($result | upsert $key $override_value)
        }
    }
}
