"""
Dashboard API Routes

Provides endpoints for dashboard metrics and visualizations.
Uses DashboardMetricsProvider abstraction for future centralization.
"""

from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any, Optional
import logging

from app.auth import get_current_user
from app.database import SessionDep
from app.models import User
from app.services.dashboard_metrics import get_metrics_provider

logger = logging.getLogger(__name__)

router = APIRouter(tags=["dashboard"])


@router.get("/dashboard/metrics")
async def get_dashboard_metrics(
    session: SessionDep,
    user: User = Depends(get_current_user),
    time_range: Optional[str] = None
) -> Dict[str, Any]:
    """
    Get aggregated dashboard metrics for the current user.
    
    Query Parameters:
        time_range: Optional time range filter (e.g., '24h', '7d', '30d')
    
    Returns:
        Aggregated metrics including:
        - Total scans and recent activity
        - Findings breakdown by severity
        - Average risk score
        - Per-analyzer statistics
        - Recent scan history
        - Risk distribution
    
    Architecture Note:
        Uses DashboardMetricsProvider abstraction layer.
        Current: Queries local SQLite database
        Future: Can switch to centralized metrics API without changing this endpoint
    """
    try:
        # Get appropriate metrics provider (local or remote)
        provider = get_metrics_provider(session)
        
        # Fetch metrics
        metrics = await provider.get_metrics(user.id, time_range)
        
        return {
            "success": True,
            "data": metrics,
            "message": "Dashboard metrics retrieved successfully"
        }
        
    except Exception as e:
        logger.error(f"Failed to get dashboard metrics: {e}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail=f"Failed to retrieve dashboard metrics: {str(e)}"
        )
