import frappe

def existing_contact_name(first_name: str, last_name: str, email: str, phone: str) -> str:
    """Check if a contact exists based on provided details."""
    filters = {
        "first_name": first_name,
        "last_name": last_name,
        "email_id": email,
        "phone": phone
    }
    existing_contacts = frappe.db.get_all("Contact", pluck="name", filters=filters)
    return existing_contacts[0] if existing_contacts else None

def get_contact(contact_name: str):
    """Retrieve a contact document by name."""
    contact = frappe.get_doc("Contact", contact_name)
    print("Retrieved existing contact:", contact.as_dict())
    return contact

def check_and_get_contact(first_name: str, last_name: str, email: str, phone: str):
    """Check if a contact exists and return the contact document if found."""
    contact_name = existing_contact_name(first_name, last_name, email, phone)
    if contact_name:
        return get_contact(contact_name)
    return None

def check_and_get_contact_by_name(contact_name: str):
    """Check if a contact exists by name and return the contact document if found."""
    if frappe.db.exists("Contact", contact_name):
        return get_contact(contact_name)
    return None

def create_contact(contact_data: dict):
    """Create a new contact."""
    contact = frappe.get_doc({
        "doctype": "Contact",
        **contact_data
    })
    contact.insert(ignore_permissions=True)
    print("Created new contact:", contact.as_dict())
    return contact

def create_contact_links(contact_docs, client_doc, address_doc):
    print("#####DEBUG: Linking contacts to client and address.")
    for contact_doc in contact_docs:
        contact_doc.address = address_doc.name
        contact_doc.append("links", {
            "link_doctype": client_doc.doctype,
            "link_name": client_doc.name
        })
        contact_doc.append("links", {
            "link_doctype": "Address",
            "link_name": address_doc.name
        })
        contact_doc.custom_customer = client_doc.name
        contact_doc.save(ignore_permissions=True)