from django.contrib.sitemaps import Sitemap
from django.urls import reverse, get_resolver
from django.conf import settings
from django.urls.resolvers import URLPattern, URLResolver

class Site:
    domain = settings.BASE_URL
    name = settings.BASE_URL
    def __str__(self):
        return self.domain

class StaticSitemap(Sitemap):
    changefreq = "monthly"
    priority = 0.8
    protocol = 'https'  # Default to https, will be set dynamically

    def get_urls(self, site=None, protocol=None, **kwargs):
        # Use the dynamic protocol
        return super().get_urls(site=Site(), protocol=self.protocol, **kwargs)

    def items(self):
        # Get URL patterns specifically from the 'website' app
        url_patterns = self._get_app_urls('website')
        return [name for name in url_patterns if isinstance(name, str)]

    def _get_app_urls(self, app_name):
        resolver = get_resolver()
        url_patterns = []

        # Recursively extract URL names for the specified app
        def extract_urls(patterns):
            for pattern in patterns:
                if isinstance(pattern, URLPattern) and pattern.callback.__module__.startswith(app_name):
                    # If the URL pattern belongs to the specified app
                    if pattern.name:
                        url_patterns.append(pattern.name)
                elif isinstance(pattern, URLResolver):
                    # Recursively check included URLConfs
                    extract_urls(pattern.url_patterns)

        extract_urls(resolver.url_patterns)
        return url_patterns

    def location(self, item):
        # Return the URL for the sitemap
        return reverse(item)