from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.core.logging_config import setup_logging
from app.core.exceptions import register_exception_handlers
from app.api.endpoints import auth, products, orders, admin

# 1. Setup global logger formatting
setup_logging()

app = FastAPI(
    title=settings.PROJECT_NAME,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    description="Backend API for Premium Jewelry E-Commerce (Titanium & Xuping)"
)

# 2. Atur CORS Middleware
# Izinkan frontend local development (Vite port 5173) mengakses REST API
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://localhost:5173", "*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 3. Registrasi exception handlers global
register_exception_handlers(app)

# Middleware Debug untuk mencetak request URL ke log cPanel
from fastapi import Request
@app.middleware("http")
async def log_requests(request: Request, call_next):
    print(f"DEBUG PATH RECEIVED: {request.url.path}")
    response = await call_next(request)
    return response

# 4. Kumpulkan API Router endpoints
# Rute standar (dengan /api/v1)
app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["Authentication"])
app.include_router(products.router, prefix=settings.API_V1_STR, tags=["Products & Categories"])
app.include_router(orders.router, prefix=f"{settings.API_V1_STR}/orders", tags=["Orders & Transactions"])
app.include_router(admin.router, prefix=f"{settings.API_V1_STR}/admin", tags=["Admin Operations"])

# Rute alternatif (tanpa /api di depan, jika Passenger memotong path menjadi /v1/...)
app.include_router(auth.router, prefix="/v1/auth", tags=["Authentication Alt"])
app.include_router(products.router, prefix="/v1", tags=["Products & Categories Alt"])
app.include_router(orders.router, prefix="/v1/orders", tags=["Orders & Transactions Alt"])
app.include_router(admin.router, prefix="/v1/admin", tags=["Admin Operations Alt"])


@app.get("/")
def root():
    """Verify backend system status."""
    return {
        "status": "healthy",
        "app": settings.PROJECT_NAME,
        "version": "1.0.0"
    }
