"""Zoho dedup — check if an email already exists in Zoho CRM.

Three-layer dedup: suppression registry → backlog dedup → Zoho dedup.
Layer 3 (this module) checks Zoho Leads and Contacts modules.

Two modes:
  Per-lead:  is_in_zoho(email) — one API call per check
  Batch:     build_zoho_email_sets() → check_email_in_sets() — pre-fetches all
             emails, O(1) lookups. Preferred for harvest/import batches.
"""

from shared.zoho.client import search_records, list_all_records


def is_in_zoho(email: str) -> tuple[bool, str]:
    """Check if an email exists in Zoho Leads or Contacts.

    Per-lead mode — one API call per check. Use for single-lead
    operations (manual renewals, individual import).

    Returns (exists, context) where context is the Zoho record info.
    API errors fail open (email treated as not found).
    """
    if not email or "@" not in email:
        return False, ""

    leads = search_records("Leads", f"(Email:equals:{email})",
                            fields="id,Company,Last_Name")
    if leads:
        name = leads[0].get("Company", leads[0].get("Last_Name", "?"))
        return True, f"Lead: {name} (ID: {leads[0].get('id', '?')})"

    contacts = search_records("Contacts", f"(Email:equals:{email})",
                               fields="id,Full_Name")
    if contacts:
        name = contacts[0].get("Full_Name", "?")
        return True, f"Contact: {name} (ID: {contacts[0].get('id', '?')})"

    return False, ""


def build_zoho_email_sets() -> tuple[set, set]:
    """Pre-fetch ALL Zoho Lead and Contact emails into local sets.

    Batch mode — 2-4 API calls total (paginated), then O(1) lookups.
    Preferred for harvest/import where many leads are checked at once.

    Returns (lead_emails: set[str], contact_emails: set[str]).
    """
    leads = list_all_records("Leads", fields="Email,id")
    contacts = list_all_records("Contacts", fields="Email,id")

    lead_emails = set()
    for l in leads:
        email = (l.get("Email") or "").lower().strip()
        if email:
            lead_emails.add(email)

    contact_emails = set()
    for c in contacts:
        email = (c.get("Email") or "").lower().strip()
        if email:
            contact_emails.add(email)

    return lead_emails, contact_emails


def check_email_in_sets(email: str, lead_emails: set, contact_emails: set) -> tuple[bool, str]:
    """Check against pre-fetched email sets (batch mode).

    Returns (exists, context).
    """
    e = email.lower().strip()
    if e in lead_emails:
        return True, "Lead (exists in Zoho)"
    if e in contact_emails:
        return True, "Contact (exists in Zoho)"
    return False, ""
