# ============================================================================ # 🚀 AI TEST CASE GENERATOR API # FastAPI + Groq + PM Tool Integration # MVC Architecture Implementation # ============================================================================ import os import traceback from contextlib import asynccontextmanager from datetime import datetime from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse from fastapi.middleware.cors import CORSMiddleware # Third-party imports try: from groq import Groq import pandas as pd from openpyxl import Workbook from openpyxl.styles import Font, PatternFill, Alignment except ImportError as e: print(f"⚠️ Missing dependency: {e}") print("Run: pip install groq pandas openpyxl aiohttp python-jose[cryptography]") exit(1) from app.config import Config from app.models.schemas import ErrorResponse from app.views.routes import router from app.utils.logger import logger from app.utils.http_client import http_client # ============================================================================ # FASTAPI APP INITIALIZATION # ============================================================================ @asynccontextmanager async def lifespan(app: FastAPI): """Startup and shutdown events""" # Startup logger.info("🚀 Starting AI Test Case Generator API...") await http_client.start() # Validate Groq API key if not Config.GROQ_API_KEY: logger.error("❌ GROQ_API_KEY not set! Set it via environment variable.") else: logger.info("✅ Groq API key configured") yield # Shutdown logger.info("🛑 Shutting down API...") await http_client.close() app = FastAPI( title=Config.API_TITLE, version=Config.API_VERSION, description=Config.API_DESCRIPTION, lifespan=lifespan ) # CORS Middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure appropriately for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include API routes app.include_router(router) # ============================================================================ # EXCEPTION HANDLERS # ============================================================================ @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): return JSONResponse( status_code=exc.status_code, content=ErrorResponse( error=exc.detail, message=str(exc), timestamp=datetime.now().isoformat() ).dict() ) @app.exception_handler(Exception) async def general_exception_handler(request, exc): logger.error(f"Unhandled exception: {exc}\n{traceback.format_exc()}") return JSONResponse( status_code=500, content=ErrorResponse( error="Internal Server Error", message=str(exc), details={"traceback": traceback.format_exc()}, timestamp=datetime.now().isoformat() ).dict() ) # ============================================================================ # MAIN ENTRY POINT # ============================================================================ if __name__ == "__main__": import uvicorn # Configuration HOST = os.getenv("HOST", "0.0.0.0") PORT = int(os.getenv("PORT", 8000)) WORKERS = int(os.getenv("WORKERS", 1)) logger.info(f""" ╔══════════════════════════════════════════════════════════════╗ ║ 🚀 AI TEST CASE GENERATOR API ║ ║ Version: {Config.API_VERSION} ║ ║ Starting on http://{HOST}:{PORT} ║ ║ Docs: http://{HOST}:{PORT}/docs ║ ╚══════════════════════════════════════════════════════════════╝ """) uvicorn.run( "main:app", host=HOST, port=PORT, workers=WORKERS, log_level=Config.LOG_LEVEL.lower(), access_log=True )