# apps/core/services/route_service.py
import os

import psutil
from django.urls import include, path

_dynamic_routes = []


def register_app_urls(prefix, app_name, priority=False):
    """注册应用路由并支持优先级控制
    :param priority: True表示前置插入，False表示追加
    """
    new_route = path(f"{prefix}/", include(f"{app_name}.urls"))
    if priority:
        _dynamic_routes.insert(0, new_route)
    else:
        _dynamic_routes.append(new_route)


def get_dynamic_routes():
    # """获取所有动态注册的路由"""
    # now = datetime.now()
    # pid = os.getpid()  # 获取当前进程ID
    # print(f'{now}:加载动态路由,包括自开发应用和插件等。')
    # return _dynamic_routes.copy()  # 返回副本防止意外修改
    """获取所有动态注册的路由"""
    try:
        current_process = psutil.Process(os.getpid())
        pid = current_process.pid
        pname = current_process.name()

        print(f'DjacoreCMS: 进程 [{pname}({pid})] 加载动态路由,包括自开发应用和插件等。')
    except Exception as e:
        print('DjacoreCMS "get_dynamic_routes"==========>', e)
    return _dynamic_routes.copy()


from collections import OrderedDict

from django.urls import URLPattern, URLResolver, get_resolver


def get_all_urls(resolver=None, pre='/', url_dict=None):
    """
    递归获取 Django 项目中的所有路由信息
    
    参数:
        resolver: URL 解析器，默认为根解析器
        pre: 当前层级的前缀
        url_dict: 存储路由信息的字典
        
    返回:
        有序字典，包含所有路由的模式和名称
    """
    if url_dict is None:
        url_dict = OrderedDict()

    if resolver is None:
        resolver = get_resolver()

    for pattern in resolver.url_patterns:
        if isinstance(pattern, URLPattern):
            # 处理终端路由
            pattern_str = str(pattern.pattern).replace('^',
                                                       '').replace('$', '')
            full_pattern = pre + pattern_str
            url_dict[full_pattern] = pattern.name
        elif isinstance(pattern, URLResolver):
            # 处理包含的子路由，递归获取
            pattern_str = str(pattern.pattern).replace('^',
                                                       '').replace('$', '')
            new_pre = pre + pattern_str
            get_all_urls(pattern, new_pre, url_dict)

    return url_dict
