"""
@mention parsing and notification for comments.

Parses @username patterns from comment text and sends immediate
email notifications to mentioned users.
"""

import re
import logging

from .mail import send_pyramid_email
from .mail_messages import MENTION_TEXT, MENTION_HTML

from ..models.user import get_user_by_name

log = logging.getLogger(__name__)

# Matches @username where username is 3-64 chars of alphanumeric + dashes,
# must start and end with alphanumeric. Preceded by start-of-string or whitespace.
MENTION_PATTERN = re.compile(
    r"(?:^|(?<=\s))@([a-zA-Z0-9][a-zA-Z0-9\-]{1,62}[a-zA-Z0-9])"
)


def extract_mentions(text):
    """Extract unique @mentioned usernames from text (without the @)."""
    if not text:
        return []
    matches = MENTION_PATTERN.findall(text)
    # Deduplicate while preserving order
    seen = set()
    unique = []
    for m in matches:
        lower = m.lower()
        if lower not in seen:
            seen.add(lower)
            unique.append(m)
    return unique


def notify_mentioned_users(request, comment, author_user):
    """
    Parse @mentions from a comment and send email notifications.

    Skips self-mentions and unverified users.
    """
    usernames = extract_mentions(comment.data)
    if not usernames:
        return

    product = comment.product
    product_url = product.absolute_url(request)
    comment_url = f"{product_url}#comment-{comment.id}"
    commenter_name = author_user.name if author_user else "Someone"

    for username in usernames:
        mentioned_user = get_user_by_name(request.dbsession, username)

        if not mentioned_user:
            continue

        # Skip self-mentions
        if author_user and mentioned_user.id == author_user.id:
            continue

        # Skip unverified users (no valid email to send to)
        if not mentioned_user.verified:
            continue

        subject = f"{commenter_name} mentioned you in a comment"
        message_text = MENTION_TEXT.format(
            commenter_name,
            product.title,
            comment.data,
            comment_url,
        )
        message_html = MENTION_HTML.format(
            subject,
            commenter_name,
            product.title,
            comment.data_html or comment.data,
            comment_url,
        )

        try:
            send_pyramid_email(
                request, mentioned_user.email, subject, message_text, message_html
            )
            log.info(f"Sent mention notification to {mentioned_user.email}")
        except Exception as e:
            log.error(
                f"Failed to send mention notification to {mentioned_user.email}: {e}"
            )
