# app/main.py
from fastapi import FastAPI, Security
from .database import Base, engine, get_db
from .routes import auth_routes, chat_routes
from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBearer
from fastapi.staticfiles import StaticFiles
import os
from fastapi.middleware.cors import CORSMiddleware

Base.metadata.create_all(bind=engine)

app = FastAPI()

# ✅ Allow frontend calls (CORS)
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://vivedev.usmsystems.com",
        "http://localhost:4200"
    ],  # You can restrict this to your frontend domain
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Absolute path to the glb_avatars directory
GLB_AVATARS_PATH = os.path.join(os.getcwd(), "app", "glb_avatars")

app.mount("/glb_avatars", StaticFiles(directory=GLB_AVATARS_PATH), name="glb_avatars")

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema

    openapi_schema = get_openapi(
        title="My API",
        version="1.0.0",
        description="API with JWT auth",
        routes=app.routes,
    )

    openapi_schema["components"]["securitySchemes"] = {
        "BearerAuth": {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT",
        }
    }

    # 🔐 Only protect specific routes like /chat-store/
    secure_paths = ["/chat-store/", "/chat/", "/user-avatar/", "/add-user-avatar/", "/user-info/", "/student-logout/", "/clone-fixed/"]

    for path in openapi_schema["paths"]:
        if path in secure_paths:
            for method in openapi_schema["paths"][path]:
                openapi_schema["paths"][path][method]["security"] = [{"BearerAuth": []}]
        else:
            for method in openapi_schema["paths"][path]:
                openapi_schema["paths"][path][method].pop("security", None)

    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

# Include routes
app.include_router(auth_routes.router)
app.include_router(chat_routes.router)
