import importlib
import pkgutil
from typing import Optional
from fastapi import FastAPI


def include_routers_from_package(app: FastAPI, package: str, prefix: str = "") -> int:
	"""从给定包下自动发现并注册包含 `router` 的模块。
	返回成功注册的路由模块数量。
	"""
	registered = 0
	pkg = importlib.import_module(package)
	
	# 收集所有模块信息
	modules = list(pkgutil.iter_modules(pkg.__path__, package + "."))
	
	for module_info in modules:
		module_name = module_info.name
		try:
			mod = importlib.import_module(module_name)
			router = getattr(mod, "router", None)
			if router is not None:
				app.include_router(router, prefix=prefix)
				registered += 1
		except Exception as e:
			# 启动期容错：打印日志即可，避免因单个模块导致整体失败
			print(f"[router:auto] failed to register {module_name}: {e}")
	
	print(f"[router:auto] registered {registered} route modules from {package}")
	return registered


