import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from db import MongoDB
from config import get_settings
from routers import entries, users
from routers import notifications
from scheduler import start_scheduler
from contextlib import asynccontextmanager

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    force=True,
)
logging.getLogger("scheduler").setLevel(logging.DEBUG)

settings = get_settings()
_scheduler = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    MongoDB.connect_db()
    global _scheduler
    _scheduler = start_scheduler()
    yield
    # Shutdown
    if _scheduler:
        _scheduler.shutdown(wait=False)
    MongoDB.close_db()

app = FastAPI(
    title="Grateful Journal API",
    description="Backend API for Grateful Journal - private journaling app",
    version="0.1.0",
    lifespan=lifespan
)

# CORS middleware (MUST be before routes)
cors_origins = [settings.frontend_url]
if settings.environment == "development":
    cors_origins.extend([
        "http://localhost:8000",
        "http://127.0.0.1:8000",
        "http://localhost:5173",
    ])

app.add_middleware(
    CORSMiddleware,
    allow_origins=cors_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# Include routers
app.include_router(users.router, prefix="/api/users", tags=["users"])
app.include_router(entries.router, prefix="/api/entries", tags=["entries"])
app.include_router(notifications.router, prefix="/api/notifications", tags=["notifications"])


@app.get("/health")
async def health_check():
    return {
        "status": "ok",
        "environment": settings.environment,
        "api_version": "0.1.0"
    }


@app.get("/")
async def root():
    return {
        "message": "Grateful Journal API",
        "version": "0.1.0",
        "docs": "/docs"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=settings.api_port,
        reload=settings.environment == "development"
    )
