from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, Response

from app.config import settings
from app.database import init_db
from app.api.v1 import api_router
from app.middleware.rate_limiter import RateLimitMiddleware, rate_limiter
from app.middleware.tenant_isolation import TenantIsolationMiddleware

# CORS Origins - Allow all in development
CORS_ORIGINS = ["*"]


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    await init_db()

    # بدء Scheduler لفحص التنبيهات تلقائياً كل دقيقة (في worker الأول فقط)
    import os
    if os.environ.get("WORKER_ID") == "1":
        from app.scheduler import start_scheduler
        start_scheduler(interval_seconds=60)

    yield

    # Shutdown
    if os.environ.get("WORKER_ID") == "1":
        from app.scheduler import stop_scheduler
        stop_scheduler()


app = FastAPI(
    title=settings.APP_NAME,
    description="منصة مراقبة أجهزة LifeSmart الذكية - Smart Device Monitoring Platform",
    version="1.0.0",
    docs_url="/api/docs",
    redoc_url="/api/redoc",
    openapi_url="/api/openapi.json",
    lifespan=lifespan,
)

# CORS - Allow all origins in development
app.add_middleware(
    CORSMiddleware,
    allow_origins=CORS_ORIGINS,
    allow_credentials=False,  # Must be False when allow_origins=["*"]
    allow_methods=["*"],
    allow_headers=["*"],
)

# Rate Limiting Middleware
app.add_middleware(RateLimitMiddleware, rate_limiter=rate_limiter)

# Tenant Isolation Middleware
app.add_middleware(TenantIsolationMiddleware, secret_key=settings.SECRET_KEY)


# Include API routes
app.include_router(api_router, prefix=settings.API_V1_PREFIX)


@app.get("/")
async def root():
    return {
        "name": settings.APP_NAME,
        "version": "1.0.0",
        "status": "running",
        "docs": "/api/docs"
    }


@app.get("/health")
async def health_check():
    return {"status": "healthy"}


# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    return JSONResponse(
        status_code=500,
        content={
            "detail": "Internal server error",
            "detail_ar": "خطأ في الخادم"
        }
    )
