"""Global opt-out suppression registry.

Append-mostly store of suppressed emails and domains.
Checked at every lead entry point (harvest, renewal scan,
manual create, push gate) to prevent re-contacting.

Auto-populated when a lead is burned with opt-out reason.
"""

import json
import os
from datetime import datetime, timezone
from pathlib import Path


SUPPRESSIONS_PATH = Path(os.environ.get("ABSEL_SUPPRESSIONS_PATH", "data/suppressions.json"))


def _ensure_file():
    SUPPRESSIONS_PATH.parent.mkdir(parents=True, exist_ok=True)
    if not SUPPRESSIONS_PATH.exists():
        _write_suppressions({"emails": {}, "domains": {}})


def _read_suppressions() -> dict:
    _ensure_file()
    try:
        data = json.loads(SUPPRESSIONS_PATH.read_text())
        data.setdefault("emails", {})
        data.setdefault("domains", {})
        return data
    except (json.JSONDecodeError, OSError):
        return {"emails": {}, "domains": {}}


def _write_suppressions(data: dict):
    SUPPRESSIONS_PATH.write_text(json.dumps(data, indent=2))


def is_suppressed(email: str) -> tuple[bool, str]:
    """Check if an email or its domain is suppressed.

    Returns (is_suppressed, reason).
    Checks email exact match first, then domain match.
    """
    if not email or "@" not in email:
        return False, ""
    data = _read_suppressions()
    email_lower = email.lower().strip()
    if email_lower in data.get("emails", {}):
        return True, data["emails"][email_lower].get("reason", "suppressed")
    domain = email_lower.split("@", 1)[1]
    if domain in data.get("domains", {}):
        return True, data["domains"][domain].get("reason", "domain suppressed")
    return False, ""


def suppress_email(email: str, reason: str, source_lead_id: str = ""):
    """Add an email to the suppression list."""
    data = _read_suppressions()
    now = datetime.now(timezone.utc).isoformat()
    data["emails"][email.lower().strip()] = {
        "suppressed_at": now,
        "reason": reason,
        "source_lead_id": source_lead_id,
    }
    _write_suppressions(data)


def suppress_domain(domain: str, reason: str):
    """Add a domain to the suppression list."""
    data = _read_suppressions()
    now = datetime.now(timezone.utc).isoformat()
    data["domains"][domain.lower().strip()] = {
        "suppressed_at": now,
        "reason": reason,
    }
    _write_suppressions(data)


def unsuppress(email_or_domain: str):
    """Remove from suppression list."""
    data = _read_suppressions()
    key = email_or_domain.lower().strip()
    removed = False
    if key in data.get("emails", {}):
        del data["emails"][key]
        removed = True
    if key in data.get("domains", {}):
        del data["domains"][key]
        removed = True
    if removed:
        _write_suppressions(data)


def list_suppressions() -> dict:
    """Return all active suppressions."""
    return _read_suppressions()


def suppression_count() -> tuple[int, int]:
    """Return (email_count, domain_count)."""
    data = _read_suppressions()
    return len(data.get("emails", {})), len(data.get("domains", {}))
