"""Webapp-side Zoho sync helpers (non-blocking triggers)."""

import threading
import logging

logger = logging.getLogger(__name__)


def trigger_zoho_sync(contact_id: int):
    """Fire-and-forget Zoho sync in a background thread.

    Safe to call even if Zoho is not configured — exits immediately.
    The thread opens its own DB session so the caller's request
    is not blocked or affected.
    """
    from zoho_client import is_configured
    if not is_configured():
        return

    def _sync():
        from icp_db import get_session
        from zoho_sync import sync_contact_to_zoho
        session = get_session()
        try:
            sync_contact_to_zoho(session, contact_id)
        except Exception as e:
            logger.error("Background Zoho sync failed for contact %d: %s", contact_id, e)
        finally:
            session.close()

    threading.Thread(target=_sync, daemon=True).start()
