
from datetime import datetime

from config.config import SystemConfig
from django.contrib import admin

from .models import UpgradeProgress
from .utils import get_latest_version


@admin.register(UpgradeProgress)
class UpgradeAdmin(admin.ModelAdmin):

    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def get_queryset(self, request):
        return UpgradeProgress.objects.none()  # 返回空查询集

    change_list_template = 'admin/upgrade/change_list.html'

    def changelist_view(self, request, extra_context=None):
        context = extra_context or {}
        current_version_str = SystemConfig.VERSION.lstrip('Vv')  # 确保去除前缀
        can_upgrade = False
        notice = "当前已是最新版本"
        latest_version_str = "unknown"

        try:
            # 获取并处理版本号
            raw_latest, data = get_latest_version()

            latest_version_str = raw_latest.lstrip('Vv')

            if latest_version_str == '0.0.0':
                notice = f"版本检测失败"

            # 版本号有效性验证
            def is_valid_version(v):
                base_ok = all(c.isdigit() or c in ('.', '_', 'p') for c in v)
                struct_ok = ((v.count('.') >= 2) or  # 主版本号 1.0.0
                             ('_p' in v and v.split('_p')[0].count('.') >= 2
                              )  # 补丁版本 1.0.0_p1
                             )
                return base_ok and struct_ok

            if not all(
                    map(is_valid_version,
                        [current_version_str, latest_version_str])):
                raise ValueError("版本号格式不符合要求")

            # 版本号解析比较（支持主版本和补丁版本）
            def parse_version(v):
                main_part, patch = v.split('_p') if '_p' in v else (v, '0')
                main_numbers = list(map(int, main_part.split('.')[:3]))  # 取前三位
                return main_numbers + [int(patch)]

            current_ver = parse_version(current_version_str)
            latest_ver = parse_version(latest_version_str)

            # 按顺序比较主版本和补丁号
            can_upgrade = latest_ver > current_ver

        except Exception as e:
            notice = f"版本检测异常：{str(e)}"

        if can_upgrade:
            notice = f"发现新版本 {latest_version_str} 可升级"

        # 构造上下文
        context.update({
            'current_version':
            f"V{current_version_str}",
            'latest_version':
            f"V{latest_version_str}"
            if latest_version_str != "unknown" else "未知",
            'can_upgrade':
            can_upgrade,
            'latest_version_data':
            data,
            'update_notice':
            notice,
            "last_check_time":
            datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })

        return super().changelist_view(request, extra_context=context)
