from django.contrib import admin
from django.utils.safestring import mark_safe

from ..models import DebugSetting
from .mixins import SingletonAdminMixin


def get_client_ip(request):
    # 优先从代理头获取真实IP（需配置可信代理）
    x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
    if x_forwarded_for:
        ip = x_forwarded_for.split(",")[0].strip()
    else:
        ip = request.META.get("REMOTE_ADDR")
    return ip or "无法获取IP"


@admin.register(DebugSetting)
class DebugSettingAdmin(SingletonAdminMixin, admin.ModelAdmin):
    readonly_fields = ("client_ip_display",)  # 只读字段显示访问者IP
    # 自定义管理界面
    fieldsets = (
        (
            "",
            {
                "description": mark_safe(
                    '<div class="alert alert-warning">打开调式模式，右侧会打开debug-tools助手.正式线上不要轻易打开debug模式，会暴露很多数据和服务器信息<br>第一次打开调式模式，需要收集一下静态后，再刷新前后端可显示debug-tools,否则会因为debug-tools所需要静态没有加载而在网页底部混乱显示。</div>'
                ),
                "fields": (),
            },
        ),
        (
            "核心设置",
            {
                "fields": ("debug_mode", "internal_ips", "client_ip_display"),
            },
        ),
    )

    def client_ip_display(self, obj):
        request = self.get_request()
        return f"当前访问者IP：{get_client_ip(request)}"

    client_ip_display.short_description = "访问者IP"

    def get_request(self):
        # 通过Admin实例获取当前请求对象
        return self.admin_site.each_context(self.request)["request"]
