aws-sso-login() {
    local profile="${1:-$AWS_PROFILE}"

    if [[ -z "$profile" ]]; then
        profile=$(aws configure list-profiles \
          | fzf --height 40% --reverse --no-preview)
    fi

    if [[ -z "$profile" ]]; then
        echo "Error: No profile provided or selected." >&2
        return 1
    fi

    # Validate existing session; login if expired or missing
    if ! aws sts get-caller-identity --profile "$profile" &>/dev/null; then
        aws sso login --use-device-code --profile "$profile" || return 1
    fi

    # Export credentials to environment for third-party tools
    local creds
    creds=$(aws configure export-credentials --profile "$profile" --format env)
    if [[ $? -eq 0 ]]; then
        eval "$creds"
        export AWS_PROFILE="$profile"
        # echo "Environment configured for profile: $profile"
    else
        echo "Error: Failed to export credentials." >&2
        return 1
    fi
}
