import hashlib
import io
import re
import uuid
from datetime import timedelta
from pathlib import Path
from urllib.parse import parse_qs, urlparse

from django.conf import settings
from django.db import IntegrityError, transaction
from django.db.models import F, Q
from django.utils import timezone
from PIL import Image, UnidentifiedImageError

from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import CompanyMembership, User
from apps.accounts_rbac.policies import scope_queryset
from apps.chat.models import (
    ChatConversation,
    ChatMessage,
    ChatNotification,
    ChatUserPreference,
    ConversationMember,
    MessageAttachment,
    MessageBookmark,
    MessageDeliveryReceipt,
    MessageEditHistory,
    MessageMention,
    MessagePin,
    MessageReaction,
    MessageReadReceipt,
    PageReferencePermissionCheck,
    SharedPageReference,
)
from apps.tenancy.models import Company
from .conversations import ChatAuditService, ChatPermissionService

DISALLOWED_EXTENSIONS = {"exe", "sh", "bat", "cmd", "js", "vbs", "ps1", "php", "html", "htm", "svg", "msi", "dll", "com"}
SENSITIVE_QUERY_KEYS = {"token", "auth", "secret", "password", "staff_code", "key", "csrf", "session", "code"}

# Authoritative server-side route permission + object-model validation matrix
ROUTE_PERMISSION_MAP: dict[str, tuple[str, str | None]] = {
    "dashboard": (Permissions.DASHBOARD_VIEW, None),
    "vouchers": (Permissions.VOUCHER_READ, "Voucher"),
    "voucher_register": (Permissions.VOUCHER_READ, "Voucher"),
    "coa": (Permissions.COA_READ, None),
    "reports": (Permissions.REPORT_READ, None),
    "projects": (Permissions.PROJECT_READ, "Project"),
    "debtors": (Permissions.DEBTORS_VIEW, None),
    "creditors": (Permissions.CREDITORS_VIEW, None),
    "banking": (Permissions.BANKING_READ, None),
    "loans": (Permissions.LOAN_READ, None),
    "procurement": (Permissions.PROCUREMENT_READ, None),
    "inventory": (Permissions.INVENTORY_READ, None),
    "hr": (Permissions.HR_READ, "EmployeeDetail"),
    "budgeting": (Permissions.BUDGET_READ, None),
    "documents": (Permissions.DOCUMENT_VIEW, None),
    "sysadmin": (Permissions.SYSTEM_VIEW, None),
    "sync": (Permissions.SYNC_PULL, None),
    "profile": ("AUTHENTICATED_SELF", None),
}


def _strip_sensitive_params(raw_params: dict | None, raw_url: str = "") -> dict:
    clean = {}
    if isinstance(raw_params, dict):
        for k, v in raw_params.items():
            if not any(s in str(k).lower() for s in SENSITIVE_QUERY_KEYS):
                clean[str(k)] = v
    if raw_url and "?" in raw_url:
        parsed = urlparse(raw_url)
        query_str = parsed.query or (parsed.fragment.split("?", 1)[1] if "?" in parsed.fragment else "")
        for k, vals in parse_qs(query_str).items():
            if not any(s in k.lower() for s in SENSITIVE_QUERY_KEYS):
                clean[k] = vals[0] if len(vals) == 1 else vals
    return clean


