Spaces:
Paused

File size: 13,890 Bytes
357bfdf
 
 
 
 
8eb630b
357bfdf
 
 
 
 
579285c
357bfdf
 
383d839
 
 
 
 
 
16a78e2
383d839
 
 
 
357bfdf
 
 
ff28ba2
357bfdf
 
 
 
ff28ba2
357bfdf
 
 
 
579285c
357bfdf
383d839
357bfdf
 
091ca1d
357bfdf
 
383d839
357bfdf
 
383d839
357bfdf
 
 
 
383d839
357bfdf
 
 
 
 
 
383d839
357bfdf
 
 
 
 
383d839
 
 
 
 
 
357bfdf
383d839
 
357bfdf
 
383d839
357bfdf
383d839
 
 
 
8eb630b
 
383d839
 
 
 
 
8eb630b
 
383d839
 
 
 
 
357bfdf
 
 
 
8eb630b
357bfdf
 
 
383d839
357bfdf
 
8eb630b
 
357bfdf
383d839
357bfdf
383d839
357bfdf
383d839
357bfdf
383d839
 
579285c
091ca1d
 
579285c
 
383d839
579285c
357bfdf
 
 
 
 
 
 
 
 
 
 
383d839
357bfdf
383d839
 
 
357bfdf
 
 
 
 
 
 
 
 
 
8eb630b
383d839
 
 
 
091ca1d
 
 
 
 
 
 
 
 
 
383d839
8eb630b
 
 
383d839
8eb630b
 
 
383d839
357bfdf
 
 
8eb630b
357bfdf
 
 
8eb630b
 
 
 
383d839
 
357bfdf
 
 
 
 
383d839
357bfdf
 
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
 
383d839
 
 
 
 
 
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
 
 
 
383d839
357bfdf
 
 
383d839
 
 
 
 
 
357bfdf
383d839
 
 
357bfdf
383d839
357bfdf
383d839
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
383d839
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
 
383d839
357bfdf
 
 
383d839
357bfdf
 
579285c
383d839
357bfdf
 
 
 
383d839
357bfdf
 
 
 
 
 
 
 
383d839
 
 
357bfdf
383d839
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
 
 
383d839
 
357bfdf
 
 
 
 
383d839
 
 
357bfdf
383d839
357bfdf
383d839
357bfdf
 
 
 
 
 
 
383d839
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
 
383d839
 
 
 
 
357bfdf
 
 
 
 
383d839
 
357bfdf
383d839
357bfdf
383d839
357bfdf
 
383d839
357bfdf
 
 
 
 
 
 
8eb630b
 
 
 
 
383d839
8eb630b
 
 
 
357bfdf
 
 
 
 
 
 
 
 
 
 
 
 
383d839
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
"""
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