"""Direct IFTTT bridge — publish platform events to automation.inbox.

Any EmpowerNow service can import this helper to fire events into the
UEAS IFTTT engine without relying on the CRUDService Platform Event Bridge
worker. The bridge worker (topic-level subscription) and this helper
(direct per-service publish) are complementary paths into automation.inbox.

Usage
-----
from empowernow_common.kafka.ifttt_bridge import publish_to_ifttt

await publish_to_ifttt(
    event_type="identity.login",
    source="idp",
    source_instance="idp_primary",
    subject_key="sub:auth:account:empowernow:jsmith",
    attrs={"account_arn": "auth:account:empowernow:jsmith", "provider": "empowernow"},
    correlation_id="abc-123",
)

The function builds a NormalizedEvent-compatible dict and publishes it to
the automation.inbox Kafka topic where the UEAS NormalizerWorker picks it up.
"""
from __future__ import annotations

import hashlib
import json
import logging
from datetime import datetime, timezone
from typing import Any
from uuid import UUID, uuid5

logger = logging.getLogger(__name__)

UEAS_NAMESPACE = UUID("a3b8c9d0-1234-5678-9abc-def012345678")
IFTTT_TOPIC = "automation.inbox"


def _uuid5_from(*parts: str) -> str:
    return str(uuid5(UEAS_NAMESPACE, ":".join(parts)))


def _sha256(data: str) -> str:
    return hashlib.sha256(data.encode("utf-8")).hexdigest()


async def publish_to_ifttt(
    event_type: str,
    source: str,
    source_instance: str,
    subject_key: str,
    attrs: dict[str, Any],
    correlation_id: str | None = None,
    occurred_at: str | None = None,
    dedupe_window_seconds: int = 60,
) -> bool:
    """Publish a NormalizedEvent to automation.inbox for IFTTT processing.

    Returns True if published, False if Kafka unavailable or publish failed.
    Best-effort — failures are logged, never raised.
    """
    from empowernow_common.kafka.platform_producer import publish

    now = datetime.now(timezone.utc)

    payload_json = json.dumps(
        {"event_type": event_type, "source": source, "attrs": attrs},
        sort_keys=True,
        default=str,
    )
    payload_sha256 = _sha256(payload_json)

    epoch_bucket = str(int(now.timestamp()) // dedupe_window_seconds)
    dedupe_basis = (
        f"{source}|{source_instance}|{event_type}"
        f"|{subject_key}|{payload_sha256}|{epoch_bucket}"
    )
    dedupe_key = _sha256(dedupe_basis)

    corr_id = (
        _uuid5_from("corr", correlation_id)
        if correlation_id
        else _uuid5_from(source_instance, dedupe_key)
    )

    event: dict[str, Any] = {
        "event_id": _uuid5_from("event", dedupe_key),
        "event_type": event_type,
        "source": source,
        "source_instance": source_instance,
        "subject_key": subject_key,
        "occurred_at": occurred_at,
        "received_at": now.isoformat(),
        "correlation_id": corr_id,
        "payload_ref": f"inline:{payload_sha256[:16]}",
        "payload_sha256": payload_sha256,
        "dedupe_key": dedupe_key,
        "attrs": attrs,
    }

    try:
        await publish(IFTTT_TOPIC, key=subject_key, value=event)
        logger.debug(
            "Published to %s: event_type=%s subject_key=%s",
            IFTTT_TOPIC, event_type, subject_key,
        )
        return True
    except Exception as exc:
        logger.warning("Failed to publish IFTTT event: %s (event_type=%s)", exc, event_type)
        return False
