File size: 21,111 Bytes
690700c
bcbf1db
690700c
 
 
bcbf1db
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
 
 
 
 
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
622abd8
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
690700c
 
 
 
bcbf1db
 
 
690700c
 
 
bcbf1db
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
690700c
 
bcbf1db
 
690700c
 
 
 
 
 
 
 
bcbf1db
690700c
bcbf1db
690700c
bcbf1db
690700c
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
690700c
bcbf1db
 
 
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcbf1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
"""
FastAPI Main Application Entry Point (UPDATED)

Banking RAG Chatbot API with JWT Authentication

CHANGES:
- Replaced old chat router with new conversation_routes
- Added conversation management features
"""

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager

from app.config import settings
from app.db.mongodb import connect_to_mongo, close_mongo_connection

# ============================================================================
# LIFESPAN MANAGER (Startup & Shutdown)
# ============================================================================

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Manage application lifespan events.
    
    Startup:
    - Connect to MongoDB Atlas
    - Create indexes for conversations
    - ML models load lazily on first use
    
    Shutdown:
    - Close MongoDB connection
    - Cleanup resources
    """
    # ========================================================================
    # STARTUP
    # ========================================================================
    print("\n" + "=" * 80)
    print("πŸš€ STARTING BANKING RAG CHATBOT API")
    print("=" * 80)
    print(f"Environment: {settings.ENVIRONMENT}")
    print(f"Debug Mode: {settings.DEBUG}")
    print("=" * 80)
    
    # Connect to MongoDB
    await connect_to_mongo()
    
    # Create indexes for conversations (async)
    try:
        from app.db.repositories.conversation_repository import conversation_repository
        await conversation_repository.create_indexes()
    except Exception as e:
        print(f"⚠️ Failed to create conversation indexes: {e}")
    
    print("\nπŸ’‘ ML Models Info:")
    print("   Policy Network: Loads on first chat request (lazy loading)")
    print("   Retriever Model: Loads on first retrieval (lazy loading)")
    print("   LLM: Groq (ChatGroq) with HuggingFace fallback")
    print("\nπŸ€– LLM Configuration:")
    print(f"   Chat Model: {settings.GROQ_CHAT_MODEL} (Llama 3 8B)")
    print(f"   Eval Model: {settings.GROQ_EVAL_MODEL} (Llama 3 70B)")
    print(f"   Groq API Keys: {len(settings.get_groq_api_keys())} configured")
    print(f"   HuggingFace Tokens: {len(settings.get_hf_tokens())} configured")
    print(f"   Fallback: Groq β†’ HuggingFace")
    
    print("\nβœ… Backend startup complete!")
    print("=" * 80)
    print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
    print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
    print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
    print("=" * 80 + "\n")
    
    yield  # Application runs here
    
    # ========================================================================
    # SHUTDOWN
    # ========================================================================
    print("\n" + "=" * 80)
    print("πŸ›‘ SHUTTING DOWN API")
    print("=" * 80)
    
    # Close MongoDB connection
    await close_mongo_connection()
    
    print("βœ… Shutdown complete")
    print("=" * 80 + "\n")

# ============================================================================
# CREATE FASTAPI APPLICATION
# ============================================================================

app = FastAPI(
    title="Banking RAG Chatbot API",
    description="""
πŸ€– AI-powered Banking Assistant with:

**Features:**
- πŸ” JWT Authentication (Sign up, Login, Protected routes)
- πŸ’¬ RAG (Retrieval-Augmented Generation)
- 🧠 RL-based Policy Network (BERT)
- πŸ” Custom E5 Retriever
- ⚑ Groq LLM with HuggingFace Fallback (Llama 3 models)
- πŸ“ Conversation Management (List, Search, Archive, Delete)

