from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from starlette.responses import FileResponse
from starlette.staticfiles import StaticFiles as StarletteStaticFiles
from app.api.v1.api import api_router
from app.core.config import settings
from app.db.session import engine
from app.db.base import Base
from app.core.logging_config import setup_logging
import os


import app.models.user           
import app.models.password_reset

# Create logs directory if it doesn't exist
os.makedirs("logs", exist_ok=True)

# Setup logging
logger = setup_logging()

# Create database tables
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="Adimsayer API",
    description="Adimsayer Backend API",
    version="1.0.0",
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    docs_url=f"{settings.API_V1_STR}/docs",
    redoc_url=f"{settings.API_V1_STR}/redoc",
)

# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"],
    )

# Include API router
app.include_router(api_router, prefix=settings.API_V1_STR)

# Mount the uploads directory so files can be served via: http://<domain>/uploads/...
# 정적 파일에 CORS 헤더 추가
class CustomStaticFiles(StaticFiles):
    async def __call__(self, scope, receive, send):
        async def custom_send(message):
            if message["type"] == "http.response.start":
                message.setdefault("headers", [])
                message["headers"].append((b"Access-Control-Allow-Origin", b"*"))
                message["headers"].append((b"Access-Control-Allow-Methods", b"*"))
                message["headers"].append((b"Access-Control-Allow-Headers", b"*"))
                message["headers"].append((b"Access-Control-Expose-Headers", b"*"))
            await send(message)
        
        await super().__call__(scope, receive, custom_send)

app.mount("/uploads", CustomStaticFiles(directory="uploads"), name="uploads")

@app.get("/")
async def root():
    logger.info("Root endpoint accessed")
    return {"message": "Welcome to Adimsayer API"}

if __name__ == "__main__":
    import uvicorn
    logger.info("Starting Adimsayer API server")
    uvicorn.run(app, host="0.0.0.0", port=8000)
