# apps/core/sitemap.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse

from .models.sitemap import SitemapConfig


class DynamicSitemap:

    def __new__(cls):
        config = SitemapConfig.get_solo()
        if getattr(config, "enable_index", False):
            return IndexSitemapGenerator()
        return UnifiedSitemapGenerator()


class IndexSitemapGenerator:

    def __init__(self):
        self.config = SitemapConfig.get_solo()
        self.sitemaps = self._generate_sitemaps()
        # 添加sitemap_obj属性指向自己，保持接口统一
        self.sitemap_obj = self

    def _generate_sitemaps(self):
        sitemap_dict = {}
        for model_class in self.config.get_active_models():
            section = f"{model_class._meta.app_label}_{model_class._meta.model_name}"
            sitemap_dict[section] = self._create_model_sitemap(model_class)
        return sitemap_dict

    def _create_model_sitemap(self, model_class):
        class ModelSitemap(Sitemap):
            changefreq = self.config.changefreq
            priority = float(self.config.priority)
            limit = self.config.paginate_by
            protocol = self.config.protocol

            def items(self):
                if model_class._meta.model_name == "category":
                    return model_class.objects.filter(review_status=1)
                return model_class.objects.filter(status=99)

            def location(self, obj):
                from apps.core.models import GlobalDNSConfig
                from apps.core.models.site_settings import SiteSettings

                dns_config = GlobalDNSConfig.get_solo()
                absolute_url = obj.get_absolute_url()
                primary_domain = dns_config.primary_domain

                # 如果启用了DNS配置且URL中已包含主域名
                if dns_config.status == "enabled" and primary_domain in obj.get_absolute_url():
                    site_url = SiteSettings.get_solo().site_url
                    if self.protocol == "http":
                        absolute_url = "http:" + absolute_url
                    else:
                        absolute_url = "https:" + absolute_url

                return absolute_url

            def _urls(self, page, protocol, domain):
                from apps.core.models import GlobalDNSConfig

                dns_config = GlobalDNSConfig.get_solo()
                urls = []
                latest_lastmod = None
                all_items_lastmod = True

                paginator_page = self.paginator.page(page)

                for item in paginator_page.object_list:

                    # 获取location方法返回的URL
                    location_result = self._location(item)

                    # 检查是否需要自定义处理
                    if (
                        dns_config.status == "enabled"
                        and dns_config.primary_domain
                        and dns_config.primary_domain in location_result
                        and location_result.startswith(("http://", "https://"))
                    ):
                        # 如果已经是完整的URL且包含主域名，直接使用
                        loc = location_result
                    else:
                        # 否则使用Django的默认拼接逻辑
                        loc = f"{protocol}://{domain}{location_result}"

                    priority = self._get("priority", item)
                    lastmod = self._get("lastmod", item)

                    if all_items_lastmod:
                        all_items_lastmod = lastmod is not None
                        if all_items_lastmod and (
                            latest_lastmod is None or lastmod > latest_lastmod
                        ):
                            latest_lastmod = lastmod

                    url_info = {
                        "item": item,
                        "location": loc,
                        "lastmod": lastmod,
                        "changefreq": self._get("changefreq", item),
                        "priority": str(priority if priority is not None else ""),
                        "alternates": [],
                    }

                    urls.append(url_info)

                if all_items_lastmod and latest_lastmod:
                    self.latest_lastmod = latest_lastmod

                return urls

        return ModelSitemap()


class UnifiedSitemapGenerator(Sitemap):
    # config = SitemapConfig.get_solo()
    # limit = getattr(config, 'paginate_by', 50)
    # priority = getattr(config, 'priority', 0.5)
    # changefreq = getattr(config, 'changefreq', 'daily')
    def __init__(self):
        self.config = SitemapConfig.get_solo()  # 在初始化时获取配置
        # 将原来的类属性改为实例属性
        self.limit = getattr(self.config, "paginate_by", 50)
        self.priority = getattr(self.config, "priority", 0.5)
        self.changefreq = getattr(self.config, "changefreq", "daily")
        # 为了保持接口统一，添加sitemap_obj属性指向自己
        self.sitemap_obj = self
        self.sitemaps = {"all": self}

    def get_paginate_by(self, obj_list):
        """动态返回配置中的分页数"""
        return self.config.paginate_by

    def items(self):
        items = []
        for model_class in self.config.get_active_models():
            if model_class._meta.model_name == "category":
                items.extend(model_class.objects.filter(review_status=1))
            else:
                items.extend(model_class.objects.filter(status=99))
        return items

    def location(self, obj):
        return obj.get_absolute_url()
