from datetime import timedelta
from pathlib import Path

from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from apps.accounts_rbac.models import User
from apps.chat.models import (
    ChatConversation,
    ChatMessage,
    ChatNotification,
    ChatPresence,
    ChatRetentionPolicy,
    ChatUserPreference,
    ConversationMember,
    MessageAttachment,
)
from apps.tenancy.models import Company
from .conversations import ChatAuditService


class ChatPresenceService:
    @staticmethod
    def update_presence(*, user: User, status: str | None = None, manual_status: str | None = None, status_message: str | None = None, socket_delta: int = 0) -> ChatPresence:
        pres, _ = ChatPresence.objects.get_or_create(user=user)
        if socket_delta:
            pres.active_socket_count = max(0, pres.active_socket_count + socket_delta)
        if manual_status is not None:
            pres.manual_status = manual_status
        if status_message is not None:
            pres.status_message = status_message[:140]
        if status:
            pres.status = status
        elif pres.manual_status in (ChatPresence.Status.BUSY, ChatPresence.Status.AWAY, ChatPresence.Status.DND):
            pres.status = pres.manual_status
        else:
            pres.status = ChatPresence.Status.ONLINE if pres.active_socket_count > 0 or status is None else ChatPresence.Status.OFFLINE
        pres.last_active_at = timezone.now()
        pres.save()
        return pres


def _in_quiet_hours(pref: ChatUserPreference, now_time) -> bool:
    if pref.dnd_enabled:
        return True
    s, e = pref.quiet_hours_start, pref.quiet_hours_end
    if not s or not e:
        return False
    if s <= e:
        return s <= now_time <= e
    # Overnight window e.g. 22:00 .. 07:00
    return now_time >= s or now_time <= e


class ChatNotificationService:
    @staticmethod
    def dispatch_for_message(*, company: Company, conv: ChatConversation, message: ChatMessage, sender: User, mentioned_user_ids: set | None = None) -> int:
        mentioned_user_ids = mentioned_user_ids or set()
        now_local = timezone.localtime().time()
        members = ConversationMember.objects.select_related("user__chat_preferences").filter(
            conversation=conv, left_at__isnull=True
        ).exclude(user=sender)
        created = 0
        for m in members:
            if m.is_muted and (not m.mute_until or m.mute_until > timezone.now()):
                continue
            pref = getattr(m.user, "chat_preferences", None)
            if pref:
                if pref.notify_scope == "MUTED":
                    continue
                if pref.notify_scope == "DM_ONLY" and conv.conversation_type != ChatConversation.Type.DIRECT:
                    continue
                if pref.notify_scope == "MENTIONS_ONLY" and m.user_id not in mentioned_user_ids:
                    continue
                if _in_quiet_hours(pref, now_local) and m.user_id not in mentioned_user_ids:
                    continue
                preview = message.body[:140] if pref.show_notification_preview else "New message received"
            else:
                preview = message.body[:140]

            ntype = (
                "MENTION"
                if m.user_id in mentioned_user_ids
                else ("DIRECT_MESSAGE" if conv.conversation_type == ChatConversation.Type.DIRECT else "MESSAGE")
            )
            ChatNotification.objects.create(
                user=m.user,
                company=company,
                conversation=conv,
                message=message,
                notification_type=ntype,
                title=f"{sender.full_name or sender.username} in {conv.title[:60]}",
                preview_text=preview or "Sent an attachment / page link",
            )
            from apps.notifications.services import DomainEventService

            emp_dept = ""
            if hasattr(sender, "staff_employee") and sender.staff_employee and sender.staff_employee.employee_profile.department:
                emp_dept = sender.staff_employee.employee_profile.department.name
            first_ref = message.page_references.first()
            DomainEventService.publish(
                event_type="chat.mention_received" if m.user_id in mentioned_user_ids else "chat.message_received",
                title=f"{'Mention from ' if m.user_id in mentioned_user_ids else ''}{sender.full_name or sender.username}",
                message=preview or "Sent an attachment / page link",
                company=company,
                actor=sender,
                category="MESSAGE",
                module="CHAT",
                priority="HIGH" if m.user_id in mentioned_user_ids else "NORMAL",
                popup_kind="CHAT",
                source_object_type="ChatConversation",
                source_object_id=str(conv.id),
                source_reference=conv.title[:80] or conv.conversation_type,
                route_key="chat:all",
                recipient_ids=[m.user_id],
                dedup_key=f"chat.msg:{message.id}:{m.user_id}",
                action_definition={
                    "actions": [
                        {"key": "OPEN_CHAT", "label": "Open Chat", "variant": "primary"},
                    ]
                },
                metadata={
                    "conversation_id": str(conv.id),
                    "conversation_type": conv.conversation_type,
                    "conversation_title": conv.title[:80],
                    "message_id": str(message.id),
                    "department": emp_dept,
                    "is_mention": m.user_id in mentioned_user_ids,
                    "has_attachment": message.attachments.exists(),
                    "has_reply": bool(message.parent_message_id),
                    "page_reference_id": str(first_ref.id) if first_ref else None,
                    "page_title": first_ref.page_title if first_ref else "",
                    "page_route_key": first_ref.route_key if first_ref else "",
                },
            )
            created += 1
        return created


