"""Auto-discovers backend modules under modules/ — any subpackage with a
router.py exposing `router` (an APIRouter) is mounted automatically. Drop a
new module folder in and it's picked up on next start; nothing here needs
editing.

A missing router.py just means the folder isn't a module (skipped quietly).
An import error *inside* an existing router.py is a real bug and is left to
raise — silently swallowing it would hide broken modules instead of
surfacing them at startup.
"""
from __future__ import annotations

import importlib
import pkgutil
from pathlib import Path
from typing import List

from fastapi import APIRouter

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


def _discover() -> List[APIRouter]:
    routers = []
    for info in sorted(pkgutil.iter_modules([str(_MODULES_DIR)]), key=lambda m: m.name):
        if not info.ispkg:
            continue
        if not (_MODULES_DIR / info.name / "router.py").exists():
            continue
        mod = importlib.import_module(f"modules.{info.name}.router")
        router = getattr(mod, "router", None)
        if isinstance(router, APIRouter):
            routers.append(router)
    return routers


ROUTERS = _discover()
