o
    'i                     @   sl   d dl Z d dlZd dlmZ d dlmZ d dlm  mZ d dl	m  m
Z
 d dlmZ G dd deZdS )    N)BaseHTTPMiddleware)Request)loggerc                   @   s0   e Zd ZdefddZdededefddZd	S )
!ComprehensiveAPILoggingMiddlewarerequestc                    s&  |j dp|j dp|jr|jjnd}d|v r#|dd  }|j d}|jj}|j}|j	}i }|
 D ]4\}	}
d|
v rgt }g }|
dD ]}| }|ra||vra|| || qK|||	< q9|
 ||	< q9d }|jdv rz#| I d H }|r| }zt|}W n tjy   |}Y nw W n ty   d}Y nw |||d	g |d
g d}t }tj|||||d}|| |  zCz||I d H }|j|_|  |W W |  S  ty } zt }d|_||_|  t d| d| d|  |d }~ww |  w )Nzx-forwarded-forz	x-real-ipunknown,r   z
user-agent)POSTPUTPATCHz<unreadable>symbolskpis)query_paramsbodyselected_stocksselected_kpis)endpointmethod
ip_address
user_agentrequest_datai  zAPI Error: z | IP: z
 | Error: )!headersgetclienthostsplitstripurlpathr   r   itemssetaddappendr   decodejsonloadsJSONDecodeError	ExceptiondatabaseSessionLocalmodelsApiLogcommitstatus_coderesponse_statusclose	traceback
format_excerror_messager   error)selfr   	call_nextipr   r   r   
raw_paramsr   keyvalueseencleaned_listvr   
body_bytesdecodedcontextdb	log_entryresponseexc	error_msg rE   1/var/www/html/stock_analysis/be/app/middleware.pydispatch   s   









z*ComprehensiveAPILoggingMiddleware.dispatchr   paramsreturnc              	   C   s6   ddddddddd	}| d
d }||d| S )z;Generate a human-readable description of the user's action.zFetching KPI time series dataz(Calculating stock performance & rankingszDownloading performance ExcelzApplying advanced KPI filterszUploading instrument listzUploading market/exchange datazSearching for stock symbolszRunning quarterly analysis)z/kpis/z/stock_performance_calculation/z"/download_stock_performance_excel/z/filter-stocks/z/upload/instrumentsz/upload/market-exchangesz/symbol-search/z(/stock_quarterly_performance_calculation?r   zUnknown action on )r   r   )r4   r   rH   r   actionsbaserE   rE   rF   _infer_actionj   s   
z/ComprehensiveAPILoggingMiddleware._infer_actionN)__name__
__module____qualname__r   rG   strdictrM   rE   rE   rE   rF   r   
   s    _r   )r$   r0   starlette.middleware.baser   fastapir   app.db.databaser@   r(   app.db.modelsr*   r   r   rE   rE   rE   rF   <module>   s    