
export-env {
    # Get infrastructure path (early return if not set)
    let infra_path = if ("CURRENT_INFRA_PATH" in $env) { $env.CURRENT_INFRA_PATH } else { "" }
    if ($infra_path | is-empty) {
        return
    }

    # Check vault-service configuration
    let vault_url = if ("VAULT_SERVICE_URL" in $env) { $env.VAULT_SERVICE_URL } else { "" }
    let vault_env = if ("PROVISIONING_ENV" in $env) { $env.PROVISIONING_ENV } else { "dev" }
    let use_vault = (not ($vault_url | is-empty)) and ($vault_url | str starts-with "http")

    if $use_vault {
        # Attempt to fetch public key from vault-service
        let response = (http get $"($vault_url)/api/v1/age/get-public?env=($vault_env)" | complete)

        if $response.exit_code == 0 {
            let json = ($response.stdout | from json)
            let public_key = ($json | get -o public_key | default "")

            if not ($public_key | is-empty) {
                $env.SOPS_AGE_RECIPIENTS = $public_key
                print $"✓ Age public key loaded from vault-service for ($vault_env)"
                return
            }
        }

        print "⚠️ Could not fetch Age key from vault-service, using filesystem fallback"
    }

    # Fallback: Load from filesystem
    let kloud_path = if ("CURRENT_KLOUD_PATH" in $env) { $env.CURRENT_KLOUD_PATH } else { "" }
    let base_path = if ($kloud_path | is-empty) { $infra_path } else { $kloud_path }

    $env.PROVISIONING_SOPS = (get_def_sops $base_path)
    $env.PROVISIONING_KAGE = (get_def_age $base_path)

    # Parse filesystem Age key
    let kage_file = if ("PROVISIONING_KAGE" in $env) { $env.PROVISIONING_KAGE } else { "" }
    if not ($kage_file | is-empty) {
        $env.SOPS_AGE_KEY_FILE = $kage_file

        let key_line = (grep "public key:" $env.SOPS_AGE_KEY_FILE | head -n 1 | default "")
        let key_parts = ($key_line | split row ":" | each { |x| $x | str trim })
        let public_key = if ($key_parts | length) > 1 { $key_parts | get 1 } else { "" }

        if not ($public_key | is-empty) {
            $env.SOPS_AGE_RECIPIENTS = $public_key
        } else {
            print $"❗Error no key found in (_ansi red_bold)($kage_file)(_ansi reset) file"
            exit 1
        }
    }
}