**Capabilities:**
- Intelligent document retrieval
- Context-aware responses
- Conversation persistence & history
- Auto-generated conversation titles
- Real-time chat with RAG pipeline
- User authentication & authorization
- Multi-provider LLM with automatic fallback
    """,
    version="2.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# ============================================================================
# CORS MIDDLEWARE
# ============================================================================

allowed_origins = settings.get_allowed_origins()
print("\n🌐 CORS Configuration:")
print(f"   Allowed Origins: {allowed_origins}")

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ============================================================================
# INCLUDE API ROUTERS (UPDATED)
# ============================================================================

from app.api.v1 import auth
from app.api.v1 import conversation_routes  # βœ… NEW IMPORT

# Auth router (public endpoints - register, login)
app.include_router(
    auth.router,
    prefix="/api/v1/auth",
    tags=["πŸ” Authentication"]
)

# Conversation & Chat router (protected endpoints - requires JWT token)
app.include_router(
    conversation_routes.router,  # βœ… NEW ROUTER
    prefix="/api/v1/chat",
    tags=["πŸ’¬ Chat & Conversations"]
)

# ============================================================================
# ROOT ENDPOINTS
# ============================================================================

@app.get("/", tags=["πŸ“ Root"])
async def root():
    """
    Root endpoint - API information and available endpoints
    """
    return {
        "message": "Banking RAG Chatbot API with Authentication & Conversation Management",
        "version": "2.0.0",
        "status": "online",
        "authentication": "JWT Bearer Token Required for chat endpoints",
        "llm_provider": "Groq (ChatGroq) with HuggingFace fallback",
        "models": {
            "chat": settings.GROQ_CHAT_MODEL,
            "evaluation": settings.GROQ_EVAL_MODEL
        },
        "documentation": {
            "swagger_ui": "/docs",
            "redoc": "/redoc"
        },
        "endpoints": {
            "auth": {
                "register": "POST /api/v1/auth/register",
                "login": "POST /api/v1/auth/login",
                "me": "GET /api/v1/auth/me (requires token)",
                "logout": "POST /api/v1/auth/logout (requires token)"
            },
            "chat": {
                "send_message": "POST /api/v1/chat/ (requires token)",
                "create_conversation": "POST /api/v1/chat/conversation (requires token)",
                "list_conversations": "GET /api/v1/chat/conversations (requires token)",
                "get_conversation": "GET /api/v1/chat/conversation/{id} (requires token)",
                "update_conversation": "PATCH /api/v1/chat/conversation/{id} (requires token)",
                "delete_conversation": "DELETE /api/v1/chat/conversation/{id} (requires token)",
                "search_conversations": "GET /api/v1/chat/conversations/search (requires token)",
                "conversation_stats": "GET /api/v1/chat/conversations/stats (requires token)"
            },
            "health": "GET /health"
        }
    }

@app.get("/health", tags=["πŸ₯ Health"])
async def health_check():
    """
    Comprehensive health check endpoint
    
    Checks status of:
    - API service
    - MongoDB connection
    - ML models (lazy loaded)
    - Authentication system
    - LLM providers (Groq & HuggingFace)
    
    Returns:
        dict: Health status of all components
    """
    from app.db.mongodb import get_database
    
    # Check MongoDB
    mongodb_status = "connected" if get_database() is not None else "disconnected"
    
    # Check ML models (don't load them, just check readiness)
    ml_models_status = {
        "policy_network": "ready (lazy load)",
        "retriever": "ready (lazy load)",
        "llm": "ready (API-based)"
    }
    
    # Check LLM providers
    llm_providers = {
        "groq": {
            "enabled": settings.is_groq_enabled(),
            "api_keys_configured": len(settings.get_groq_api_keys()),
            "chat_model": settings.GROQ_CHAT_MODEL,
            "eval_model": settings.GROQ_EVAL_MODEL
        },
        "huggingface": {
            "enabled": settings.is_hf_enabled(),
            "tokens_configured": len(settings.get_hf_tokens()),
            "chat_model": settings.HF_CHAT_MODEL,
            "eval_model": settings.HF_EVAL_MODEL
        }
    }
    
    # Check authentication
    auth_status = {
        "jwt_enabled": bool(settings.SECRET_KEY and settings.SECRET_KEY != "your-secret-key-change-in-production"),
        "algorithm": settings.ALGORITHM,
        "token_expiry_minutes": settings.ACCESS_TOKEN_EXPIRE_MINUTES
    }
    
    # Overall health
    is_healthy = (
        mongodb_status == "connected" and 
        auth_status["jwt_enabled"] and
        (llm_providers["groq"]["enabled"] or llm_providers["huggingface"]["enabled"])
    )
    
    return {
        "status": "healthy" if is_healthy else "degraded",
        "api": "online",
        "version": "2.0.0",
        "mongodb": mongodb_status,
        "authentication": auth_status,
        "llm_providers": llm_providers,
        "ml_models": ml_models_status,
        "environment": settings.ENVIRONMENT,
        "debug_mode": settings.DEBUG
    }

# ============================================================================
# GLOBAL EXCEPTION HANDLER
# ============================================================================

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """
    Global exception handler for unhandled errors
    """
    print(f"\n❌ Unhandled Exception:")
    print(f"   Path: {request.url.path}")
    print(f"   Error: {str(exc)}")
    
    if settings.DEBUG:
        import traceback
        traceback.print_exc()
    
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal Server Error",
            "detail": str(exc) if settings.DEBUG else "An unexpected error occurred",
            "path": str(request.url.path)
        }
    )

# ============================================================================
# MAIN ENTRY POINT (for direct execution)
# ============================================================================

if __name__ == "__main__":
    import uvicorn
    
    print("\nπŸš€ Starting server directly...")
    print("   Note: For production, use: uvicorn app.main:app --host 0.0.0.0 --port 8000")
    
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG  # Auto-reload only in debug mode
    )


# """
# FastAPI Main Application Entry Point

