import time
import httpx
import logging

from .. import settings

log = logging.getLogger(__name__)

# in-memory throttle: key -> last_ts
_last_notify: dict[str, float] = {}


def _should_notify(key: str, min_interval_sec: int = 300) -> bool:
    now = time.time()
    last = _last_notify.get(key)
    if last is not None and (now - last) < min_interval_sec:
        return False
    _last_notify[key] = now
    return True


async def send_slack(text: str, key: str = "default", min_interval_sec: int = 60):
    if not getattr(settings, "SLACK_WEBHOOK_URL", ""):
        log.debug("Slack webhook not configured; skipping notification for key=%s", key)
        return
    if not _should_notify(key, min_interval_sec=min_interval_sec):
        log.debug(
            "Notification throttled for key=%s (min_interval=%ss)",
            key,
            min_interval_sec,
        )
        return
    try:
        async with httpx.AsyncClient(timeout=10) as c:
            resp = await c.post(settings.SLACK_WEBHOOK_URL, json={"text": text})
            if resp.status_code >= 300:
                log.debug(
                    "Slack webhook responded with %s: %s",
                    resp.status_code,
                    resp.text[:200],
                )
    except Exception as e:
        # Best-effort only; do not propagate errors
        log.debug("Slack notification failed: %s", e)


async def notify_approval_request(
    org_name: str, requester: str, total: int, job_id: str
):
    text = (
        "\U0001f9e9 L2A bulk needs approval\n"
        f"• Org: {org_name}\n"
        f"• Requested by: {requester}\n"
        f"• Leads: {total}\n"
        f"• Job: `{job_id}`"
    )
    await send_slack(text, key=f"approve:{org_name}", min_interval_sec=60)


async def notify_job_done(
    org_name: str, job_id: str, status: str, applied: int, skipped: int, errors: int
):
    emoji = "✅" if status == "completed" else ("⛔️" if status == "canceled" else "❌")
    text = (
        f"{emoji} L2A bulk finished ({status})\n"
        f"• Org: {org_name}\n"
        f"• Job: `{job_id}`\n"
        f"• Applied: {applied} • Skipped: {skipped} • Errors: {errors}"
    )
    await send_slack(text, key=f"done:{org_name}", min_interval_sec=60)


# ===== C2A variants =====


async def notify_c2a_approval_request(
    org_name: str, requester: str, total: int, job_id: str
):
    text = (
        "🧭 C2A job needs approval\n"
        f"• Org: {org_name}\n"
        f"• Requested by: {requester}\n"
        f"• Contacts: {total}\n"
        f"• Job: `{job_id}`"
    )
    await send_slack(text, key=f"c2a-approve:{org_name}", min_interval_sec=60)


async def notify_c2a_job_done(
    org_name: str,
    job_id: str,
    status: str,
    created: int,
    skipped_b2c: int,
    conflicts: int,
):
    emoji = "✅" if status == "completed" else ("⏹️" if status == "canceled" else "⚠️")
    text = (
        f"{emoji} C2A job finished ({status})\n"
        f"• Org: {org_name}\n"
        f"• Job: `{job_id}`\n"
        f"• Suggestions: {created} • B2C Skipped: {skipped_b2c} • Conflicts: {conflicts}"
    )
    await send_slack(text, key=f"c2a-done:{org_name}", min_interval_sec=60)
