
    /i                        d dl Z d dlmZmZmZmZ d dlmZ d dlm	Z	 d dl
mZmZ d dlmZ  eddg	      Z e j                   e      Zej'                  d
edd       ee	j(                         ee	j*                        fdefd       Zej'                  ddd       ee	j(                         ee	j*                        fdefd       Zej'                  ddd       ee	j(                         ee	j*                        fdefd       Zej'                  ddd       ee	j(                         ee	j*                        fdefd       Zej'                  ddd       ee	j(                        d  ee	j*                        fded!efd"       Zej9                  d#eej:                  d$d%&       ee	j(                         ee	j*                        fdefd'       Zy)(    N)	APIRouterDependsHTTPExceptionstatus)AsyncSession)deps)DashboardResponseDashboardRefreshResponse)DashboardServicez
/dashboard	dashboard)prefixtags/zGet Complete Dashboard DatazSRetrieve all dashboard data including KPIs, trends, analysis, and recent violations)response_modelsummarydescriptiondbc                    K   	 t        j                  |        d{   }|S 7 # t        $ rA}t        j	                  dt        |              t        t        j                  d      d}~ww xY ww)a  
    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)
    Nz!Error retrieving dashboard data: z!Failed to retrieve dashboard datastatus_codedetail)	r   get_complete_dashboard	Exceptionloggererrorstrr   r   HTTP_500_INTERNAL_SERVER_ERROR)r   current_userdashboard_dataes       >/var/www/html/marco-python-backend/app/api/routes/dashboard.pyget_dashboardr"      sj     ,
/FFrJJ K 
8QAB==6
 	

0   A2% #% A2% 	A/<A**A//A2z/kpi-summaryzGet KPI Summary CardszMGet KPI cards for active violations, monitored products, and average discount)r   r   c                    K   	 t        j                  |        d{   }|S 7 # t        $ rA}t        j	                  dt        |              t        t        j                  d      d}~ww xY ww)a  
    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
    NzError retrieving KPI summary: zFailed to retrieve KPI summaryr   )	r   get_kpi_summaryr   r   r   r   r   r   r   )r   r   kpi_summaryr    s       r!   r%   r%   .   sj     "
,<<R@@ A 
5c!fX>?==3
 	

r#   z/violation-trendzGet 30-Day Violation Trendz0Get violation count per day for the last 30 daysc                    K   	 t        j                  |        d{   }|S 7 # t        $ rA}t        j	                  dt        |              t        t        j                  d      d}~ww xY ww)a  
    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
    Nz"Error retrieving violation trend: z"Failed to retrieve violation trendr   )	r   get_30day_violation_trendr   r   r   r   r   r   r   )r   r   
trend_datar    s       r!   get_violation_trendr*   J   sj     (
+EEbII
 J 
9#a&BC==7
 	

r#   z/violation-analysiszGet Violation AnalysiszPGet analysis including top marketplaces, vendors, products, and financial impactc                    K   	 t        j                  |        d{   }|S 7 # t        $ rA}t        j	                  dt        |              t        t        j                  d      d}~ww xY ww)ai  
    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
    Nz%Error retrieving violation analysis: z%Failed to retrieve violation analysisr   )	r   get_violation_analysisr   r   r   r   r   r   r   )r   r   analysisr    s       r!   r,   r,   i   si     &
)@@DD E 
<SVHEF==:
 	

r#   z/recent-violationszGet Recent Violationsz3Get list of most recent violations with all details
   limitc                   K   |dk  s|dkD  rd}	 t        j                  | |       d{   }|S 7 # t        $ rA}t        j	                  dt        |              t        t        j                  d      d}~ww xY ww)	a  
    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
       d   r.   )r/   Nz$Error retrieving recent violations: z$Failed to retrieve recent violationsr   )	r   get_recent_violationsr   r   r   r   r   r   r   )r   r/   r   recentr    s        r!   r3   r3      s     6 qyECK
'==bNN O 
;CF8DE==9
 	

s0   B 3 13 B 3 	A=<A88A==B z/refreshzRefresh Dashboard Dataz9Trigger dashboard data refresh without reloading the page)r   r   r   r   c                    K   	 t        ddd      }t        j                  d       |S # t        $ rA}t        j	                  dt        |              t        t        j                  d      d}~ww xY ww)	ax  
    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)
    z-Dashboard data refresh triggered successfullyFN)messageis_refreshingnext_refresh_estimatez#Dashboard refresh triggered by userz$Error triggering dashboard refresh: z Failed to refresh dashboard datar   )	r
   r   infor   r   r   r   r   r   )r   r   responser    s       r!   refresh_dashboardr;      st     :
 ,C"&

 	9; 
;CF8DE==5
 	

s$   A6$) A6	A3<A..A33A6)loggingfastapir   r   r   r   sqlalchemy.ext.asyncior   app.apir   app.schemas.dashboardr	   r
   app.services.dashboard_servicer   router	getLogger__name__r   getget_dbget_current_userr"   r%   r*   r,   intr3   postHTTP_202_ACCEPTEDr;        r!   <module>rM      s/    = = /  M ;	,k]	;			8	$ $)e	   t{{+../


6 #_   t{{+../



. (B   t{{+../



4 $b   t{{+../



2 #E   t{{+../!
!
!

!
H +(($K   t{{+../%
%
%
rL   