import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from app.config import settings
from app.db import init_db, close_db
from app.routers import auth, profiles, photos, likes, chat

# Initialize app
app = FastAPI(
    title="Dating App API",
    description="MVP dating app with profiles, photos, and chat",
    version="1.0.0"
)

# CORS middleware
cors_origins = settings.cors_origins.split(",")
app.add_middleware(
    CORSMiddleware,
    allow_origins=cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(auth.router)
app.include_router(profiles.router)
app.include_router(photos.router)
app.include_router(likes.router)
app.include_router(chat.router)

# Serve media files
os.makedirs(settings.media_dir, exist_ok=True)
app.mount("/media", StaticFiles(directory=settings.media_dir), name="media")

# Events
@app.on_event("startup")
async def startup_event():
    """Initialize database on startup"""
    init_db()

@app.on_event("shutdown")
async def shutdown_event():
    """Close database connections on shutdown"""
    close_db()

@app.get("/health")
def health_check():
    """Health check endpoint"""
    return {"status": "ok"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8001,
        reload=True
    )
