import sys
import json
from loguru import logger
from fastapi import FastAPI 
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
 
from app.api import router

# Configure logging
logger.remove()
logger.add(
    sys.stderr,
    colorize=True,
    format="<green>{time:HH:mm:ss}</green> | <level>{message}</level>",
    level=10,
)
logger.add("based_content_advertising.log", rotation="1 MB", level="DEBUG", compression="zip")

# 
app = FastAPI(
    title="Based Content Advertising API",
    description="This is a Project for content advertising based on video processing.",
    version="0.0.1",
)

# 
origins = [
    "http://localhost:2023",
    "http://173.212.199.208:2023",
]

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

# 
app.mount("/static", StaticFiles(directory="static"), name="static")

# 
@app.on_event("startup")
def save_openapi_json():
    """
    Event handler that saves the OpenAPI documentation data to a JSON file on startup.
    """
    openapi_data = app.openapi()
    with open("openapi.json", "w") as file:
        json.dump(openapi_data, file)

# 
@app.get("/", tags=["Root"], include_in_schema=False)
async def root():
    """
    Redirects the root URL ("/") to the API documentation page.

    Returns:
        RedirectResponse: Redirects the client to the "/docs" endpoint.
    """
    logger.debug("Redirecting root URL to /docs")
    return RedirectResponse(url="/docs")

app.include_router(router)