import os
from fastapi import FastAPI, Depends
from fastapi_pagination import add_pagination
from starlette.requests import Request
import uvicorn
from app.api.api_v1.routers.kintone import kinton_router
from app.api.api_v1.routers.users import users_router
from app.api.api_v1.routers.auth import auth_router
from app.api.api_v1.routers.platform import platform_router
from app.core import config
#from app.db import Base,engine
from app.core.auth import get_current_active_user
from app.core.celery_app import celery_app
from app import tasks
from fastapi.middleware.cors import CORSMiddleware
import logging
from app.core.apiexception import APIException, writedblog
from app.core.common import ApiReturnError
from app.db.crud import create_log
from fastapi.responses import JSONResponse
import asyncio
from contextlib import asynccontextmanager
from app.core.operation import LoggingMiddleware

#Base.metadata.create_all(bind=engine) 

@asynccontextmanager
async def lifespan(app: FastAPI):
    startup_event()
    yield

app = FastAPI(
    title=config.PROJECT_NAME, docs_url="/api/docs", openapi_url="/api",lifespan=lifespan
)

origins = [
    "*"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(LoggingMiddleware)

add_pagination(app)

# @app.middleware("http")
# async def db_session_middleware(request: Request, call_next):
#     request.state.db = SessionLocal()
#     response = await call_next(request)
#     request.state.db.close()
#     return response

def startup_event():
    log_dir="log"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    logger = logging.getLogger("uvicorn.access")
    handler = logging.handlers.RotatingFileHandler(f"{log_dir}/api.log",mode="a",maxBytes = 100*1024, backupCount = 3)
    handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
    logger.addHandler(handler)

@app.exception_handler(APIException)
async def api_exception_handler(request: Request, exc: APIException):
    loop = asyncio.get_event_loop()
    loop.run_in_executor(None,writedblog,exc)
    return JSONResponse(
            status_code=exc.status_code,
            content= ApiReturnError(msg = f"{exc.detail}").model_dump(),
    )

@app.get("/api/v1")
async def root():
    return {"message": "success"}


@app.get("/api/v1/task")
async def example_task():
    celery_app.send_task("app.tasks.example_task", args=["Hello World"])

    return {"message": "success"}


# Routers
app.include_router(
    users_router,
    prefix="/api/v1",
    tags=["users"],
    dependencies=[Depends(get_current_active_user)],
)
app.include_router(auth_router, prefix="/api", tags=["auth"])
app.include_router(kinton_router,prefix="/api/v1",tags=["kintone"])
app.include_router(platform_router,prefix="/api",tags=["platform"])

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", reload=True, port=8888)
