"""
Push near-real-time staff-performance refresh events to the CRM.

Settings (URL + secret) are read from CompanyIntegrationSettings in the database,
configured in System Admin → Integration.
"""
from __future__ import annotations

import logging
import threading

import requests

logger = logging.getLogger(__name__)


def _post(url, secret, staff_ids):
    try:
        requests.post(
            url,
            json={"staff_id": ",".join(staff_ids)},
            headers={"X-Webhook-Secret": secret or ""},
            timeout=8,
        )
    except Exception as exc:  # noqa: BLE001 — never break the caller
        logger.warning("CRM performance webhook failed: %s", exc)


def _resolve_webhook_config():
    from system_administration.host_policy import resolve_crm_webhook

    return resolve_crm_webhook("crm_performance_webhook_url")


def notify_crm_staff_performance(staff_ids):
    """Queue a CRM performance refresh for the given ERP staff id(s)."""
    url, secret = _resolve_webhook_config()
    if not url:
        return

    clean = []
    for sid in staff_ids or []:
        if sid is None:
            continue
        text = str(sid).strip()
        if text and text not in clean:
            clean.append(text)
    if not clean:
        return

    threading.Thread(target=_post, args=(url, secret, clean), daemon=True).start()


def account_manager_staff_ids_for_order(order):
    """Staff whose performance is affected by this order: the customer's account
    manager (ERP performance is attributed by CustomerAccountManager), plus the
    sales person / creator as a fallback."""
    ids = []
    try:
        from sales_and_marketing.models import CustomerAccountManager

        customer = getattr(order, "customer_profile", None)
        if customer is not None:
            cam = CustomerAccountManager.objects.filter(customer_profile=customer).first()
            if cam and cam.staff_profile_id:
                ids.append(cam.staff_profile_id)
    except Exception as exc:  # noqa: BLE001
        logger.warning("account manager lookup failed: %s", exc)

    for attr in ("sales_person_id", "created_by_id"):
        sid = getattr(order, attr, None)
        if sid:
            ids.append(sid)
    return ids
