import frappe

# Override ERPNext's hook that will set a Lead's mobile_no field based on a Contact's phone number even if it's not a mobile number
def update_lead_phone_numbers(contact, method):
    if not contact.phone_nos:
        return

    contact_lead = contact.get_link_for("Lead")
    if not contact_lead:
        return

    # Get list of phones explicitly marked as primary mobile numbers
    mobile_nos = [
        phone_doc.phone
        for phone_doc in contact.phone_nos
        if phone_doc.is_primary_mobile_no
    ]

    # If no mobile numbers were marked, clear Lead.mobile_no
    if not mobile_nos:
        lead = frappe.get_doc("Lead", contact_lead)

        if lead.mobile_no:
            # Optional: only unset if the current value matches one of the Contact's phones
            contact_phone_values = {p.phone for p in contact.phone_nos}
            if lead.mobile_no in contact_phone_values:
                lead.db_set("mobile_no", None)