class SharedPageLinkService:
    @staticmethod
    def _validate_target_route(route_key: str) -> tuple[str, str | None]:
        clean = (route_key or "").strip().lstrip("#/")
        base = clean.split(":")[0].split("?")[0]
        if base not in ROUTE_PERMISSION_MAP:
            raise ValueError(f"Unsupported or disallowed internal Maya OS route: {route_key}")
        return ROUTE_PERMISSION_MAP[base]

    @staticmethod
    def create_page_reference(*, company: Company, user: User, payload: dict, conversation: ChatConversation | None = None) -> SharedPageReference:
        cfg = ChatPermissionService.assert_chat_enabled(company)
        if not cfg.page_link_sharing_enabled:
            raise PermissionError("Page link sharing is disabled by organization policy.")

        route_key = (payload.get("route_key") or "").strip()
        SharedPageLinkService._validate_target_route(route_key)
        sanitized = _strip_sensitive_params(payload.get("params"), payload.get("url", ""))

        proj = None
        if payload.get("project_id"):
            from apps.projects.models import Project

            proj = Project.objects.filter(company=company, id=payload["project_id"]).first()

        return SharedPageReference.objects.create(
            company=company,
            conversation=conversation,
            shared_by=user,
            route_key=route_key[:120],
            page_title=(payload.get("page_title") or route_key)[:160],
            module_name=(payload.get("module_name") or route_key.split(":")[0].upper())[:64],
            object_type=(payload.get("object_type") or "")[:64],
            object_id=str(payload.get("object_id") or "")[:64],
            object_ref_code=(payload.get("object_ref_code") or "")[:64],
            project=proj,
            sanitized_params=sanitized,
        )

    @staticmethod
    def check_recipient_access(*, user: User, company: Company, ref: SharedPageReference) -> dict:
        if str(ref.company_id) != str(company.id):
            PageReferencePermissionCheck.objects.create(reference=ref, user=user, allowed=False, reason="Company mismatch")
            return {"allowed": False, "reason": "Link belongs to a different company context."}

        mem = CompanyMembership.objects.select_related("role").prefetch_related("roles", "branches", "projects", "sites").filter(
            user=user, company=company, is_active=True
        ).first()
        if not mem and not user.is_superuser:
            PageReferencePermissionCheck.objects.create(reference=ref, user=user, allowed=False, reason="No active membership")
            return {"allowed": False, "reason": "No active membership in target company."}

        required_perm, expected_model = SharedPageLinkService._validate_target_route(ref.route_key)
        if required_perm != "AUTHENTICATED_SELF" and not user.is_superuser:
            perms = set(mem.effective_permissions())
            if required_perm not in perms:
                PageReferencePermissionCheck.objects.create(
                    reference=ref, user=user, allowed=False, reason=f"Missing permission {required_perm}"
                )
                return {"allowed": False, "reason": f"Access denied: missing permission ({required_perm})."}

        # Object & Project / Branch scope check
        if ref.project_id and not user.is_superuser and mem:
            if mem.data_scope in ("PROJECT", "SITE") and not mem.projects.filter(id=ref.project_id).exists():
                PageReferencePermissionCheck.objects.create(reference=ref, user=user, allowed=False, reason="Out of project scope")
                return {"allowed": False, "reason": "Access denied: target project is outside your assigned scope."}

        if ref.object_id and expected_model == "Voucher" and not user.is_superuser and mem:
            from apps.accounting.models import Voucher

            v_qs = scope_queryset(
                Voucher.objects.filter(company=company, id=ref.object_id),
                mem,
                user,
                branch_field="branch_id",
                project_field="project_id",
                site_field="site_id",
            )
            if not v_qs.exists():
                PageReferencePermissionCheck.objects.create(reference=ref, user=user, allowed=False, reason="Voucher scope denied")
                return {"allowed": False, "reason": "Access denied: you lack permission for this voucher."}

        if ref.object_id and expected_model == "Project" and not user.is_superuser and mem:
            from apps.projects.models import Project

            if mem.data_scope in ("PROJECT", "SITE") and not mem.projects.filter(id=ref.object_id).exists():
                PageReferencePermissionCheck.objects.create(reference=ref, user=user, allowed=False, reason="Project scope denied")
                return {"allowed": False, "reason": "Access denied: project is restricted."}

        PageReferencePermissionCheck.objects.create(reference=ref, user=user, allowed=True, reason="Authorized")
        return {
            "allowed": True,
            "route_key": ref.route_key,
            "page_title": ref.page_title,
            "object_type": ref.object_type,
            "object_id": ref.object_id,
            "object_ref_code": ref.object_ref_code,
            "sanitized_params": ref.sanitized_params,
        }


class MessageAttachmentService:
    @staticmethod
    @transaction.atomic
    def upload(*, company: Company, conv: ChatConversation, uploader: User, file_obj) -> MessageAttachment:
        cfg = ChatPermissionService.assert_chat_enabled(company)
        if not cfg.attachments_enabled or not conv.allow_attachments:
            raise PermissionError("File attachments are disabled in this conversation.")

        name = Path(file_obj.name).name
        if name.count(".") > 1 and any(p.lower() in DISALLOWED_EXTENSIONS for p in name.split(".")[1:]):
            raise ValueError("Potentially unsafe multi-extension filename rejected.")
        ext = Path(name).suffix.lstrip(".").lower()
        allowed = [e.lower() for e in (cfg.allowed_extensions or [])]
        if not ext or ext in DISALLOWED_EXTENSIONS or (allowed and ext not in allowed):
            raise ValueError(f"File type .{ext or 'unknown'} is blocked by security policy.")

        raw = file_obj.read()
        max_bytes = int(cfg.max_file_size_mb or 15) * 1024 * 1024
        if len(raw) == 0 or len(raw) > max_bytes:
            raise ValueError(f"Attachment size must be between 1 byte and {cfg.max_file_size_mb} MB.")

        # Heuristic header + image verification
        if ext in ("jpg", "jpeg", "png", "webp"):
            try:
                with Image.open(io.BytesIO(raw)) as im:
                    im.verify()
            except (UnidentifiedImageError, Exception) as exc:
                raise ValueError("Invalid or corrupt image payload rejected.") from exc
        if raw[:2] == b"MZ" or b"<script" in raw[:4096].lower():
            raise ValueError("Executable or scripted payload rejected by attachment scanner.")

        sha = hashlib.sha256(raw).hexdigest()
        dest_dir = Path(settings.PRIVATE_DOCUMENT_ROOT) / "chat_attachments" / str(company.id)
        dest_dir.mkdir(parents=True, exist_ok=True)
        att_id = uuid.uuid4()
        dest_path = dest_dir / f"{att_id}.{ext}"
        dest_path.write_bytes(raw)

        att = MessageAttachment.objects.create(
            id=att_id,
            company=company,
            conversation=conv,
            uploader=uploader,
            original_filename=name[:255],
            mime_type=(getattr(file_obj, "content_type", "") or "application/octet-stream")[:120],
            file_extension=ext,
            file_path=str(dest_path),
            size_bytes=len(raw),
            sha256_checksum=sha,
            scan_status=MessageAttachment.ScanStatus.CLEAN,
        )
        ChatAuditService.record(
            company=company,
            actor=uploader,
            action="CHAT_ATTACHMENT_UPLOADED",
            conversation=conv,
            metadata={"attachment_id": str(att.id), "filename": att.original_filename, "size_bytes": att.size_bytes},
        )
        return att


