"""Deduplikacja leadów względem CRM (cache w pamięci)."""

import logging
import time

from .crm import CRMClient, _norm_phone

log = logging.getLogger(__name__)

CACHE_TTL_SECONDS = 3600  # odśwież cache co 1h


class Deduplicator:
    def __init__(self, crm: CRMClient):
        self.crm = crm
        self._emails: set[str] = set()
        self._phones: set[str] = set()
        self._loaded_at: float = 0.0

    def load(self, force: bool = False) -> None:
        """Pobiera wszystkie istniejące leady z CRM do cache."""
        if not force and self._loaded_at and (time.time() - self._loaded_at) < CACHE_TTL_SECONDS:
            return
        log.info("Loading existing leads from CRM for dedup cache...")
        leads = self.crm.get_all_leads()
        self._emails = {
            (l.get("email") or "").lower().strip()
            for l in leads
            if l.get("email")
        }
        self._phones = {
            _norm_phone(l.get("phone") or "")
            for l in leads
            if l.get("phone")
        }
        self._loaded_at = time.time()
        log.info(
            "Dedup cache loaded: %d leads, %d emails, %d phones",
            len(leads),
            len(self._emails),
            len(self._phones),
        )

    def is_duplicate(self, email: str | None, phone: str | None) -> bool:
        """Sprawdza w cache czy email lub telefon już istnieje w CRM."""
        self.load()  # lazy/refresh
        if email and email.lower().strip() in self._emails:
            return True
        if phone:
            np = _norm_phone(phone)
            if np and np in self._phones:
                return True
        return False

    def remember(self, email: str | None, phone: str | None) -> None:
        """Dodaje świeżo wgranego leada do cache, by uniknąć duplikatów w tej samej sesji."""
        if email:
            self._emails.add(email.lower().strip())
        if phone:
            np = _norm_phone(phone)
            if np:
                self._phones.add(np)
