import logging

from django.utils.translation import gettext_lazy as _

from ..djangoblog.utils import get_current_site
from ..djangoblog.utils import send_email

# 获取当前模块的 logger 实例，用于记录日志
logger = logging.getLogger(__name__)


#ssj
def send_comment_email(comment):
    # 获取当前站点的域名（如 example.com）
    site = get_current_site().domain

    # 邮件主题（支持国际化）
    subject = _('Thanks for your comment')

    # 构造文章的完整绝对 URL（使用 HTTPS）
    article_url = f"https://{site}{comment.article.get_absolute_url()}"

    # 构造发送给评论作者的 HTML 邮件内容
    # 内容包含感谢语、文章链接和标题，并支持变量替换
    html_content = _("""<p>Thank you very much for your comments on this site</p>
                    You can visit <a href="%(article_url)s" rel="bookmark">%(article_title)s</a>
                    to review your comments,
                    Thank you again!
                    <br />
                    If the link above cannot be opened, please copy this link to your browser.
                    %(article_url)s""") % {
        'article_url': article_url,
        'article_title': comment.article.title
    }

    # 收件人邮箱：当前发表评论的用户
    tomail = comment.author.email

    # 调用发送邮件的通用函数，发送感谢邮件
    send_email([tomail], subject, html_content)

#ssj
    try:
        # 如果当前评论是回复（即存在父评论）
        if comment.parent_comment:
            # 构造发送给被回复用户的 HTML 邮件内容
            # 通知其评论收到了新的回复
            html_content = _("""Your comment on <a href="%(article_url)s" rel="bookmark">%(article_title)s</a><br/> has 
                   received a reply. <br/> %(comment_body)s
                    <br/>   
                    go check it out!
                     <br/>
                     If the link above cannot be opened, please copy this link to your browser.
                     %(article_url)s
                    """) % {
                'article_url': article_url,
                'article_title': comment.article.title,
                'comment_body': comment.parent_comment.body  # 被回复的原始评论内容
            }

            # 收件人邮箱：被回复的评论的作者
            tomail = comment.parent_comment.author.email

            # 发送回复通知邮件
            send_email([tomail], subject, html_content)

#ssj
    except Exception as e:
        # 如果在发送通知邮件过程中发生异常（如用户无邮箱等），记录错误日志
        logger.error(e)