class MessageService:
    @staticmethod
    @transaction.atomic
    def send_message(
        *,
        company: Company,
        conv: ChatConversation,
        sender: User,
        membership: CompanyMembership | None,
        sender_mem: ConversationMember,
        body: str,
        client_operation_id: str | None = None,
        parent_message_id: str | None = None,
        forwarded_from_id: str | None = None,
        attachment_ids: list[str] | None = None,
        page_reference_payload: dict | None = None,
        scheduled_for=None,
    ) -> tuple[ChatMessage, bool]:
        ChatPermissionService.assert_chat_enabled(company)
        ChatPermissionService.assert_can_post(conv, sender_mem, membership, sender)

        op_id = (client_operation_id or str(uuid.uuid4()))[:64]
        existing = ChatMessage.objects.filter(conversation=conv, sender=sender, client_operation_id=op_id).first()
        if existing:
            return existing, False

        body_clean = (body or "").strip()
        if not body_clean and not attachment_ids and not page_reference_payload:
            raise ValueError("Cannot send an empty message.")

        parent = ChatMessage.objects.filter(conversation=conv, id=parent_message_id).first() if parent_message_id else None
        forwarded = ChatMessage.objects.filter(id=forwarded_from_id).first() if forwarded_from_id else None

        msg_type = (
            ChatMessage.MessageType.PAGE_LINK
            if page_reference_payload
            else (ChatMessage.MessageType.ATTACHMENT if attachment_ids else ChatMessage.MessageType.TEXT)
        )
        try:
            msg = ChatMessage.objects.create(
                company=company,
                conversation=conv,
                sender=sender,
                client_operation_id=op_id,
                parent_message=parent,
                forwarded_from=forwarded,
                message_type=msg_type,
                body=body_clean,
                status=ChatMessage.Status.DRAFT if scheduled_for else ChatMessage.Status.SENT,
                scheduled_for=scheduled_for,
            )
        except IntegrityError:
            return ChatMessage.objects.get(conversation=conv, sender=sender, client_operation_id=op_id), False

        if attachment_ids:
            MessageAttachment.objects.filter(
                id__in=attachment_ids, conversation=conv, uploader=sender, message__isnull=True
            ).update(message=msg)

        if page_reference_payload:
            ref = SharedPageLinkService.create_page_reference(
                company=company, user=sender, payload=page_reference_payload, conversation=conv
            )
            ref.message = msg
            ref.save(update_fields=["message"])

        # Parse @mentions
        mention_tokens = set(re.findall(r"@([a-zA-Z0-9_.-]+)", body_clean))
        mentioned_users = set()
        if "all" in {t.lower() for t in mention_tokens} and conv.conversation_type != ChatConversation.Type.DIRECT:
            MessageMention.objects.create(message=msg, mention_type=MessageMention.MentionType.ALL)
            mentioned_users.update(
                conv.members.filter(left_at__isnull=True).exclude(user=sender).values_list("user_id", flat=True)
            )
        for uname in mention_tokens:
            if uname.lower() == "all":
                continue
            target = conv.members.select_related("user").filter(left_at__isnull=True, user__username__iexact=uname).first()
            if target:
                MessageMention.objects.create(
                    message=msg, mentioned_user=target.user, mention_type=MessageMention.MentionType.USER
                )
                mentioned_users.add(target.user_id)

        if not scheduled_for:
            now = timezone.now()
            conv.last_message_at = now
            conv.save(update_fields=["last_message_at"])
            # Update unread counts & clear sender draft
            ConversationMember.objects.filter(conversation=conv, user=sender).update(
                draft_text="", draft_page_refs=[], last_read_message_id=msg.id, last_read_at=now
            )
            ConversationMember.objects.filter(conversation=conv, left_at__isnull=True).exclude(user=sender).update(
                unread_count=F("unread_count") + 1
            )

            # Queue respecting per-user notification & privacy preferences
            from .presence_search_retention import ChatNotificationService

            ChatNotificationService.dispatch_for_message(
                company=company, conv=conv, message=msg, sender=sender, mentioned_user_ids=mentioned_users
            )

        return msg, True

    @staticmethod
    @transaction.atomic
    def edit_message(*, company: Company, conv: ChatConversation, msg: ChatMessage, actor: User, new_body: str) -> ChatMessage:
        cfg = ChatPermissionService.get_config(company)
        if msg.sender_id != actor.id:
            raise PermissionError("You can only edit your own messages.")
        if msg.is_deleted_for_everyone:
            raise ValueError("Deleted messages cannot be edited.")
        if (timezone.now() - msg.created_at) > timedelta(minutes=cfg.edit_window_minutes):
            raise PermissionError(f"Edit window expired ({cfg.edit_window_minutes} minutes).")

        MessageEditHistory.objects.create(message=msg, previous_body=msg.body, edited_by=actor)
        msg.body = (new_body or "").strip()
        msg.is_edited = True
        msg.edited_at = timezone.now()
        msg.save(update_fields=["body", "is_edited", "edited_at"])
        return msg

    @staticmethod
    @transaction.atomic
    def delete_message(*, company: Company, msg: ChatMessage, actor: User, membership: CompanyMembership | None, for_everyone: bool = False) -> ChatMessage:
        cfg = ChatPermissionService.get_config(company)
        if not for_everyone:
            deleted_for = list(msg.deleted_for_user_ids or [])
            if str(actor.id) not in deleted_for:
                deleted_for.append(str(actor.id))
                msg.deleted_for_user_ids = deleted_for
                msg.save(update_fields=["deleted_for_user_ids"])
            return msg

        is_mod = actor.is_superuser or (membership and Permissions.CHAT_MODERATE in set(membership.effective_permissions()))
        if msg.sender_id != actor.id and not is_mod:
            raise PermissionError("Only sender or authorized moderator can delete for everyone.")
        if not is_mod and (timezone.now() - msg.created_at) > timedelta(minutes=cfg.delete_for_everyone_minutes):
            raise PermissionError("Delete-for-everyone time limit exceeded.")

        msg.is_deleted_for_everyone = True
        msg.status = ChatMessage.Status.DELETED
        msg.body = "[Message removed under policy]"
        msg.save(update_fields=["is_deleted_for_everyone", "status", "body"])
        ChatAuditService.record(company=company, actor=actor, action="MESSAGE_DELETED_FOR_ALL", conversation=msg.conversation, metadata={"message_id": str(msg.id)})
        return msg


