import logging
import re
from datetime import timedelta

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.utils import timezone

from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import CompanyMembership, User
from apps.notifications.models import (
    Notification,
    NotificationDelivery,
    NotificationEvent,
    NotificationGlobalConfiguration,
    NotificationPreference,
    NotificationRecipientState,
)
from apps.tenancy.models import Company

logger = logging.getLogger(__name__)

SENSITIVE_KEYS_RE = re.compile(r"(password|secret|token|staff_code|private_key|api_key)", re.I)


def sanitize_payload(obj):
    if isinstance(obj, dict):
        return {
            str(k): ("[REDACTED]" if SENSITIVE_KEYS_RE.search(str(k)) else sanitize_payload(v))
            for k, v in obj.items()
        }
    if isinstance(obj, list):
        return [sanitize_payload(x) for x in obj]
    return obj


def _serialize_notification_push(notif: Notification, state: NotificationRecipientState | None = None) -> dict:
    st = state or getattr(notif, "state", None)
    sender_name = "Maya OS System"
    sender_avatar = None
    if notif.sender:
        sender_name = notif.sender.full_name or notif.sender.username
        if hasattr(notif.sender, "avatar") and notif.sender.avatar:
            sender_avatar = f"/api/profile/avatar/{notif.sender_id}/?thumb=1"
    return {
        "id": str(notif.id),
        "company_id": str(notif.company_id) if notif.company_id else None,
        "event_type": notif.event_type,
        "title": notif.title,
        "message": notif.message,
        "description": notif.description,
        "priority": notif.priority,
        "category": notif.category,
        "module": notif.module,
        "popup_kind": notif.popup_kind,
        "source_object_type": notif.source_object_type,
        "source_object_id": notif.source_object_id,
        "source_reference": notif.source_reference,
        "route_key": notif.route_key,
        "action_definition": notif.action_definition or {},
        "metadata": notif.metadata or {},
        "is_mandatory_critical": notif.is_mandatory_critical,
        "status": notif.status,
        "sender_id": str(notif.sender_id) if notif.sender_id else None,
        "sender_name": sender_name,
        "sender_avatar": sender_avatar,
        "created_at": notif.created_at.isoformat() if notif.created_at else timezone.now().isoformat(),
        "is_read": st.is_read if st else False,
        "read_at": st.read_at.isoformat() if st and st.read_at else None,
        "is_archived": st.is_archived if st else False,
        "dismissed_at": st.dismissed_at.isoformat() if st and st.dismissed_at else None,
        "acknowledged_at": st.acknowledged_at.isoformat() if st and st.acknowledged_at else None,
        "executed_action": st.executed_action if st else "",
    }


def _broadcast_ws_notification(user_id, payload: dict) -> None:
    layer = get_channel_layer()
    if not layer:
        return
    try:
        async_to_sync(layer.group_send)(
            f"notif_user_{user_id}",
            {"type": "notification.event", "payload": payload},
        )
    except Exception:
        logger.debug("WebSocket notification push deferred (outbox retains record)", exc_info=True)


def broadcast_notification_force_disconnect(user_id, reason: str = "Session revoked") -> None:
    layer = get_channel_layer()
    if not layer:
        return
    try:
        async_to_sync(layer.group_send)(
            f"notif_user_{user_id}",
            {"type": "force.disconnect", "reason": reason},
        )
    except Exception:
        pass


class NotificationConfigService:
    @staticmethod
    def get_config(company: Company) -> NotificationGlobalConfiguration:
        cfg, _ = NotificationGlobalConfiguration.objects.get_or_create(company=company)
        return cfg

    @staticmethod
    def get_user_preferences(user: User) -> tuple[NotificationPreference, dict[str, NotificationPreference]]:
        general, _ = NotificationPreference.objects.get_or_create(user=user, category="ALL")
        modules = {p.category: p for p in NotificationPreference.objects.filter(user=user).exclude(category="ALL")}
        return general, modules

    @staticmethod
    def is_suppressed_by_user(
        *,
        user: User,
        category: str,
        module: str,
        priority: str,
        is_mandatory_critical: bool,
    ) -> bool:
        # Critical mandatory security / system alerts cannot be silently suppressed
        if is_mandatory_critical or priority == Notification.Priority.CRITICAL:
            return False

        general, modules = NotificationConfigService.get_user_preferences(user)
        if general.dnd_enabled or general.delivery_mode == "MUTED":
            return True

        now_t = timezone.localtime().time()
        s, e = general.quiet_hours_start, general.quiet_hours_end
        if s and e:
            in_quiet = (s <= now_t <= e) if s <= e else (now_t >= s or now_t <= e)
            if in_quiet:
                return True

        mod_pref = modules.get((module or "").upper()) or modules.get(category)
        if mod_pref and mod_pref.delivery_mode == "MUTED":
            return True
        return False


