import os
import importlib
from pathlib import Path
from fastapi import FastAPI
from {{ base_package }}.core.config import settings
from {{ base_package }}.core.exceptions import AppError, app_error_handler
from {{ base_package }}.core.logger import logger

def register_routers(app: FastAPI):
    """
    自动发现并注册 features 目录中的路由。
    支持结构: features/{db_name}_{ip}/{schema}_{table}/{op}/public.py
    以及简单结构: features/{slice_name}/public.py
    """
    # 根据此文件位置推导 base_package_path
    app_dir = Path(__file__).parent
    features_dir = app_dir / "features"
    
    if not features_dir.exists():
        return

    # 遍历 features 目录
    for root, dirs, files in os.walk(features_dir):
        if "public.py" in files:
            try:
                # 计算相对于 app 根目录的模块路径
                # 例如 root = .../app/features/xyz, app_dir = .../app
                # relative = features/xyz
                rel_path = Path(root).relative_to(app_dir)
                
                # 构建模块导入字符串: app.features.xyz.public
                module_name = f"{{ base_package }}.{str(rel_path).replace(os.sep, '.')}.public"
                
                module = importlib.import_module(module_name)
                if hasattr(module, "router"):
                    router = module.router
                    
                    # 根据路径确定前缀和标签
                    # 相对于 features 目录的路径部分
                    path_parts = Path(root).relative_to(features_dir).parts
                    
                    if len(path_parts) >= 3:
                        # 结构: {db_folder}/{table_folder}/{op}
                        db_folder = path_parts[0]
                        table_folder = path_parts[1]
                        op = path_parts[2]
                        
                        prefix = f"/{db_folder}/{table_folder}/{op.replace('_', '-')}"
                        tag = f"{db_folder}.{table_folder}"
                        
                        app.include_router(router, prefix=prefix, tags=[tag])
                        logger.info(f"已注册路由: {prefix}")
                        
                    elif len(path_parts) == 1:
                        # 结构: {slice_name}
                        slice_name = path_parts[0]
                        prefix = f"/{slice_name.replace('_', '-')}"
                        app.include_router(router, prefix=prefix, tags=[slice_name])
                        logger.info(f"已注册路由: {prefix}")
                        
            except Exception as e:
                logger.error(f"从 {root} 注册路由失败: {e}")

def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.PROJECT_NAME,
        openapi_url=f"{settings.API_V1_STR}/openapi.json"
    )

    # 注册异常处理器
    app.add_exception_handler(AppError, app_error_handler)

    # 自动注册路由
    register_routers(app)

    @app.get("/")
    async def root():
        return {"message": f"欢迎使用 {settings.PROJECT_NAME}"}

    return app

app = create_app()
