o
    #jm9                     @   s  d Z ddlmZ ddlmZmZmZ ddlmZmZ ddl	m
Z
mZmZ ddlmZmZmZmZmZmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ede Z!edZ"e!j#ddgdeeddddd Z$	 e!j#ddgddd Z%e!j#ddgddd Z&e!j#ddgddd Z'e!j#ddgdedd  Z(e!j#d!dgdej)ed"d# Z*e!j#d$dgdd%d& Z+e!j#d'dgdej)e
ed(d) Z,e!j#d*dgdej)e
ed+d, Z-e!j#d-dgdej)e
ed.d/ Z.e!j#d0dgdej)d1d2 Z/e!j#d3dgdej)d4d5 Z0e!j#d0dgdej)d6d7 Z1e!j#d8dgdej)e
ed9d: Z2e!j#d;dgdej)d<d= Z3e!j#d>dgdej)d?d@ Z4e!j#dAdgdej)dBdC Z5e!j#dDdgdej)dEdF Z6e!j#dGdgdej)e
edHdI Z7e!j#dJdgdej)e
edKdL Z8e!j#dMdgdej)e
edNdO Z9e!j#dPdgdej)e
edQdR Z:e!j#dSdgdej)dTdU Z;e!j#dVdgdej)dWdX Z<e!j#dVdgdej)dYdZ Z=e!>d[d\d] Z?e!>d^d_d` Z@e!>eAdadb ZBdcS )dz
# File: pyapi/app/routes/api.py
# Description: API routes for the OTT Reports service, including caching, validation, and error handling
    )datetime)	Blueprintjsonifyrequest)
get_loggerperformance_log)validate_jsonvalidate_queryvalidate_multiple)ProphetTrainRequestProphetForecastRequestProphetPlotRequestProphetValidateRequestRegressionTrainRequestCollectionRiskScoreRequestSalesTargetPredictRequest)CacheServicecache_response)auth_middleware)ProphetController)ReportController)RegressionControllerapiz/healthGET)methodshealth_check<   )timeoutc               
   C   s  z[dt t t d} t }| }t|dr | | d< n2t|dr+|j	| d< n't
|trNt|dkrN|d }t|drF| | d< ndd	d
| d< n|| d< t| }d|_|W S  ty } z#tdt |  tdt |t t d}d|_|W  Y d}~S d}~ww )z+Health check endpoint with cache statisticshealthy)status	timestampcacheget_json	databasesjson   r   unknownz(Unable to parse database health response)r   error   zHealth check failed: 	unhealthy)r   r'   r      N)strr   nowr   	get_statsr   get_database_healthhasattrr"   r$   
isinstancetuplelenr   status_code	Exceptionloggerr'   )health_datareport_controllerdb_health_responseresponse_dataresponsee r<   ,/var/www/html/oms-prod-mcp/app/routes/api.pyr   7   s>   



z/dataPOSTc                  C   s    t j} 	 td| d}d|_|S )NzData created)messagedata   )r   r$   r   r3   )r@   r:   r<   r<   r=   create_datau   s
   rB   z/data/<int:data_id>c                 C   s   t | dd}d|_|S )z
    Endpoint to retrieve data by ID
    This is a placeholder for demonstration purposes.
    In a real application, you would retrieve data from a database or service.
    zSample data)data_idr@   r(   r   r3   rC   r:   r<   r<   r=   get_data      rF   DELETEc                 C   s   t d| d}d|_|S )z
    Endpoint to delete data by ID
    This is a placeholder for demonstration purposes.
    In a real application, you would delete data from a database or service.
    zData deleted)r?   rC      rD   rE   r<   r<   r=   delete_data   rG   rJ   z/cache/statsc               
   C   s   zt  } td| tt d}d|_|W S  ty@ } zt	dt|  tdt|d}d|_|W  Y d}~S d}~ww )	zGet cache statisticssuccess)r   r@   r    r(   zError getting cache stats: r'   r   r?   r*   N)
r   r-   r   r+   r   r,   r3   r4   r5   r'   )statsr:   r;   r<   r<   r=   get_cache_stats   s   rN   z/cache/clearc               
   C   s   zt  } t| r
dnd| rdndtt d}d|_|W S  tyH } zt	dt|  tdt|d	}d
|_|W  Y d}~S d}~ww )z Clear all cache (admin endpoint)rK   warningzCache cleared successfullyzCache clear may have failed)r   r?   r    r(   zError clearing cache: r'   rL   r*   N)
r   clearr   r+   r   r,   r3   r4   r5   r'   )rK   r:   r;   r<   r<   r=   clear_cache   s&   

	rQ   z/reports/database/healthc                  C      t  } |  S )z"Database connectivity health check)r   r.   
