import os from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.core.config import settings from app.core.database import engine, Base, SessionLocal from app.core.auth import get_password_hash from app.models.models import User, AIEndpoint from app.api import auth, admin, chat # Create database tables def init_db(): Base.metadata.create_all(bind=engine) # Create default admin user and default AI endpoint def create_defaults(): db = SessionLocal() try: # Check if admin exists admin = db.query(User).filter(User.email == settings.DEFAULT_ADMIN_EMAIL).first() if not admin: admin = User( email=settings.DEFAULT_ADMIN_EMAIL, username="admin", hashed_password=get_password_hash(settings.DEFAULT_ADMIN_PASSWORD), role="admin", is_active=True ) db.add(admin) print(f"Created default admin user: {settings.DEFAULT_ADMIN_EMAIL}") # Check if default endpoint exists default_endpoint = db.query(AIEndpoint).filter(AIEndpoint.is_default == True).first() if not default_endpoint: # Create a default Ollama endpoint default_endpoint = AIEndpoint( name="Default Ollama", endpoint_type="ollama", base_url="http://localhost:11434", model_name="llama2", is_active=True, is_default=True ) db.add(default_endpoint) print("Created default Ollama endpoint") db.commit() finally: db.close() @asynccontextmanager async def lifespan(app: FastAPI): # Startup init_db() create_defaults() # Ensure upload directory exists os.makedirs(settings.UPLOAD_DIR, exist_ok=True) yield # Shutdown (if needed) pass app = FastAPI( title="Moxiegen API", description="Backend API for Moxiegen application", version="1.0.0", lifespan=lifespan ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure this properly in production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include routers app.include_router(auth.router, prefix="/api") app.include_router(admin.router, prefix="/api") app.include_router(chat.router, prefix="/api") @app.get("/") def root(): return {"message": "Welcome to Moxiegen API", "version": "1.0.0"} @app.get("/health") def health_check(): return {"status": "healthy"}