import os import socket import webbrowser import time import uvicorn import secrets from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from threading import Thread # --- Security & Sessions --- from starlette.middleware.sessions import SessionMiddleware # āœ… FIX: Add Proxy Middleware import from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware # Import database instance from database.db_connection import db_instance # Import custom utilities try: from src.utils import start_periodic_cleanup, cleanup_artifacts_directory except ImportError as e: print(f"āŒ [STARTUP ERROR] Failed to import modules: {e}") raise # --- Import Routers from the 'api' folder --- from api.routes import router as api_router from api.auth import router as auth_router from api.ui import router as ui_router # Define lifespan for startup and shutdown events @asynccontextmanager async def lifespan(app: FastAPI): print("\n" + "="*60) print("🟢 [LIFECYCLE] Starting up application lifecycle...") try: print("🟢 [DATABASE] Attempting to connect to MongoDB...") db_instance.connect() print("āœ… [DATABASE] MongoDB connection successful.") except Exception as e: print(f"āŒ [DATABASE] Connection failed on startup: {e}") print("🟢 [BACKGROUND] Initializing periodic cleanup tasks...") start_periodic_cleanup() print("🟢 [BACKGROUND] Cleaning up legacy artifacts directory...") cleanup_artifacts_directory() print("āœ… [LIFECYCLE] Application startup complete.") print("="*60 + "\n") yield print("\n" + "="*60) print("šŸ”“ [LIFECYCLE] Shutting down application lifecycle...") print("šŸ”“ [DATABASE] Closing MongoDB database connection...") db_instance.close() print("āœ… [LIFECYCLE] Application shutdown complete.") print("="*60 + "\n") # Initialize FastAPI app app = FastAPI(title="Student Performance Analyzer", lifespan=lifespan) # Fetch the secret key (Emergency Fix: Removed hardcoded fallback) SECRET_KEY = os.environ.get("SECRET_KEY") if not SECRET_KEY: print("āš ļø [SECURITY] SECRET_KEY environment variable is missing. Using a volatile random key.") SECRET_KEY = secrets.token_hex(32) # Session middleware (Emergency Fix: https_only must be a boolean, not a string) app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, same_site="none", https_only=True) app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*") # Static files app.mount("/static", StaticFiles(directory="static"), name="static") # Routers print("🟢 [ROUTING] Mounting application routers (auth, ui, api)...") app.include_router(auth_router) app.include_router(ui_router) app.include_router(api_router) @app.get('/health') async def health(): return {"status": "healthy"} def find_free_port(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('', 0)) s.listen(1) port = s.getsockname()[1] return port def is_port_available(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(('', port)) return True except socket.error: return False if __name__ == "__main__": port = 8000 if not is_port_available(port): port = find_free_port() print("=" * 60) print(f"āš ļø [SERVER] PORT 8000 WAS ALREADY IN USE. Using alternative port: {port}") print("=" * 60) print("=" * 60) print(f"šŸš€ [SERVER] Student Performance Analyzer is starting!") print(f"🌐 [SERVER] Opening browser at: http://localhost:{port}") print("=" * 60) def open_browser(): time.sleep(2) try: webbrowser.open_new(f"http://localhost:{port}") print("āœ… [BROWSER] Browser opened successfully") except Exception as e: print(f"āŒ [BROWSER] Could not open browser automatically: {e}") browser_thread = Thread(target=open_browser, daemon=True) browser_thread.start() try: print("🟢 [SERVER] Starting Uvicorn server...") uvicorn.run("application:app", host="127.0.0.1", port=port, log_level="warning", reload=True) except KeyboardInterrupt: print("\nšŸ‘‹ [SERVER] Server stopped by user (KeyboardInterrupt)") except Exception as e: print(f"\nāŒ [SERVER] Application crash: {e}")