from fastapi import FastAPI, Depends,HTTPException,Request,status,Response
from router.auth import auth_router, oauth2_scheme, verify_token
from router.users import users_router
from router.graph import graph_router
from router.file_browse import file_browse_router
from router.kg import kg_router
from router.tasks import task_router
from router.nlp_models import  nlp_router
from router.labeling import labeling_router
from router.data_import import data_import_router
from router.data_export import data_export_router
from router.dify_kb import dify_kb_router
from db.database import Base, engine
import router.errors as errors
import jieba

jieba.load_userdict("./dict/jieba_dict.txt")


    
#from models.response import ResponseFormatterMiddleware
app = FastAPI()
@app.middleware("http")
async def debug_middleware(request: Request, call_next):
    print(f"Request path: {request.url.path}")
    response = await call_next(request)
    if response.status_code == 404:
        print(f"404 Not Found for path: {request.url.path}")
    return response        
errors.registerCustomErrorHandle(app)
Base.metadata.create_all(bind=engine)
# 添加中间件到应用中
#app.add_middleware(ResponseFormatterMiddleware)
# 挂载路由
app.include_router(auth_router)
app.include_router(users_router)
#app.include_router(graph_router, dependencies=[Depends(oauth2_scheme)])
app.include_router(file_browse_router)
app.include_router(kg_router)
app.include_router(nlp_router)
app.include_router(task_router)
app.include_router(labeling_router)
app.include_router(data_import_router)
app.include_router(data_export_router)
app.include_router(dify_kb_router)

def print_all_routes():
    print("Listing all routes:")
    for route in app.routes:
        # 获取路径
        path = route.path
        # 获取方法列表
        methods = ','.join([method for method in route.methods]) if hasattr(route, 'methods') else 'N/A'
        # 获取名称（通常是处理函数的名字）
        name = route.name
        print(f"Path: {path}, Methods: {methods}, Name: {name}")

        
print_all_routes()
# @app.middleware("http")
# async def verify_http_token(request: Request, call_next):
#     auth_error = HTTPException(
#         status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
#         detail="Internal services error",
#         headers={"WWW-Authenticate": "Bearer"},  # OAuth2的规范，如果认证失败，请求头中返回“WWW-Authenticate”
#     )
#     # 获取请求路径
#     path: str = request.get('path')
#     # 登录接口、docs文档依赖的接口，不做token校验
#     if path.startswith('/api/token') | path.startswith('/api/docs') | path.startswith('/api/openapi') | path.startswith('/api/node-create'):
#         response = await call_next(request)
#         return response
#     else:
#         try:
#             # 从header读取token
#             authorization: str = request.headers.get('authorization')         
                
#             response = Response(
#                     status_code=status.HTTP_401_UNAUTHORIZED,
#                     content="Invalid authentication credentials",
#                     headers={"WWW-Authenticate": "Bearer"},  # OAuth2的规范，如果认证失败，请求头中返回“WWW-Authenticate”
#             )
#             if not authorization:
#                 print("request was not authorized")
#                 return response
#             # 拿到token值
#             token = authorization.split(' ')[1]
#             # 这个是我自己封装的校验token的逻辑，大家可以自己替换成自己的
            
#             if verify_token(token):
#                 print("request token was correct")
#                 response = await call_next(request)
#                 return response
            
#             print("request token was incorrect")
#             return response
#         except Exception as e:
#             print("http_middleware error: ", e)
            
#             return auth_error
        
        
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app='main:app', host="0.0.0.0", port=8000, reload=True)