# Banking RAG Chatbot API with JWT Authentication

# This file:
# 1. Creates the FastAPI app
# 2. Configures CORS middleware
# 3. Connects to MongoDB on startup/shutdown
# 4. Includes API routers (auth + chat)
# 5. Provides health check endpoints
# """

# from fastapi import FastAPI, Request
# from fastapi.middleware.cors import CORSMiddleware
# from fastapi.responses import JSONResponse
# from contextlib import asynccontextmanager

# from app.config import settings
# from app.db.mongodb import connect_to_mongo, close_mongo_connection

# # ============================================================================
# # LIFESPAN MANAGER (Startup & Shutdown)
# # ============================================================================

# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     """
#     Manage application lifespan events.
    
#     Startup:
#     - Connect to MongoDB Atlas
#     - ML models load lazily on first use
    
#     Shutdown:
#     - Close MongoDB connection
#     - Cleanup resources
#     """
#     # ========================================================================
#     # STARTUP
#     # ========================================================================
#     print("\n" + "=" * 80)
#     print("πŸš€ STARTING BANKING RAG CHATBOT API")
#     print("=" * 80)
#     print(f"Environment: {settings.ENVIRONMENT}")
#     print(f"Debug Mode: {settings.DEBUG}")
#     print("=" * 80)
    
#     # Connect to MongoDB
#     await connect_to_mongo()
    
#     print("\nπŸ’‘ ML Models Info:")
#     print("   Policy Network: Loads on first chat request (lazy loading)")
#     print("   Retriever Model: Loads on first retrieval (lazy loading)")
#     print("   LLM: Groq (ChatGroq) with HuggingFace fallback")
#     print("\nπŸ€– LLM Configuration:")
#     print(f"   Chat Model: {settings.GROQ_CHAT_MODEL} (Llama 3 8B)")
#     print(f"   Eval Model: {settings.GROQ_EVAL_MODEL} (Llama 3 70B)")
#     print(f"   Groq API Keys: {len(settings.get_groq_api_keys())} configured")
#     print(f"   HuggingFace Tokens: {len(settings.get_hf_tokens())} configured")
#     print(f"   Fallback: Groq β†’ HuggingFace")
    
