File size: 4,491 Bytes
90897ab
 
 
 
 
80320be
90897ab
 
 
 
 
 
 
 
 
8218058
90897ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80320be
 
 
 
 
90897ab
80320be
 
90897ab
73f1f11
90897ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48322a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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}")