"""Zimbra contacts operations."""

from .api import soap

MAIL_NS = "urn:zimbraMail"


def search(query="*", limit=50):
    """Search contacts."""
    result = soap(MAIL_NS, "SearchRequest", {
        "query": query,
        "types": "contact",
        "sortBy": "nameAsc",
        "limit": limit,
    })
    resp = result.get("SearchResponse", {})
    contacts = resp.get("cn", [])

    output = []
    for c in contacts:
        attrs = {a["n"]: a.get("_content", "") for a in c.get("_attrs", c.get("a", []))}
        output.append({
            "id": c.get("id"),
            "folder": c.get("l"),
            "email": attrs.get("email", ""),
            "first_name": attrs.get("firstName", ""),
            "last_name": attrs.get("lastName", ""),
            "full_name": attrs.get("fullName", ""),
            "company": attrs.get("company", ""),
            "phone": attrs.get("workPhone", attrs.get("mobilePhone", attrs.get("homePhone", ""))),
            "job_title": attrs.get("jobTitle", ""),
        })
    return output


def get(contact_id):
    """Get a contact by ID with all fields."""
    result = soap(MAIL_NS, "GetContactsRequest", {
        "cn": [{"id": str(contact_id)}],
    })
    contacts = result.get("GetContactsResponse", {}).get("cn", [])
    if not contacts:
        raise RuntimeError(f"Contact {contact_id} not found")

    c = contacts[0]
    attrs = {a["n"]: a.get("_content", "") for a in c.get("_attrs", c.get("a", []))}
    return {
        "id": c.get("id"),
        "folder": c.get("l"),
        **attrs,
    }


def create(email, first_name="", last_name="", company="",
           phone="", job_title="", folder_id="7", **extra):
    """Create a contact."""
    attrs = []
    if email:
        attrs.append({"n": "email", "_content": email})
    if first_name:
        attrs.append({"n": "firstName", "_content": first_name})
    if last_name:
        attrs.append({"n": "lastName", "_content": last_name})
    if company:
        attrs.append({"n": "company", "_content": company})
    if phone:
        attrs.append({"n": "mobilePhone", "_content": phone})
    if job_title:
        attrs.append({"n": "jobTitle", "_content": job_title})
    for key, val in extra.items():
        if val:
            attrs.append({"n": key, "_content": str(val)})

    result = soap(MAIL_NS, "CreateContactRequest", {
        "cn": {"l": str(folder_id), "a": attrs},
    })
    cn = result.get("CreateContactResponse", {}).get("cn", [{}])[0]
    return {"success": True, "id": cn.get("id")}


def update(contact_id, **fields):
    """Update a contact. Pass field names as kwargs."""
    attrs = [{"n": k, "_content": str(v)} for k, v in fields.items() if v is not None]
    if not attrs:
        raise ValueError("No fields to update")

    result = soap(MAIL_NS, "ModifyContactRequest", {
        "cn": {"id": str(contact_id), "a": attrs},
    })
    return {"success": True, "id": contact_id}


def delete(contact_id):
    """Delete a contact."""
    soap(MAIL_NS, "ContactActionRequest", {
        "action": {"id": str(contact_id), "op": "trash"},
    })
    return {"success": True, "id": contact_id}
