from django.db import models
from django.conf import settings # 用于引用 AUTH_USER_MODEL
from django.utils.translation import gettext_lazy as _
from django.utils import timezone

class Group(models.Model):
    name = models.CharField(_('小组名称'), max_length=100, unique=True)
    description = models.TextField(_('小组描述'), blank=True)
    cover_image = models.ImageField(_('小组封面'), upload_to='group_covers/', null=True, blank=True)
    creator = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name=_('创建者'),
        on_delete=models.SET_NULL,
        null=True,
        related_name='created_groups'
    )
    members = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        through='Membership',
        through_fields=('group', 'user'),
        verbose_name=_('小组成员'),
        blank=True,
        related_name='joined_groups'
    )
    tags = models.ManyToManyField(
        'accounts.InterestTag',
        verbose_name=_('相关兴趣标签'),
        blank=True,
        related_name='groups_with_tag'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('创建时间'))
    updated_at = models.DateTimeField(auto_now=True, verbose_name=_('更新时间'))

    class Meta:
        verbose_name = _('小组')
        verbose_name_plural = _('小组们')
        ordering = ['-created_at']

    def __str__(self):
        return self.name

class Membership(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('用户'))
    group = models.ForeignKey(Group, on_delete=models.CASCADE, verbose_name=_('小组'))
    date_joined = models.DateTimeField(auto_now_add=True, verbose_name=_('加入日期'))
    
    class Meta:
        verbose_name = _('小组成员关系')
        verbose_name_plural = _('小组成员关系们')
        unique_together = ('user', 'group')
        ordering = ['-date_joined']

    def __str__(self):
        user_identifier = self.user.email
        if hasattr(self.user, 'display_name') and self.user.display_name:
            user_identifier = self.user.display_name
        elif hasattr(self.user, 'nickname') and self.user.nickname:
            user_identifier = self.user.nickname
        return f"{user_identifier} 加入了 {self.group.name}"

class Post(models.Model):
    group = models.ForeignKey(
        Group, 
        on_delete=models.CASCADE,
        related_name='posts',
        verbose_name=_('所属小组')
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='%(app_label)s_posts',
        verbose_name=_('作者')
    )
    title = models.CharField(_('帖子标题'), max_length=200, blank=True, null=True)
    content = models.TextField(_('帖子内容'))
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('发布时间'))
    updated_at = models.DateTimeField(auto_now=True, verbose_name=_('更新时间'))

    class Meta:
        verbose_name = _('帖子/动态')
        verbose_name_plural = _('帖子/动态们')
        ordering = ['-created_at']

    def __str__(self):
        author_identifier = self.author.email
        if hasattr(self.author, 'display_name') and self.author.display_name:
            author_identifier = self.author.display_name
        elif hasattr(self.author, 'nickname') and self.author.nickname:
            author_identifier = self.author.nickname
        title_part = f"'{self.title}'" if self.title else f"动态来自 {author_identifier}"
        return f"{title_part} 在小组 '{self.group.name}'"

class Comment(models.Model):
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name='comments',
        verbose_name=_('所属帖子')
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='%(app_label)s_comments',
        verbose_name=_('评论作者')
    )
    content = models.TextField(_('评论内容'))
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('评论时间'))
    updated_at = models.DateTimeField(auto_now=True, verbose_name=_('更新时间'))

    class Meta:
        verbose_name = _('评论')
        verbose_name_plural = _('评论们')
        ordering = ['created_at']

    def __str__(self):
        author_identifier = self.author.email
        if hasattr(self.author, 'display_name') and self.author.display_name:
            author_identifier = self.author.display_name
        elif hasattr(self.author, 'nickname') and self.author.nickname:
            author_identifier = self.author.nickname
        post_identifier = self.post.title if self.post.title else f"帖子ID({self.post.id})"
        content_preview = (self.content[:30] + '...') if len(self.content) > 30 else self.content
        return f"{author_identifier} 对 '{post_identifier}' 的评论: \"{content_preview}\""

class PostLike(models.Model): # <<<< 新增 PostLike 模型
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='post_likes',
        verbose_name=_('点赞用户')
    )
    post = models.ForeignKey(
        Post,
        on_delete=models.CASCADE,
        related_name='likes', # 允许 post.likes.count()
        verbose_name=_('被点赞的帖子')
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('点赞时间'))

    class Meta:
        verbose_name = _('帖子点赞')
        verbose_name_plural = _('帖子点赞们')
        unique_together = ('user', 'post') # 核心：确保用户对帖子只能点赞一次
        ordering = ['-created_at']

    def __str__(self):
        user_identifier = self.user.email
        if hasattr(self.user, 'display_name') and self.user.display_name:
            user_identifier = self.user.display_name
        elif hasattr(self.user, 'nickname') and self.user.nickname:
            user_identifier = self.user.nickname
        
        post_identifier = self.post.title if self.post.title else f"帖子ID({self.post.id})"
        return f"{user_identifier} 点赞了 '{post_identifier}'"