import time
from pathlib import Path

from apps.content.models import Category
from django import forms
from django.conf import settings
from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from mptt.forms import TreeNodeChoiceField

from ..models import Article
from .mixins import SingletonAdminMixin


class ArticleForm(forms.ModelForm):
    category = TreeNodeChoiceField(
        queryset=Category.objects.filter(content_type__model='article'),
        label="栏目",
        help_text="选择树状栏目",
    )

    class Meta:
        model = Article
        fields = '__all__'


@admin.register(Article)
class ArticleAdmin(SingletonAdminMixin, admin.ModelAdmin):
    form = ArticleForm
    list_filter = ('status', 'category', 'editor')
    search_fields = ('title', 'subtitle', 'content', 'author', 'source')
    # list_editable = ('allow_comment', 'status')
    # 日期导航
    @property
    def date_hierarchy(self):
        """
        依赖 ContentConfig.get_solo() 方法自身的内置缓存。
        避免在模块加载时访问数据库，同时保证效率。
        """
        from apps.core.models.content_config import ContentConfig
        try:
            # 依赖于 get_solo() 方法内部的缓存实现
            content_config = ContentConfig.get_solo()
            if getattr(content_config, 'date_hierarchy', False):
                return 'update_time'
        except Exception:
            # 优雅处理异常，例如初次迁移时表可能不存在
            pass
        return None

    # radio_fields = {'status': admin.HORIZONTAL}

    # 字段分组布局
    fieldsets = (
        (None, {
            'fields': ('title', 'py_title', 'subtitle', ('category', 'status'),
                       ('author', 'source'))
        }),
        ('内容管理', {
            'fields': ('content', 'thumb_image')
        }),
        ('SEO优化', {
            'classes': ('collapse', ),
            'fields': ('meta_title', 'meta_description', 'meta_keywords',
                       'canonical_url', 'slug', ('og_title', 'og_description'),
                       'twitter_card_type')
        }),
        # ('内容关联', {
        #     'classes': ('collapse', ),
        #     'fields': (('related_tags', 'related_wikis'), )
        # }),
        ('发布设置', {
            'fields': (('allow_comment', 'editor'), 'template',
                       ('update_time', 'create_time'))
        }),
        ('权限控制', {
            'classes': ('collapse', ),
            'fields': ('staff_only', 'allowed_groups')
        }))

    # 自定义方法
    def view_thumb_preview(self, obj):
        if obj.thumb_image:
            return format_html(
                '<img src="{}" style="max-height:50px;max-width:100px;" />',
                obj.thumb_image.url)
        return "-"

    view_thumb_preview.short_description = '缩略图预览'

    # 其他优化配置
    filter_horizontal = ('related_tags', 'related_wikis')
    show_full_result_count = False

    def cached_status(self, obj):
        """显示单个文章的缓存状态"""
        filepath = Path(
            settings.BASE_DIR) / 'html' / f"{obj.category.slug}/{obj.pk}.html"
        if not filepath.exists():
            return '未生成'
        age = time.time() - filepath.stat().st_mtime
        return f"{int(age//3600)}小时前生成" if age < 86400 else '已过期'

    cached_status.short_description = '缓存状态'

    # 表单字段自定义
    # def formfield_for_dbfield(self, db_field, request, **kwargs):
    #     # 优化状态字段显示为单选按钮
    #     if db_field.name == 'status':
    #         kwargs['widget'] = admin.widgets.AdminRadioSelect(
    #             attrs={'class': 'status-radio'})
    #         kwargs['choices'] = Article.StatusChoices.choices
    #     return super().formfield_for_dbfield(db_field, request, **kwargs)


# Admin 安全引用示例‌：
# apps/articles/admin/article.py
# from django.contrib import admin
# from django.apps import apps

# Article = apps.get_model('articles.Article')  # 避免循环导入

# @admin.register(Article)
# class ArticleAdmin(admin.ModelAdmin):
#     pass