class ChatSearchService:
    @staticmethod
    def search_messages(*, user: User, company: Company, params: dict) -> list[dict]:
        # Strictly restrict search results to conversations where user is an active member
        member_conv_ids = ConversationMember.objects.filter(
            user=user, conversation__company=company, left_at__isnull=True
        ).values_list("conversation_id", flat=True)

        qs = (
            ChatMessage.objects.select_related("sender", "conversation")
            .prefetch_related("attachments", "page_references")
            .filter(conversation_id__in=member_conv_ids, is_deleted_for_everyone=False)
            .exclude(status=ChatMessage.Status.DRAFT)
        )
        q = (params.get("q") or "").strip()
        if q:
            qs = qs.filter(
                Q(body__icontains=q)
                | Q(page_references__page_title__icontains=q)
                | Q(page_references__object_ref_code__icontains=q)
                | Q(attachments__original_filename__icontains=q)
            ).distinct()
        if params.get("conversation_id"):
            qs = qs.filter(conversation_id=params["conversation_id"])
        if params.get("sender_id"):
            qs = qs.filter(sender_id=params["sender_id"])
        if params.get("message_type"):
            qs = qs.filter(message_type=params["message_type"])
        if params.get("date_from"):
            qs = qs.filter(created_at__date__gte=params["date_from"])
        if params.get("date_to"):
            qs = qs.filter(created_at__date__lte=params["date_to"])

        results = []
        for msg in qs.order_by("-created_at")[:80]:
            if str(user.id) in (msg.deleted_for_user_ids or []):
                continue
            results.append(
                {
                    "id": str(msg.id),
                    "conversation_id": str(msg.conversation_id),
                    "conversation_title": msg.conversation.title,
                    "sender_name": msg.sender.full_name or msg.sender.username,
                    "message_type": msg.message_type,
                    "body": msg.body[:240],
                    "created_at": msg.created_at.isoformat(),
                }
            )
        return results


class ChatRetentionService:
    @staticmethod
    def get_policy(company: Company) -> ChatRetentionPolicy:
        pol, _ = ChatRetentionPolicy.objects.get_or_create(company=company)
        return pol

    @staticmethod
    @transaction.atomic
    def enforce_retention(company: Company, *, actor: User | None = None) -> dict:
        pol = ChatRetentionService.get_policy(company)
        if pol.legal_hold_active or not pol.retention_days:
            return {"skipped": True, "reason": "Legal hold active or permanent retention configured.", "purged_messages": 0}

        cutoff = timezone.now() - timedelta(days=pol.retention_days)
        expired = ChatMessage.objects.filter(company=company, created_at__lt=cutoff)
        purged = 0
        for m in expired:
            m.is_deleted_for_everyone = True
            m.status = ChatMessage.Status.DELETED
            m.body = "[Expired under retention policy]"
            m.save(update_fields=["is_deleted_for_everyone", "status", "body"])
            purged += 1

        att_purged = 0
        if pol.attachment_retention_days:
            att_cutoff = timezone.now() - timedelta(days=pol.attachment_retention_days)
            for att in MessageAttachment.objects.filter(company=company, created_at__lt=att_cutoff, retention_locked=False):
                Path(att.file_path).unlink(missing_ok=True)
                att.delete()
                att_purged += 1

        ChatAuditService.record(
            company=company,
            actor=actor,
            action="CHAT_RETENTION_ENFORCED",
            metadata={"purged_messages": purged, "purged_attachments": att_purged},
        )
        return {"skipped": False, "purged_messages": purged, "purged_attachments": att_purged}