#     print("\nβœ… Backend startup complete!")
#     print("=" * 80)
#     print(f"πŸ“– API Docs: https://eeshanyaj-questrag-backend.hf.space/docs")
#     print(f"πŸ₯ Health Check: https://eeshanyaj-questrag-backend.hf.space/health")
#     print(f"🧠 Backend Link: https://eeshanyaj-questrag-backend.hf.space/")
#     # print(f"πŸ”‘ Login: POST http://localhost:8000/api/v1/auth/login")
#     print("=" * 80 + "\n")
    
#     yield  # Application runs here
    
#     # ========================================================================
#     # SHUTDOWN
#     # ========================================================================
#     print("\n" + "=" * 80)
#     print("πŸ›‘ SHUTTING DOWN API")
#     print("=" * 80)
    
#     # Close MongoDB connection
#     await close_mongo_connection()
    
#     print("βœ… Shutdown complete")
#     print("=" * 80 + "\n")

# # ============================================================================
# # CREATE FASTAPI APPLICATION
# # ============================================================================

# app = FastAPI(
#     title="Banking RAG Chatbot API",
#     description="""
# πŸ€– AI-powered Banking Assistant with:

# **Features:**
# - πŸ” JWT Authentication (Sign up, Login, Protected routes)
# - πŸ’¬ RAG (Retrieval-Augmented Generation)
# - 🧠 RL-based Policy Network (BERT)
# - πŸ” Custom E5 Retriever
# - ⚑ Groq LLM with HuggingFace Fallback (Llama 3 models)

# **Capabilities:**
# - Intelligent document retrieval
# - Context-aware responses
# - Conversation history
# - Real-time chat
# - User authentication & authorization
# - Multi-provider LLM with automatic fallback
#     """,
#     version="1.0.0",
#     docs_url="/docs",
#     redoc_url="/redoc",
#     lifespan=lifespan
# )

# # ============================================================================
# # CORS MIDDLEWARE
# # ============================================================================

# allowed_origins = settings.get_allowed_origins()
# print("\n🌐 CORS Configuration:")
# print(f"   Allowed Origins: {allowed_origins}")

# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=allowed_origins,
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )

# # ============================================================================
# # INCLUDE API ROUTERS
# # ============================================================================

# from app.api.v1 import chat, auth

# # Auth router (public endpoints - register, login)
# app.include_router(
#     auth.router,
#     prefix="/api/v1/auth",
#     tags=["πŸ” Authentication"]
# )

# # Chat router (protected endpoints - requires JWT token)
# app.include_router(
#     chat.router,
#     prefix="/api/v1/chat",
#     tags=["πŸ’¬ Chat"]
# )

# # ============================================================================
# # ROOT ENDPOINTS
# # ============================================================================

# @app.get("/", tags=["πŸ“ Root"])
# async def root():
#     """
#     Root endpoint - API information and available endpoints
#     """
#     return {
#         "message": "Banking RAG Chatbot API with Authentication",
#         "version": "1.0.0",
#         "status": "online",
#         "authentication": "JWT Bearer Token Required for chat endpoints",
#         "llm_provider": "Groq (ChatGroq) with HuggingFace fallback",
#         "models": {
#             "chat": settings.GROQ_CHAT_MODEL,
#             "evaluation": settings.GROQ_EVAL_MODEL
#         },
#         "documentation": {
#             "swagger_ui": "/docs",
#             "redoc": "/redoc"
#         },
#         "endpoints": {
#             "auth": {
#                 "register": "POST /api/v1/auth/register",
#                 "login": "POST /api/v1/auth/login",
#                 "me": "GET /api/v1/auth/me (requires token)",
#                 "logout": "POST /api/v1/auth/logout (requires token)"
#             },
#             "chat": {
#                 "send_message": "POST /api/v1/chat/ (requires token)",
#                 "get_history": "GET /api/v1/chat/history/{conversation_id} (requires token)",
#                 "list_conversations": "GET /api/v1/chat/conversations (requires token)",
#                 "delete_conversation": "DELETE /api/v1/chat/conversation/{conversation_id} (requires token)"
#             },
#             "health": "GET /health"
#         }
#     }

