# utils.py

def is_sa_instance(obj) -> bool:
    return hasattr(obj, "_sa_instance_state")


def get_field(obj, name, default=None):
    return obj.get(name, default) if isinstance(obj, dict) else getattr(obj, name, default)


def set_field(obj, **updates):
    if isinstance(obj, dict):
        new_obj = dict(obj)
        new_obj.update(updates)
        return new_obj

    if hasattr(obj, "model_copy"):
        return obj.model_copy(update=updates)

    for k, v in updates.items():
        setattr(obj, k, v)
    return obj


def split_item(order_products, idx, qty, waiter_id):
    op = order_products[idx]
    original_qty = get_field(op, "quantity", 0)

    assigned = set_field(op, quantity=qty, waiter_id=waiter_id)
    remaining_qty = original_qty - qty

    if remaining_qty <= 0:
        order_products[idx] = assigned
        return None

    order_products[idx] = set_field(op, quantity=remaining_qty)
    return assigned
