# 文章版本管理模型
# 用于追踪文章的修改历史，支持版本对比和回滚

from django.conf import settings
from django.db import models
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _

from blog.models import Article


class ArticleVersion(models.Model):
    """
    文章版本模型
    每次文章保存时自动创建版本记录
    """
    # 关联的文章
    article = models.ForeignKey(
        Article,
        verbose_name='文章',
        on_delete=models.CASCADE,
        related_name='versions'
    )

    # 版本号（自动递增）
    version_number = models.PositiveIntegerField('版本号', default=1)

    # 文章标题（保存时的标题）
    title = models.CharField('标题', max_length=200)

    # 文章正文（保存时的内容）
    body = models.TextField('正文')

    # 发布时间
    pub_time = models.DateTimeField('发布时间')

    # 状态
    status = models.CharField('状态', max_length=1)

    # 评论状态
    comment_status = models.CharField('评论状态', max_length=1)

    # 类型
    type = models.CharField('类型', max_length=1)

    # 分类（保存时的分类ID）
    category_id = models.IntegerField('分类ID')
    category_name = models.CharField('分类名称', max_length=30)

    # 创建版本的用户
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name='创建者',
        on_delete=models.SET_NULL,
        null=True,
        related_name='article_versions_created'
    )

    # 版本创建时间
    creation_time = models.DateTimeField('创建时间', default=now, db_index=True)

    # 变更说明（可选）
    change_summary = models.CharField(
        '变更说明',
        max_length=200,
        blank=True,
        default=''
    )

    # 是否为自动保存
    is_auto_save = models.BooleanField('自动保存', default=True)

    class Meta:
        ordering = ['-version_number']
        verbose_name = '文章版本'
        verbose_name_plural = '文章版本'
        unique_together = [['article', 'version_number']]
        indexes = [
            models.Index(fields=['article', '-version_number'], name='version_article_num_idx'),
            models.Index(fields=['creation_time'], name='version_creation_time_idx'),
        ]

    def __str__(self):
        return f"{self.article.title} - v{self.version_number}"

    @classmethod
    def create_version(cls, article, user=None, change_summary='', is_auto_save=True):
        """
        创建文章版本

        Args:
            article: Article 实例
            user: 创建版本的用户
            change_summary: 变更说明
            is_auto_save: 是否为自动保存

        Returns:
            ArticleVersion 实例
        """
        # 获取最新版本号
        latest_version = cls.objects.filter(article=article).first()
        version_number = (latest_version.version_number + 1) if latest_version else 1

        # 创建版本记录
        version = cls.objects.create(
            article=article,
            version_number=version_number,
            title=article.title,
            body=article.body,
            pub_time=article.pub_time,
            status=article.status,
            comment_status=article.comment_status,
            type=article.type,
            category_id=article.category_id,
            category_name=article.category.name,
            created_by=user or article.author,
            change_summary=change_summary,
            is_auto_save=is_auto_save
        )

        return version

    def restore_to_article(self):
        """
        将此版本恢复到文章

        Returns:
            bool: 是否成功恢复
        """
        try:
            article = self.article
            article.title = self.title
            article.body = self.body
            article.pub_time = self.pub_time
            article.status = self.status
            article.comment_status = self.comment_status
            article.type = self.type

            # 尝试恢复分类（如果分类ID仍存在）
            from blog.models import Category
            try:
                category = Category.objects.get(id=self.category_id)
                article.category = category
            except Category.DoesNotExist:
                # 如果原分类已删除，保持当前分类不变
                pass

            article.save()
            return True
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to restore version {self.id}: {e}")
            return False

    def get_diff_with_current(self):
        """
        获取与当前文章的差异

        Returns:
            dict: 包含差异信息的字典
        """
        article = self.article
        diff = {
            'title_changed': self.title != article.title,
            'body_changed': self.body != article.body,
            'status_changed': self.status != article.status,
            'category_changed': self.category_id != article.category_id,
        }
        return diff