# @app.get("/health", tags=["πŸ₯ Health"])
# async def health_check():
#     """
#     Comprehensive health check endpoint
    
#     Checks status of:
#     - API service
#     - MongoDB connection
#     - ML models (lazy loaded)
#     - Authentication system
#     - LLM providers (Groq & HuggingFace)
    
#     Returns:
#         dict: Health status of all components
#     """
#     from app.db.mongodb import get_database
    
#     # Check MongoDB
#     mongodb_status = "connected" if get_database() is not None else "disconnected"
    
#     # Check ML models (don't load them, just check readiness)
#     ml_models_status = {
#         "policy_network": "ready (lazy load)",
#         "retriever": "ready (lazy load)",
#         "llm": "ready (API-based)"
#     }
    
#     # Check LLM providers
#     llm_providers = {
#         "groq": {
#             "enabled": settings.is_groq_enabled(),
#             "api_keys_configured": len(settings.get_groq_api_keys()),
#             "chat_model": settings.GROQ_CHAT_MODEL,
#             "eval_model": settings.GROQ_EVAL_MODEL
#         },
#         "huggingface": {
#             "enabled": settings.is_hf_enabled(),
#             "tokens_configured": len(settings.get_hf_tokens()),
#             "chat_model": settings.HF_CHAT_MODEL,
#             "eval_model": settings.HF_EVAL_MODEL
#         }
#     }
    
#     # Check authentication
#     auth_status = {
#         "jwt_enabled": bool(settings.SECRET_KEY and settings.SECRET_KEY != "your-secret-key-change-in-production"),
#         "algorithm": settings.ALGORITHM,
#         "token_expiry_minutes": settings.ACCESS_TOKEN_EXPIRE_MINUTES
#     }
    
#     # Overall health
#     is_healthy = (
#         mongodb_status == "connected" and 
#         auth_status["jwt_enabled"] and
#         (llm_providers["groq"]["enabled"] or llm_providers["huggingface"]["enabled"])
#     )
    
#     return {
#         "status": "healthy" if is_healthy else "degraded",
#         "api": "online",
#         "mongodb": mongodb_status,
#         "authentication": auth_status,
#         "llm_providers": llm_providers,
#         "ml_models": ml_models_status,
#         "environment": settings.ENVIRONMENT,
#         "debug_mode": settings.DEBUG
#     }

# # ============================================================================
# # GLOBAL EXCEPTION HANDLER
# # ============================================================================

# @app.exception_handler(Exception)
# async def global_exception_handler(request: Request, exc: Exception):
#     """
#     Global exception handler for unhandled errors
#     """
#     print(f"\n❌ Unhandled Exception:")
#     print(f"   Path: {request.url.path}")
#     print(f"   Error: {str(exc)}")
    
#     if settings.DEBUG:
#         import traceback
#         traceback.print_exc()
    
#     return JSONResponse(
#         status_code=500,
#         content={
#             "error": "Internal Server Error",
#             "detail": str(exc) if settings.DEBUG else "An unexpected error occurred",
#             "path": str(request.url.path)
#         }
#     )

# # ============================================================================
# # MAIN ENTRY POINT (for direct execution)
# # ============================================================================

# if __name__ == "__main__":
#     import uvicorn
    
#     print("\nπŸš€ Starting server directly...")
#     print("   Note: For production, use: uvicorn app.main:app --host 0.0.0.0 --port 8000")
    
#     uvicorn.run(
#         "app.main:app",
#         host="0.0.0.0",
#         port=8000,
#         reload=settings.DEBUG  # Auto-reload only in debug mode
#     )