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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Analytics Dashboard API Endpoints
Provides aggregated metrics and KPIs for the analytics dashboard
"""

from datetime import datetime, timedelta
import logging
from typing import Any, Dict, List, Optional
from fastapi import Query, HTTPException
from pydantic import BaseModel, Field

from core.base_routes import BaseAPIRouter
from core.database import SessionLocal
from core.workflow_analytics_engine import (
    AlertSeverity,
    MetricType,
    PerformanceMetrics,
    WorkflowAnalyticsEngine,
)

logger = logging.getLogger(__name__)

router = BaseAPIRouter(tags=["Analytics Dashboard"])

# Global analytics engine instance
_analytics_engine: Optional[WorkflowAnalyticsEngine] = None


def get_analytics_engine() -> WorkflowAnalyticsEngine:
    """Get or create analytics engine instance"""
    global _analytics_engine
    if _analytics_engine is None:
        _analytics_engine = WorkflowAnalyticsEngine()
    return _analytics_engine


# Request/Response Models
class TimeRangeParams(BaseModel):
    """Time range parameters for dashboard queries"""
    time_window: str = Field(default="24h", description="Time window: 1h, 24h, 7d, 30d")


class DashboardKPIs(BaseModel):
    """Dashboard key performance indicators"""
    total_executions: int
    successful_executions: int
    failed_executions: int
    success_rate: float
    average_duration_ms: float
    average_duration_seconds: float
    unique_workflows: int
    unique_users: int
    error_rate: float


class WorkflowPerformanceRanking(BaseModel):
    """Workflow performance for ranking table"""
    workflow_id: str
    workflow_name: str
    total_executions: int
    success_rate: float
    average_duration_ms: float
    last_execution: Optional[datetime]
    trend: str  # "up", "down", "stable"


class ExecutionTimelineData(BaseModel):
    """Execution data for timeline chart"""
    timestamp: datetime
    count: int
    success_count: int
    failure_count: int
    average_duration_ms: float


class AlertConfiguration(BaseModel):
    """Alert configuration"""
    alert_id: str
    name: str
    description: str
    severity: str
    metric_name: str
    condition: str
    threshold_value: float
    workflow_id: Optional[str]
    enabled: bool


class RealtimeExecutionEvent(BaseModel):
    """Real-time execution event for feed"""
    event_id: str
    workflow_id: str
    workflow_name: str
    execution_id: str
    event_type: str
    timestamp: datetime
    status: Optional[str]
    duration_ms: Optional[int]
    user_id: str


# API Endpoints

@router.get("/api/analytics/dashboard/kpis", response_model=DashboardKPIs)
async def get_dashboard_kpis(
    time_window: str = Query(default="24h", description="Time window: 1h, 24h, 7d, 30d"),
    user_id: Optional[str] = Query(default=None, description="Filter by user ID")
):
    """
    Get key performance indicators for the dashboard

    Returns aggregated metrics including:
    - Total executions
    - Success/failure rates
    - Average execution duration
    - Unique workflows and users
    - Error rate
    """
    try:
        analytics = get_analytics_engine()

        # Get performance metrics
        metrics = analytics.get_performance_metrics(
            workflow_id="*",  # All workflows
            time_window=time_window
        )

        if not metrics:
            return DashboardKPIs(
                total_executions=0,
                successful_executions=0,
                failed_executions=0,
                success_rate=0.0,
                average_duration_ms=0.0,
                average_duration_seconds=0.0,
                unique_workflows=0,
                unique_users=0,
                error_rate=0.0
            )

        # Calculate KPIs
        total_executions = metrics.total_executions
        successful_executions = metrics.successful_executions
        failed_executions = metrics.failed_executions
        success_rate = (successful_executions / total_executions * 100) if total_executions > 0 else 0.0
        error_rate = metrics.error_rate

        return DashboardKPIs(
            total_executions=total_executions,
            successful_executions=successful_executions,
            failed_executions=failed_executions,
            success_rate=round(success_rate, 2),
            average_duration_ms=round(metrics.average_duration_ms, 2),
            average_duration_seconds=round(metrics.average_duration_ms / 1000, 2),
            unique_workflows=analytics.get_unique_workflow_count(time_window),
            unique_users=metrics.unique_users,
            error_rate=round(error_rate, 2)
        )

    except Exception as e:
        logger.error(f"Error getting dashboard KPIs: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/dashboard/workflows/top-performing", response_model=List[WorkflowPerformanceRanking])
async def get_top_workflows(
    limit: int = Query(default=10, ge=1, le=100),
    time_window: str = Query(default="24h", description="Time window: 1h, 24h, 7d, 30d"),
    sort_by: str = Query(default="success_rate", description="Sort by: success_rate, executions, duration")
):
    """
    Get top-performing workflows ranked by performance metrics

    Returns workflows sorted by:
    - success_rate (default): Highest success rate first
    - executions: Most executions first
    - duration: Fastest average duration first
    """
    try:
        analytics = get_analytics_engine()

        # Get all workflow IDs
        workflow_ids = analytics.get_all_workflow_ids(time_window)

        rankings = []
        for workflow_id in workflow_ids:
            metrics = analytics.get_performance_metrics(
                workflow_id=workflow_id,
                time_window=time_window
            )

            if not metrics:
                continue

            # Calculate trend (simplified)
            recent_metrics = analytics.get_performance_metrics(
                workflow_id=workflow_id,
                time_window="1h"
            )
            trend = "stable"
            if recent_metrics and recent_metrics.total_executions > 0:
                if recent_metrics.success_rate > metrics.success_rate + 5:
                    trend = "up"
                elif recent_metrics.success_rate < metrics.success_rate - 5:
                    trend = "down"

            rankings.append(WorkflowPerformanceRanking(
                workflow_id=workflow_id,
                workflow_name=analytics.get_workflow_name(workflow_id) or workflow_id,
                total_executions=metrics.total_executions,
                success_rate=round(metrics.success_rate, 2),
                average_duration_ms=round(metrics.average_duration_ms, 2),
                last_execution=analytics.get_last_execution_time(workflow_id),
                trend=trend
            ))

        # Sort rankings
        if sort_by == "success_rate":
            rankings.sort(key=lambda x: x.success_rate, reverse=True)
        elif sort_by == "executions":
            rankings.sort(key=lambda x: x.total_executions, reverse=True)
        elif sort_by == "duration":
            rankings.sort(key=lambda x: x.average_duration_ms)

        return rankings[:limit]

    except Exception as e:
        logger.error(f"Error getting top workflows: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/dashboard/timeline", response_model=List[ExecutionTimelineData])
async def get_execution_timeline(
    time_window: str = Query(default="24h", description="Time window: 1h, 24h, 7d, 30d"),
    interval: str = Query(default="1h", description="Interval: 5m, 15m, 1h, 1d"),
    workflow_id: Optional[str] = Query(default=None, description="Filter by workflow ID")
):
    """
    Get execution timeline data for charts

    Returns time-series data grouped by interval:
    - Execution count
    - Success/failure counts
    - Average duration
    """
    try:
        analytics = get_analytics_engine()

        # Parse time window
        time_delta_map = {
            "1h": timedelta(hours=1),
            "24h": timedelta(hours=24),
            "7d": timedelta(days=7),
            "30d": timedelta(days=30)
        }
        time_delta = time_delta_map.get(time_window, timedelta(hours=24))

        # Parse interval
        interval_delta_map = {
            "5m": timedelta(minutes=5),
            "15m": timedelta(minutes=15),
            "1h": timedelta(hours=1),
            "1d": timedelta(days=1)
        }
        interval_delta = interval_delta_map.get(interval, timedelta(hours=1))

        # Get timeline data
        timeline_data = analytics.get_execution_timeline(
            workflow_id=workflow_id or "*",
            time_window=time_window,
            interval=interval
        )

        return timeline_data

    except Exception as e:
        logger.error(f"Error getting execution timeline: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/dashboard/errors/breakdown")
async def get_error_breakdown(
    time_window: str = Query(default="24h", description="Time window: 1h, 24h, 7d, 30d"),
    workflow_id: Optional[str] = Query(default=None, description="Filter by workflow ID")
):
    """
    Get error breakdown by type and workflow

    Returns:
    - Error types with counts
    - Workflows with most errors
    - Recent error messages
    """
    try:
        analytics = get_analytics_engine()

        breakdown = analytics.get_error_breakdown(
            workflow_id=workflow_id or "*",
            time_window=time_window
        )

        return breakdown

    except Exception as e:
        logger.error(f"Error getting error breakdown: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/alerts", response_model=List[AlertConfiguration])
async def get_alerts(
    workflow_id: Optional[str] = Query(default=None, description="Filter by workflow ID"),
    enabled_only: bool = Query(default=False, description="Only return enabled alerts")
):
    """
    Get all configured alerts

    Returns alert configurations with:
    - Alert ID and name
    - Severity and condition
    - Associated workflow/metric
    - Enabled status
    """
    try:
        analytics = get_analytics_engine()

        alerts = analytics.get_all_alerts(
            workflow_id=workflow_id,
            enabled_only=enabled_only
        )

        return [
            AlertConfiguration(
                alert_id=alert.alert_id,
                name=alert.name,
                description=alert.description,
                severity=alert.severity.value,
                metric_name=alert.metric_name,
                condition=alert.condition,
                threshold_value=float(alert.threshold_value) if alert.threshold_value else 0.0,
                workflow_id=alert.workflow_id,
                enabled=alert.enabled
            )
            for alert in alerts
        ]

    except Exception as e:
        logger.error(f"Error getting alerts: {e}")
        raise router.internal_error(message=str(e))


@router.post("/api/analytics/alerts")
async def create_alert(alert: AlertConfiguration):
    """
    Create a new analytics alert

    Alert conditions are evaluated as Python expressions.
    Example: "error_rate > 5" or "avg_duration_ms > 10000"
    """
    try:
        analytics = get_analytics_engine()

        from core.workflow_analytics_engine import Alert

        new_alert = Alert(
            alert_id=alert.alert_id,
            name=alert.name,
            description=alert.description,
            severity=AlertSeverity(alert.severity),
            condition=alert.condition,
            threshold_value=alert.threshold_value,
            metric_name=alert.metric_name,
            workflow_id=alert.workflow_id,
            enabled=alert.enabled,
            created_at=datetime.now(),
            notification_channels=[]
        )

        analytics.create_alert(new_alert)

        return router.success_response(
            data={"alert_id": alert.alert_id},
            message="Alert created successfully"
        )

    except Exception as e:
        logger.error(f"Error creating alert: {e}")
        raise router.internal_error(message=str(e))


@router.put("/api/analytics/alerts/{alert_id}")
async def update_alert(
    alert_id: str,
    enabled: Optional[bool] = None,
    threshold_value: Optional[float] = None
):
    """
    Update an existing alert

    Can update:
    - Enabled status
    - Threshold value
    """
    try:
        analytics = get_analytics_engine()

        analytics.update_alert(
            alert_id=alert_id,
            enabled=enabled,
            threshold_value=threshold_value
        )

        return router.success_response(message="Alert updated successfully")

    except Exception as e:
        logger.error(f"Error updating alert: {e}")
        raise router.internal_error(message=str(e))


@router.delete("/api/analytics/alerts/{alert_id}")
async def delete_alert(alert_id: str):
    """Delete an alert configuration"""
    try:
        analytics = get_analytics_engine()
        analytics.delete_alert(alert_id)
        return router.success_response(message="Alert deleted successfully")

    except Exception as e:
        logger.error(f"Error deleting alert: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/dashboard/realtime-feed", response_model=List[RealtimeExecutionEvent])
async def get_realtime_execution_feed(
    limit: int = Query(default=50, ge=1),
    workflow_id: Optional[str] = Query(default=None, description="Filter by workflow ID")
):
    """
    Get real-time execution feed

    Returns recent execution events:
    - Workflow started/completed/failed events
    - Step execution events
    - Error events
    """
    try:
        analytics = get_analytics_engine()

        # Cap limit at 500
        actual_limit = min(limit, 500)

        events = analytics.get_recent_events(
            limit=actual_limit,
            workflow_id=workflow_id
        )

        return [
            RealtimeExecutionEvent(
                event_id=event.event_id,
                workflow_id=event.workflow_id,
                workflow_name=analytics.get_workflow_name(event.workflow_id) or event.workflow_id,
                execution_id=event.execution_id,
                event_type=event.event_type,
                timestamp=event.timestamp,
                status=event.status,
                duration_ms=event.duration_ms,
                user_id=event.user_id
            )
            for event in events
        ]

    except Exception as e:
        logger.error(f"Error getting real-time feed: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/dashboard/metrics/summary")
async def get_metrics_summary(
    time_window: str = Query(default="24h", description="Time window: 1h, 24h, 7d, 30d")
):
    """
    Get comprehensive metrics summary for dashboard

    Returns aggregated data for:
    - KPI cards
    - Performance chart
    - Error breakdown
    - Top workflows
    """
    try:
        analytics = get_analytics_engine()

        # Get KPIs
        kpis = await get_dashboard_kpis(time_window=time_window)

        # Get top workflows
        top_workflows = await get_top_workflows(limit=10, time_window=time_window)

        # Get error breakdown
        error_breakdown = await get_error_breakdown(time_window=time_window)

        # Get timeline data
        timeline = await get_execution_timeline(time_window=time_window)

        # Handle timeline data - can be list of dicts or Pydantic models
        if timeline and isinstance(timeline, list) and len(timeline) > 0:
            if hasattr(timeline[0], 'model_dump'):
                timeline_data = [t.model_dump() for t in timeline]
            else:
                timeline_data = timeline
        else:
            timeline_data = []

        return router.success_response(
            data={
                "kpis": kpis.model_dump(),
                "top_workflows": [w.model_dump() for w in top_workflows],
                "error_breakdown": error_breakdown,
                "timeline": timeline_data
            },
            message="Metrics summary retrieved successfully"
        )

    except Exception as e:
        logger.error(f"Error getting metrics summary: {e}")
        raise router.internal_error(message=str(e))


@router.get("/api/analytics/dashboard/workflow/{workflow_id}/performance")
async def get_workflow_performance_detail(
    workflow_id: str,
    time_window: str = Query(default="24h", description="Time window: 1h, 24h, 7d, 30d")
):
    """
    Get detailed performance metrics for a specific workflow

    Returns:
    - Execution metrics
    - Step-by-step breakdown
    - Error analysis
    - Performance trends
    """
    try:
        analytics = get_analytics_engine()

        metrics = analytics.get_performance_metrics(
            workflow_id=workflow_id,
            time_window=time_window
        )

        if not metrics:
            raise router.not_found_error("Workflow", workflow_id)

        return router.success_response(
            data={
                "workflow_id": workflow_id,
                "workflow_name": analytics.get_workflow_name(workflow_id),
                "metrics": {
                    "total_executions": metrics.total_executions,
                    "successful_executions": metrics.successful_executions,
                    "failed_executions": metrics.failed_executions,
                    "success_rate": round(metrics.success_rate, 2),
                    "average_duration_ms": round(metrics.average_duration_ms, 2),
                    "median_duration_ms": round(metrics.median_duration_ms, 2),
                    "p95_duration_ms": round(metrics.p95_duration_ms, 2),
                    "p99_duration_ms": round(metrics.p99_duration_ms, 2),
                    "error_rate": round(metrics.error_rate, 2)
                },
                "step_performance": metrics.average_step_duration,
                "common_errors": metrics.most_common_errors,
                "user_metrics": {
                    "unique_users": metrics.unique_users,
                    "executions_by_user": metrics.executions_by_user
                }
            },
            message="Workflow performance retrieved successfully"
        )

    except HTTPException:
        # Re-raise HTTP exceptions (like 404) as-is
        raise
    except Exception as e:
        logger.error(f"Error getting workflow performance detail: {e}")
        raise router.internal_error(message=str(e))