""" YAZ Care Platform - Main API Clean, maintainable API endpoints """ import uuid from fastapi import APIRouter, Depends, HTTPException, Request from fastapi.responses import JSONResponse from typing import Dict, Any, Optional from datetime import datetime from pydantic import BaseModel import structlog # Import authentication system from core.auth import auth_service, User, AuthenticationError from core.dependencies import get_current_user, CurrentUser # Login brute-force guard try: from core.security.login_protection import login_guard as _login_guard _LOGIN_GUARD_AVAILABLE = True except ImportError: _login_guard = None _LOGIN_GUARD_AVAILABLE = False # Import existing routers try: from api.analytics_router import analytics_router except ImportError: analytics_router = None try: from api.main_routes import main_router, get_dashboard_metrics except ImportError: main_router = None get_dashboard_metrics = lambda: {"patients": 0, "cases": 0} logger = structlog.get_logger(__name__) # Pydantic Models class UserLogin(BaseModel): email: str # accepts username or email password: str class UserRegister(BaseModel): firstName: str lastName: str email: str password: str role: Optional[str] = "patient" # Create main API router api_router = APIRouter(prefix="/api", tags=["API"]) # ============= AUTHENTICATION ENDPOINTS ============= @api_router.post("/auth/login", response_model=Dict[str, Any]) async def login(login_data: UserLogin, request: Request): """ Authenticate user and return session data for frontend """ client_ip = request.client.host if request.client else "unknown" # Brute-force protection — check BEFORE touching credentials if _LOGIN_GUARD_AVAILABLE and _login_guard: await _login_guard.check_or_raise(ip=client_ip, username=login_data.email) try: # Get client info (already extracted above) # Authenticate user user = auth_service.authenticate_user(login_data.email, login_data.password) if not user: if _LOGIN_GUARD_AVAILABLE and _login_guard: await _login_guard.record_failure(ip=client_ip, username=login_data.email) raise HTTPException(status_code=401, detail="Invalid email or password") # Create tokens using the create_tokens method which takes a User object token_response = auth_service.create_tokens(user) # Clear failure counter on success if _LOGIN_GUARD_AVAILABLE and _login_guard: await _login_guard.record_success(ip=client_ip, username=login_data.email) # Generate a simple session ID (UUID) session_id = str(uuid.uuid4()) logger.info( "User logged in successfully", extra={"user_id": str(user.id), "sensitive": True} ) return { "success": True, "message": "Login successful", "user": { "id": str(user.id), "email": user.email, "username": user.username, "full_name": user.full_name, "role": user.role.value if hasattr(user.role, "value") else str(user.role), }, "tokens": { "access_token": token_response.access_token, "refresh_token": token_response.refresh_token, "token_type": "bearer", "expires_in": token_response.expires_in, }, "session_id": session_id, } except AuthenticationError as e: if _LOGIN_GUARD_AVAILABLE and _login_guard: await _login_guard.record_failure(ip=client_ip, username=login_data.email) raise HTTPException(status_code=401, detail=str(e)) from e except HTTPException: raise except Exception as exc: # Never expose internal exception details to clients (security: hide stack trace) logger.error("Login error (details redacted for security)") raise HTTPException(status_code=500, detail="Authentication service unavailable") from None @api_router.post("/auth/logout") async def logout(current_user: User = Depends(get_current_user)): """ Logout user and invalidate session """ try: # In a real implementation, you'd get session_id from token # For now, we'll use a placeholder session_id = "current_session" success = auth_service.end_session(session_id) return {"success": success, "message": "Logged out successfully"} except Exception as e: logger.error("Logout error: %s", str(e)) raise HTTPException(status_code=500, detail="Internal server error") @api_router.get("/auth/me") async def get_current_user_info(current_user: User = Depends(get_current_user)): """ Get current authenticated user information for frontend """ # Handle role - might be enum or string role_value = ( current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role) ) # Derive permissions from role _role_perms = { "admin": ["*"], "surgeon": ["read", "write", "delete", "sign"], "physician": ["read", "write", "sign"], "nurse": ["read", "write"], "manager": ["read", "write"], "viewer": ["read"], } permissions = _role_perms.get(role_value, ["read", "write"]) # Handle last_login - might be datetime, string, or None last_login_value = None if current_user.last_login: if hasattr(current_user.last_login, "isoformat"): last_login_value = current_user.last_login.isoformat() else: last_login_value = str(current_user.last_login) return { "success": True, "user": { "id": str(current_user.id), "email": current_user.email, "username": current_user.username, "full_name": current_user.full_name, "role": role_value, "permissions": permissions, "is_active": bool(current_user.is_active), "is_verified": bool(current_user.is_verified), "last_login": last_login_value, }, } # ============= DASHBOARD ENDPOINTS ============= @api_router.get("/dashboard/metrics") async def get_dashboard_data(current_user: User = Depends(get_current_user)): """ Get dashboard metrics and data for frontend dashboard """ try: # Get base metrics base_metrics = get_dashboard_metrics() if get_dashboard_metrics else {"patients": 0} # Add user-specific data dashboard_data = { "success": True, "data": { "user_info": { "name": current_user.full_name, "role": ( current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role) ), "email": current_user.email, }, "metrics": base_metrics, "recent_activities": [ { "id": 1, "type": "login", "description": "User logged in", "timestamp": datetime.now().isoformat(), } ], "notifications": [ { "id": 1, "type": "info", "title": "Welcome to YAZ Care", "message": "Your healthcare platform is ready", "timestamp": datetime.now().isoformat(), } ], "quick_actions": [ { "id": "patients", "title": "View Patients", "icon": "user", "url": "/patients", }, {"id": "analytics", "title": "Analytics", "icon": "chart", "url": "/analytics"}, {"id": "reports", "title": "Reports", "icon": "file", "url": "/reports"}, ], }, } return dashboard_data except Exception as e: logger.error("Dashboard data error: %s", str(e)) raise HTTPException(status_code=500, detail="Failed to load dashboard data") # ============= HEALTHCARE DATA ENDPOINTS ============= @api_router.get("/patients") async def get_patients( page: int = 1, limit: int = 10, search: Optional[str] = None, current_user: User = Depends(get_current_user), ): """ Get patients list with pagination and search for frontend """ try: # Mock patient data for now patients = [ { "id": f"patient_{i}", "name": f"Patient {i}", "email": f"patient{i}@example.com", "age": 25 + (i % 50), "gender": "male" if i % 2 else "female", "last_visit": datetime.now().isoformat(), "status": "active", } for i in range(1, 21) ] # Apply search filter if provided if search: patients = [p for p in patients if search.lower() in p["name"].lower()] # type: ignore[union-attr] # Apply pagination start = (page - 1) * limit end = start + limit paginated_patients = patients[start:end] return { "success": True, "data": { "patients": paginated_patients, "pagination": { "page": page, "limit": limit, "total": len(patients), "pages": (len(patients) + limit - 1) // limit, }, }, } except Exception as e: logger.error("Patients data error: %s", str(e)) raise HTTPException(status_code=500, detail="Failed to load patients data") @api_router.get("/analytics/overview") async def get_analytics_overview(current_user: User = Depends(get_current_user)): """ Get analytics overview data for frontend charts and visualizations """ try: analytics_data = { "success": True, "data": { "summary": { "total_patients": 1247, "active_cases": 89, "completed_procedures": 156, "pending_reports": 23, }, "charts": { "patient_trends": [ {"month": "Jan", "count": 120}, {"month": "Feb", "count": 135}, {"month": "Mar", "count": 142}, {"month": "Apr", "count": 158}, {"month": "May", "count": 167}, ], "procedure_types": [ {"type": "Surgery", "count": 45, "percentage": 28.8}, {"type": "Consultation", "count": 78, "percentage": 50.0}, {"type": "Follow-up", "count": 33, "percentage": 21.2}, ], }, "recent_stats": { "today_appointments": 12, "week_procedures": 34, "month_revenue": 125000, "satisfaction_score": 4.7, }, }, } return analytics_data except Exception as e: logger.error("Analytics data error: %s", str(e)) raise HTTPException(status_code=500, detail="Failed to load analytics data") # ============= SYSTEM ENDPOINTS ============= @api_router.get("/system/health") async def system_health(): """ Get system health status for frontend monitoring """ try: # Basic health checks health_data = { "success": True, "status": "healthy", "timestamp": datetime.now().isoformat(), "services": { "api": {"status": "healthy", "response_time": "15ms"}, "database": {"status": "healthy", "connections": 5}, "auth": { "status": "healthy", "active_sessions": auth_service.get_active_sessions_count(), }, "cache": {"status": "healthy", "hit_rate": "92%"}, }, "system": { "uptime": "2h 45m", "memory_usage": "65%", "cpu_usage": "23%", "disk_space": "78%", }, } return health_data except Exception as e: logger.error("Health check error: %s", str(e)) return {"success": False, "status": "error", "error": str(e)} # ============= ERROR HANDLERS ============= # Exception handlers will be added at app level, not router level # ============= INCLUDE SUB-ROUTERS ============= # Include FHIR R4 router (Healthcare interoperability) try: from api.fhir import fhir_router api_router.include_router(fhir_router) logger.info("✅ FHIR R4 API mounted at /api/v1/fhir") except ImportError as e: logger.warning("FHIR R4 API not available: %s", e) # Include existing routers if available if analytics_router: api_router.include_router(analytics_router, prefix="/analytics") # NOTE: main_router has conflicting routes with UI (e.g., "/" route) # Only include specific routes or use a prefix to avoid conflicts if main_router: # Skip the main_router to avoid route conflicts with UI # UI takes priority for the root "/" route logger.info("⚠️ Skipping main_router inclusion to avoid UI route conflicts") # Export router = api_router