import logging
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.schemas.dashboard import DashboardResponse, DashboardRefreshResponse
from app.services.dashboard_service import DashboardService

router = APIRouter(prefix="/dashboard", tags=["dashboard"])
logger = logging.getLogger(__name__)


@router.get(
    "/",
    response_model=DashboardResponse,
    summary="Get Complete Dashboard Data",
    description="Retrieve all dashboard data including KPIs, trends, analysis, and recent violations",
)
async def get_dashboard(
    db: AsyncSession = Depends(deps.get_db),
    current_user=Depends(deps.get_current_user),
):
    """
    Get complete dashboard data with real-time metrics.
    
    **Returns:**
    - KPI Summary: Active violations, monitored products, average discount
    - Violation Trend: 30-day violation trend chart data
    - Violation Analysis: Marketplace insights, vendor analysis, financial impact
    - Recent Violations: List of most recent violations
    - Last Refreshed: Timestamp of when dashboard data was last aggregated
    
    **Requires:** Authenticated user (admin level recommended)
    """
    try:
        dashboard_data = await DashboardService.get_complete_dashboard(db)
        return dashboard_data
    except Exception as e:
        logger.error(f"Error retrieving dashboard data: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve dashboard data",
        )


@router.get(
    "/kpi-summary",
    summary="Get KPI Summary Cards",
    description="Get KPI cards for active violations, monitored products, and average discount",
)
async def get_kpi_summary(
    db: AsyncSession = Depends(deps.get_db),
    current_user=Depends(deps.get_current_user),
):
    """
    Get KPI summary section of dashboard.
    
    **Returns:**
    - Active Violations: Count, detections, vendor count, product count, status
    - Monitored Products: Total monitored products
    - Average Discount: Average discount percentage across violations
    """
    try:
        kpi_summary = await DashboardService.get_kpi_summary(db)
        return kpi_summary
    except Exception as e:
        logger.error(f"Error retrieving KPI summary: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve KPI summary",
        )


@router.get(
    "/violation-trend",
    summary="Get 30-Day Violation Trend",
    description="Get violation count per day for the last 30 days",
)
async def get_violation_trend(
    db: AsyncSession = Depends(deps.get_db),
    current_user=Depends(deps.get_current_user),
):
    """
    Get 30-day violation trend chart data.
    
    **Returns:**
    - Trend Data: List of dates with violation counts
    - Period Label: Description of the time period
    
    **Hover Tooltip Data Includes:**
    - Date (YYYY-MM-DD format)
    - Violation count for that date
    """
    try:
        trend_data = await DashboardService.get_30day_violation_trend(db)
        return trend_data
    except Exception as e:
        logger.error(f"Error retrieving violation trend: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve violation trend",
        )


@router.get(
    "/violation-analysis",
    summary="Get Violation Analysis",
    description="Get analysis including top marketplaces, vendors, products, and financial impact",
)
async def get_violation_analysis(
    db: AsyncSession = Depends(deps.get_db),
    current_user=Depends(deps.get_current_user),
):
    """
    Get violation analysis section.
    
    **Returns:**
    - Marketplace with Most Violations: Top violation source
    - Most Offending Vendor: Vendor with most violations
    - Most Affected Product: Product with most violations
    - Highest Discount Detected: Greatest discount percentage found
    - Financial Impact: Total estimated impact in USD
    """
    try:
        analysis = await DashboardService.get_violation_analysis(db)
        return analysis
    except Exception as e:
        logger.error(f"Error retrieving violation analysis: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve violation analysis",
        )


@router.get(
    "/recent-violations",
    summary="Get Recent Violations",
    description="Get list of most recent violations with all details",
)
async def get_recent_violations(
    db: AsyncSession = Depends(deps.get_db),
    limit: int = 10,
    current_user=Depends(deps.get_current_user),
):
    """
    Get recent violations panel.
    
    **Query Parameters:**
    - `limit`: Number of recent violations to return (default: 10, max: 100)
    
    **Returns:**
    - Recent Violations List: Most recent violations with full details
      - Product Name
      - Marketplace badge
      - Vendor name
      - Current Price
      - Target MSP
      - Price Difference
      - Status indicator (open/notified)
    - Total Violations: Count of all active violations
    """
    if limit < 1 or limit > 100:
        limit = 10

    try:
        recent = await DashboardService.get_recent_violations(db, limit=limit)
        return recent
    except Exception as e:
        logger.error(f"Error retrieving recent violations: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve recent violations",
        )


@router.post(
    "/refresh",
    response_model=DashboardRefreshResponse,
    status_code=status.HTTP_202_ACCEPTED,
    summary="Refresh Dashboard Data",
    description="Trigger dashboard data refresh without reloading the page",
)
async def refresh_dashboard(
    db: AsyncSession = Depends(deps.get_db),
    current_user=Depends(deps.get_current_user),
):
    """
    Trigger dashboard data refresh.
    
    This endpoint allows admins to manually refresh dashboard data including:
    - Fetching latest violations
    - Recalculating KPIs
    - Updating trends and analysis
    
    **Response:**
    - message: Status message about refresh
    - is_refreshing: Whether refresh operation is in progress
    - next_refresh_estimate: Expected time for data to be available
    
    **Note:** Refresh happens asynchronously without requiring page reload.
    Client should poll the GET /dashboard endpoint for updated data.
    
    **Requires:** Authenticated user (admin level recommended)
    """
    try:
        # In a production system, this would likely trigger an async task
        # For now, we return a success response indicating immediate availability
        response = DashboardRefreshResponse(
            message="Dashboard data refresh triggered successfully",
            is_refreshing=False,
            next_refresh_estimate=None,
        )
        logger.info(f"Dashboard refresh triggered by user")
        return response
    except Exception as e:
        logger.error(f"Error triggering dashboard refresh: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to refresh dashboard data",
        )