class DomainEventService:
    """
    Transactional Outbox + Deduplicated Notification Router.
    Business actions publish here AFTER transaction commit (`transaction.on_commit`)
    or within atomic blocks using `on_commit=True` (default).
    """

    @staticmethod
    def resolve_recipients(
        *,
        company: Company | None,
        explicit_recipient_ids: list | None = None,
        required_permission: str | None = None,
        exclude_user_id=None,
        project_id=None,
    ) -> list[User]:
        if explicit_recipient_ids is not None:
            qs = User.objects.filter(id__in=explicit_recipient_ids, is_active=True)
            if company:
                qs = qs.filter(memberships__company=company, memberships__is_active=True).distinct()
            if exclude_user_id:
                qs = qs.exclude(id=exclude_user_id)
            return list(qs)

        if not company:
            qs = User.objects.filter(is_superuser=True, is_active=True)
            if exclude_user_id:
                qs = qs.exclude(id=exclude_user_id)
            return list(qs)

        memberships = (
            CompanyMembership.objects.select_related("user", "role")
            .prefetch_related("roles", "projects")
            .filter(company=company, is_active=True, user__is_active=True)
        )
        recipients: list[User] = []
        seen = set()
        for mem in memberships:
            if exclude_user_id and str(mem.user_id) == str(exclude_user_id):
                continue
            if required_permission and not mem.user.is_superuser:
                if required_permission not in set(mem.effective_permissions()):
                    continue
            if project_id and not mem.user.is_superuser and mem.data_scope in (
                CompanyMembership.DataScope.PROJECT,
                CompanyMembership.DataScope.SITE,
            ):
                if not mem.projects.filter(id=project_id).exists():
                    continue
            if mem.user_id not in seen:
                seen.add(mem.user_id)
                recipients.append(mem.user)
        return recipients

    @staticmethod
    def publish(
        *,
        event_type: str,
        title: str,
        message: str,
        company: Company | None = None,
        actor: User | None = None,
        category: str = Notification.Category.GENERAL,
        module: str = "SYSTEM",
        priority: str = Notification.Priority.NORMAL,
        popup_kind: str = "INFO",
        description: str = "",
        source_object_type: str = "",
        source_object_id: str = "",
        source_reference: str = "",
        route_key: str = "",
        action_definition: dict | None = None,
        metadata: dict | None = None,
        dedup_key: str = "",
        recipient_ids: list | None = None,
        required_permission: str | None = None,
        exclude_actor: bool = False,
        project_id=None,
        is_mandatory_critical: bool = False,
        defer_until_commit: bool = True,
    ) -> NotificationEvent | None:
        clean_meta = sanitize_payload(metadata or {})
        clean_action = sanitize_payload(action_definition or {})

        def _dispatch_sync():
            ev = NotificationEvent.objects.create(
                event_type=event_type,
                company=company,
                actor=actor,
                source_object_type=source_object_type[:64],
                source_object_id=str(source_object_id or "")[:64],
                source_reference=source_reference[:128],
                dedup_key=dedup_key[:191],
                payload={
                    "title": title[:180],
                    "message": message,
                    "priority": priority,
                    "category": category,
                    "module": module,
                    "popup_kind": popup_kind,
                    "route_key": route_key,
                    "action_definition": clean_action,
                    "metadata": clean_meta,
                    "recipient_ids": [str(x) for x in recipient_ids] if recipient_ids is not None else None,
                    "required_permission": required_permission,
                    "exclude_actor": exclude_actor,
                    "project_id": str(project_id) if project_id else None,
                    "is_mandatory_critical": is_mandatory_critical,
                },
                processing_status=NotificationEvent.ProcessingStatus.PENDING,
            )
            DomainEventService.process_event(ev)
            return ev

        if defer_until_commit:
            transaction.on_commit(_dispatch_sync)
            return None
        return _dispatch_sync()

    @staticmethod
    def process_event(ev: NotificationEvent) -> int:
        pl = ev.payload or {}
        try:
            company = ev.company
            recipients = DomainEventService.resolve_recipients(
                company=company,
                explicit_recipient_ids=pl.get("recipient_ids"),
                required_permission=pl.get("required_permission"),
                exclude_user_id=ev.actor_id if pl.get("exclude_actor") else None,
                project_id=pl.get("project_id"),
            )
            mandatory = bool(pl.get("is_mandatory_critical")) or pl.get("priority") == Notification.Priority.CRITICAL
            if company:
                cfg = NotificationConfigService.get_config(company)
                if pl.get("category") == Notification.Category.SECURITY and cfg.mandatory_security_popup:
                    mandatory = True
                ttl_days = cfg.retention_days or 180
                expires_at = timezone.now() + timedelta(days=ttl_days)
            else:
                expires_at = timezone.now() + timedelta(days=180)

            created_count = 0
            for user in recipients:
                suppressed = NotificationConfigService.is_suppressed_by_user(
                    user=user,
                    category=pl.get("category", Notification.Category.GENERAL),
                    module=pl.get("module", "SYSTEM"),
                    priority=pl.get("priority", Notification.Priority.NORMAL),
                    is_mandatory_critical=mandatory,
                )
                d_key = ev.dedup_key.strip() if ev.dedup_key else None
                try:
                    with transaction.atomic():
                        notif = Notification.objects.create(
                            company=company,
                            recipient=user,
                            sender=ev.actor,
                            event=ev,
                            event_type=ev.event_type,
                            title=pl.get("title", ev.event_type)[:180],
                            message=pl.get("message", ""),
                            description=pl.get("description", ""),
                            priority=pl.get("priority", Notification.Priority.NORMAL),
                            category=pl.get("category", Notification.Category.GENERAL),
                            module=pl.get("module", "SYSTEM")[:48],
                            popup_kind=pl.get("popup_kind", "INFO"),
                            source_object_type=ev.source_object_type,
                            source_object_id=ev.source_object_id,
                            source_reference=ev.source_reference,
                            route_key=pl.get("route_key", ""),
                            action_definition=pl.get("action_definition", {}),
                            metadata=pl.get("metadata", {}),
                            dedup_key=d_key,
                            is_mandatory_critical=mandatory,
                            expires_at=expires_at,
                        )
                        state = NotificationRecipientState.objects.create(
                            notification=notif,
                            recipient=user,
                        )
                except IntegrityError:
                    # Deduplication constraint matched -> ignore duplicate emission cleanly
                    continue

                if suppressed:
                    NotificationDelivery.objects.create(
                        event=ev,
                        notification=notif,
                        recipient=user,
                        delivery_channel="IN_APP",
                        delivery_status="SUPPRESSED_PREF",
                        delivered_at=timezone.now(),
                    )
                else:
                    NotificationDelivery.objects.create(
                        event=ev,
                        notification=notif,
                        recipient=user,
                        delivery_channel="WEBSOCKET",
                        delivery_status="DELIVERED",
                        delivered_at=timezone.now(),
                    )
                    general_pref, _ = NotificationConfigService.get_user_preferences(user)
                    push_payload = {
                        "type": "notification_created",
                        "notification": _serialize_notification_push(notif, state),
                        "should_popup": bool(general_pref.popup_enabled and general_pref.center_screen_enabled) or mandatory,
                    }
                    _broadcast_ws_notification(user.id, push_payload)
                created_count += 1

            ev.processing_status = NotificationEvent.ProcessingStatus.PROCESSED
            ev.processed_at = timezone.now()
            ev.save(update_fields=["processing_status", "processed_at"])
            return created_count
        except Exception as exc:
            ev.processing_status = NotificationEvent.ProcessingStatus.FAILED
            ev.error_detail = str(exc)[:250]
            ev.save(update_fields=["processing_status", "error_detail"])
            logger.exception("NotificationEvent processing failed for %s", ev.event_id)
            return 0

