import re
import uuid
from datetime import datetime

import pytz
from apps.content.utils.processors import process_keywords
from apps.content.utils.text_processor import clean_truncate_intro
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _


class BaseModel(models.Model):
    """
    所有模型的基类，包含通用字段
    """

    class StatusChoices(models.IntegerChoices):
        REVIEW = 99, _("已发布")  # 正式发布
        STORED = 0, _("已入库")  # 新增入库状态 ★
        DRAFT = 1, _("草稿")  # 初始编辑状态
        SUBMITTED = 2, _("已提交")  # 提交待审
        IN_REVIEW = 3, _("审核中")  # 正在审核
        APPROVED = 4, _("已通过")  # 审核通过

        REJECTED = 5, _("已驳回")  # 审核驳回
        ARCHIVED = 6, _("已归档")  # 历史归档

    create_time = models.DateTimeField(
        verbose_name=_("创建时间"), auto_now_add=True, db_index=True, editable=False
    )
    update_time = models.DateTimeField(verbose_name=_("更新时间"), auto_now=True)
    status = models.PositiveSmallIntegerField(
        choices=StatusChoices.choices, default=StatusChoices.REVIEW, verbose_name=_("审核状态")
    )
    template = models.FilePathField(
        verbose_name=_("个性模板"),
        path=settings.TEMPLATES_THEME_DIR,  # 动态路径获取
        match=r".*\.html$",
        recursive=True,
        allow_files=True,
        allow_folders=False,
        blank=True,
        max_length=500,
    )

    class Meta:
        abstract = True  # 设为抽象基类，不会创建数据库表
        ordering = ["-create_time"]  # 默认按创建时间倒序


class SEOMixin(models.Model):
    """
    SEO基础模型类（抽象基类）
    使用方法：class Article(SEOMixin, models.Model)
    """

    meta_title = models.CharField(
        verbose_name=_("SEO标题"), max_length=200, blank=True, help_text=_("建议长度60个字符内")
    )
    meta_description = models.TextField(
        verbose_name=_("SEO描述"), max_length=300, blank=True, help_text=_("建议长度150-300字符")
    )
    meta_keywords = models.CharField(
        verbose_name=_("SEO关键词"),
        max_length=200,
        blank=True,
        help_text=_("多个关键词用英文逗号分隔"),
    )
    canonical_url = models.URLField(
        verbose_name=_("规范链接"), blank=True, help_text=_("用于防止重复内容，留空自动生成")
    )
    slug = models.SlugField(
        verbose_name=_("URL标识"),
        max_length=200,
        blank=True,  # 允许表单提交为空（后台逻辑强制生成）
        null=False,  # 数据库层保持非空约束
        unique_for_date="update_time",  # 假设有发布时间字段
        allow_unicode=True,
        help_text=_("URL友好化标识，留空自动生成"),
    )
    og_title = models.CharField(verbose_name=_("Open Graph标题"), max_length=200, blank=True)
    og_description = models.TextField(verbose_name=_("Open Graph描述"), max_length=300, blank=True)
    twitter_card_type = models.CharField(
        verbose_name=_("Twitter卡片类型"),
        max_length=20,
        choices=(("summary", _("摘要")), ("summary_large_image", _("大图摘要"))),
        default="summary",
    )

    class Meta:
        abstract = True  # 声明为抽象基类

    def save(self, *args, **kwargs):
        """自动处理字段逻辑"""
        from apps.core.models.content_config import ContentConfig

        config = ContentConfig.get_solo()

        if not self.meta_title:
            self.meta_title = self.title

        self.meta_keywords = re.sub(
            r"[，。!?,;]$", "", self.meta_keywords.replace("，", ",").strip()
        )

        # 自动生成slug（处理中文转拼音）
        if not self.slug or len(self.slug.strip()) == 0:  # 覆盖空字符串场景
            from slugify import slugify  # 使用更强大的 slugify 库

            base_slug = slugify(self.title, max_length=180, lowercase=True, separator="-")
            timestamp = datetime.now(pytz.utc).strftime("%Y%m%d%H%M%S")
            unique_suffix = uuid.uuid4().hex[:6]  # 添加随机后缀
            self.slug = f"{base_slug}-{timestamp}-{unique_suffix}"[:200]  # 长度截断保险

        # 自动生成meta描述
        if not self.meta_description.strip() and config.auto_summary and hasattr(self, "content"):
            self.meta_description = clean_truncate_intro(self.content, config)

        # 设置OG默认值
        if not self.og_title:
            self.og_title = self.meta_title or self.title
        if not self.og_description:
            self.og_description = self.meta_description

        super().save(*args, **kwargs)

        # 异步处理关键词
        import threading

        threading.Thread(target=process_keywords, args=(self,)).start()

    def get_meta_tags(self):
        """生成完整的meta标签字典（模板中可直接使用）"""
        return {
            "title": self.meta_title or self.title,
            "description": self.meta_description,
            "keywords": self.meta_keywords,
            "og": {
                "type": "article",
                "title": self.og_title,
                "description": self.og_description,
                "url": self.get_absolute_url(),
            },
            "twitter": {
                "card": self.twitter_card_type,
                "title": self.og_title,
                "description": self.og_description,
            },
        }
