"""
Zoho CRM sync orchestrator.

Bridges zoho_client (API calls) and icp_db (DB operations).
Called from webapp routes, webapp background threads, and CLI.
"""

import logging

from icp_db import get_contact_by_id, log_zoho_sync, get_unsynced_icp_contacts
from zoho_client import push_contact_to_zoho, is_configured

logger = logging.getLogger(__name__)


def sync_contact_to_zoho(session, contact_id: int) -> dict:
    """Sync a single contact to Zoho CRM.

    Returns dict with keys: action, zoho_id (on success), reason (on skip/error).
    """
    if not is_configured():
        return {"action": "skip", "reason": "not_configured"}

    contact = get_contact_by_id(session, contact_id)
    if not contact:
        return {"action": "skip", "reason": "contact_not_found"}

    if contact["status"] != "ICP":
        return {"action": "skip", "reason": "not_icp"}

    try:
        result = push_contact_to_zoho(contact)
        log_zoho_sync(
            session,
            contact_id,
            action=result["action"],
            zoho_id=result.get("zoho_id"),
            details=result.get("reason", ""),
        )
        return result
    except Exception as e:
        logger.error("Zoho sync failed for contact %d: %s", contact_id, e)
        log_zoho_sync(
            session,
            contact_id,
            action="error",
            details=str(e)[:500],
        )
        return {"action": "error", "reason": str(e)}


def sync_all_unsynced(session) -> dict:
    """Bulk sync all unsynced ICP contacts.

    Used by admin UI 'Sync All' button and CLI --zoho-sync flag.
    Returns summary dict with synced/errors/skipped/total counts.
    """
    if not is_configured():
        return {"synced": 0, "errors": 0, "skipped": 0, "total": 0,
                "reason": "not_configured"}

    contacts = get_unsynced_icp_contacts(session)
    synced = 0
    errors = 0
    skipped = 0

    for c in contacts:
        result = sync_contact_to_zoho(session, c["id"])
        if result["action"] in ("create", "update"):
            synced += 1
        elif result["action"] == "error":
            errors += 1
        else:
            skipped += 1

    return {
        "synced": synced,
        "errors": errors,
        "skipped": skipped,
        "total": len(contacts),
    }
