"""业务路由注册中心 (route registry).

═══════════════════════════════════════════════════════════════════════════
  这里是"业务路由"的总装配点。app/routes/ 目录下每个 *.py 文件只要定义了一个
  名为 `router` 的 APIRouter，就会被自动发现并挂载 —— 你不用改这个文件。
  Every *.py file in app/routes/ that defines a top-level `router` (APIRouter)
  is auto-discovered and mounted. You do NOT edit this file to add an endpoint.
═══════════════════════════════════════════════════════════════════════════
"""

import importlib
import pkgutil
from pathlib import Path

from fastapi import APIRouter, FastAPI

_ROUTES_DIR = Path(__file__).resolve().parent


def _discover_routers() -> list[APIRouter]:
    """扫描本包下所有模块，收集其顶层 `router` 对象."""
    routers: list[APIRouter] = []
    for module_info in pkgutil.iter_modules([str(_ROUTES_DIR)]):
        module = importlib.import_module(f"{__name__}.{module_info.name}")
        candidate = getattr(module, "router", None)
        if isinstance(candidate, APIRouter):
            routers.append(candidate)
    return routers


def register_routes(app: FastAPI) -> None:
    """把发现到的全部业务路由挂载到应用上."""
    for router in _discover_routers():
        app.include_router(router)
