Problem with rotating objects by script
My take on this


  the aim is to reorient all selected mesh objects to have their local x
  axis along their longest edges. Every object receives different
  rotation



Get all the meshes of selected objects, could be anything from 1 (all
share same mesh) to having a mesh each.
Find the longest edge of each, rotate mesh about origin such that x
axis aligns.  Keep the inverse transform of this rotation.
For each selected object transform by inverse. (ie rotate back to orginal global orientation with new local axis)
Used rotation difference of two vectors. Using rotation difference of
two tracking quats would help with aligning up axis too.
Assumes all meshes have at least one edge, used bmesh purely for
BMEdge.calc_length() could use mesh data directly.


Test script.

import bpy
import bmesh
from mathutils import Vector

context = bpy.context
ob = context.object
meshes = set(o.data for o in context.selected_objects if o.type == 'MESH')

bm = bmesh.new()
lut = {}
for me in meshes:
    bm.from_mesh(me)
    le = sorted(bm.edges, key=lambda e: e.calc_length()).pop()
    axis = (le.verts[1].co - le.verts[0].co).normalized()
    q = axis.rotation_difference(Vector((1, 0, 0)))
    R =  q.to_matrix()
    me.transform(R.to_4x4())
    lut[me] = R.inverted().to_4x4()
    bm.clear()

for o in (o for o in context.selected_objects if o.type == 'MESH'):
    o.matrix_world @= lut[o.data]