class MessageDeliveryService:
    @staticmethod
    def ack_delivery(*, message: ChatMessage, recipient: User, device_id: str = "") -> MessageDeliveryReceipt:
        if message.sender_id == recipient.id:
            raise ValueError("Sender cannot acknowledge own delivery.")
        rec, _ = MessageDeliveryReceipt.objects.get_or_create(
            message=message, user=recipient, defaults={"device_id": device_id}
        )
        if message.status == ChatMessage.Status.SENT:
            message.status = ChatMessage.Status.DELIVERED
            message.save(update_fields=["status"])
        return rec


class MessageReadReceiptService:
    @staticmethod
    @transaction.atomic
    def mark_conversation_read(*, conv: ChatConversation, user: User, up_to_message: ChatMessage | None = None) -> int:
        mem = ConversationMember.objects.filter(conversation=conv, user=user, left_at__isnull=True).first()
        if not mem:
            raise PermissionError("Not an active member.")
        target_msg = up_to_message or conv.messages.order_by("-created_at").first()
        now = timezone.now()
        mem.unread_count = 0
        mem.marked_unread = False
        if target_msg:
            mem.last_read_message_id = target_msg.id
        mem.last_read_at = now
        mem.save(update_fields=["unread_count", "marked_unread", "last_read_message_id", "last_read_at"])

        pref = ChatUserPreference.objects.filter(user=user).first()
        allow_receipt = pref.send_read_receipts if pref else True
        if allow_receipt and target_msg:
            unread_msgs = conv.messages.filter(created_at__lte=target_msg.created_at).exclude(sender=user).order_by("-created_at")[:50]
            for m in unread_msgs:
                MessageReadReceipt.objects.get_or_create(message=m, user=user)
                if m.status in (ChatMessage.Status.SENT, ChatMessage.Status.DELIVERED):
                    m.status = ChatMessage.Status.READ
                    m.save(update_fields=["status"])

        ChatNotification.objects.filter(user=user, conversation=conv, is_read=False).update(is_read=True, read_at=now)
        return 0