controllerr<   r<   r=   get_reports_database_health   s   rU   z/prophet/trainc                 C      t  }|| S )z!Train a Prophet forecasting model)r   train_modelvalidated_jsonrT   r<   r<   r=   train_prophet_model      
rZ   z/prophet/forecast/<model_id>c                 C      t  }|| |S )z/Generate forecast using a trained Prophet model)r   generate_forecastmodel_idrY   rT   r<   r<   r=   generate_prophet_forecast      r`   z/prophet/plot/<model_id>c                 C   r\   )z2Generate forecast plot for a trained Prophet model)r   get_forecast_plotr^   r<   r<   r=   generate_prophet_plot   ra   rc   z/prophet/models/<model_id>c                 C   rV   )z-Get information about a trained Prophet model)r   get_model_infor_   rT   r<   r<   r=   get_prophet_model_info      
rf   z/prophet/modelsc                  C   rR   )zList all trained Prophet models)r   list_modelsrS   r<   r<   r=   list_prophet_models      ri   c                 C   rV   )zDelete a trained Prophet model)r   delete_modelre   r<   r<   r=   delete_prophet_model   rg   rl   z/prophet/validatec                 C   rV   )z,Validate time series data format for Prophet)r   validate_datarX   r<   r<   r=   validate_prophet_data  r[   rn   z/prophet/train/dbc                  C   s    t  } tjddp
i }| |S )z2Train a Prophet model using data from OMS databaseT)silent)r   r   r"   train_from_database)rT   r@   r<   r<   r=   train_prophet_from_database  s   
rq   z/prophet/tablesc                  C   rR   )z1Get available OMS tables for time series analysis)r   get_available_tablesrS   r<   r<   r=   get_prophet_tables  rj   rs   z#/prophet/tables/<table_key>/previewc                 C   s   t  }tj }|| |S )z,Get preview of time series data from a table)r   r   argsto_dictget_data_preview)	table_keyrT   paramsr<   r<   r=   get_prophet_data_preview%  s   
ry   z$/prophet/tables/<table_key>/validatec                 C   rV   )zValidate a table configuration)r   validate_table_config)rw   rT   r<   r<   r=   validate_prophet_table.  rg   r{   z!/regression/train/collection-riskc                 C   rV   )z6Train XGBoost collection risk classifier for a company)r   train_collection_riskrX   r<   r<   r=   train_collection_risk_model:  r[   r}   z/regression/train/sales-targetc                 C   rV   )z=Train XGBoost sales target attainment regressor for a company)r   train_sales_targetrX   r<   r<   r=   train_sales_target_modelC  r[   r   z!/regression/score/collection-riskc                 C   rV   )z+Score clients for payment delay probability)r   score_collection_riskrX   r<   r<   r=   r   L  r[   r   z /regression/predict/sales-targetc                 C   rV   )u<   Predict attainment % for district×product_head combinations)r   predict_sales_targetrX   r<   r<   r=   r   U  r[   r   z/regression/modelsc                  C   rR   )z1List all trained regression/classification models)r   rh   rS   r<   r<   r=   list_regression_models^  rj   r   z/regression/models/<model_id>c                 C   rV   )z(Get info for a specific regression model)r   rd   re   r<   r<   r=   get_regression_model_infof  rg   r   c                 C   rV   )zDelete a regression model)r   rk   re   r<   r<   r=   delete_regression_modeln  rg   r     c                 C   s(   t dtj  tddi}d|_|S )Nz404 error for path: r'   zEndpoint not foundr   )r5   rO   r   pathr   r3   r'   r:   r<   r<   r=   	not_foundv  s   r     c                 C   s0   t dtj dtj  tddi}d|_|S )Nz405 error for  r'   zMethod not allowedr   )r5   rO   r   methodr   r   r3   r   r<   r<   r=   method_not_allowed~  s   r   c                 C   s,   t dt|   tddd}d|_|S )zECatch any unhandled exceptions in API routes and ensure JSON responsezUnhandled API exception: zInternal server errorzAn unexpected error occurred)r'   r?   r*   )r5   r'   r+   r   r3   r   r<   r<   r=   handle_api_exception  s   r   N)C__doc__r   flaskr   r   r   app.utils.helpersr   r   app.decorators.validationr   r	   r
   app.schemas.request_schemasr   r   r   r   r   r   r   app.services.cache_servicer   r   app.middleware.auth_middlewarer   "app.controllers.prophet_controllerr   !app.controllers.report_controllerr   %app.controllers.regression_controllerr   __name__api_bpr5   router   rB   rF   rJ   rN   require_api_keyrQ   rU   rZ   r`   rc   rf   ri   rl   rn   rq   rs   ry   r{   r}   r   r   r   r   r   r   errorhandlerr   r   r4   r   r<   r<   r<   r=   <module>   s    $	

0








