
    diu                        d Z ddlmZ ddlmZmZ ddlmZ ddlmZ ddl	m
Z  ej                  dd	      	 d	 	 	 	 	 dd
       Zy)z~
Celery task for training monthly demand forecast model using Random Forest.
Uses the monthly_prediction module for training.
    )annotations)DictOptional)datetime)
celery_app)mainTzZsrc.smart_inventory.tasks.monthly_demand_forecast_task.train_monthly_demand_forecast_model)bindnamec                   ddl m} ddlm}m} t         |             }d}| j                  j                  }t        d| d|        	 |j                  |      j                  |j                  |k(        j                         }t        d|        |rF|j                  |_        t        j                          |_        |j%                          t        d       nt        d	|        t'        |d
|dd      \  }	}
}}}|	j)                  ||      }ddlm}  |t.              j0                  j0                  j0                  j0                  }|dz  d| dz  }|r:|j2                  |_        t        j                          |_        |j%                          dd| d
|t7        |j9                  dd            t7        |j9                  dd            t7        |j9                  dd            dt;        |      d|j=                          S # t>        $ r}	 |sO|j                  |      j                  |j                  | j                  j                  k(        j                         }|rJ|j@                  |_        t        j                          |_        t;        |      |_!        |j%                          n$# tD        $ r}t        d|        Y d}~nd}~ww xY wdt;        |      |dcY d}~|j=                          S d}~wtD        $ r}	 |sO|j                  |      j                  |j                  | j                  j                  k(        j                         }|rM|j@                  |_        t        j                          |_        dt;        |       |_!        |j%                          n$# tD        $ r}t        d|        Y d}~nd}~ww xY wddt;        |       |dcY d}~|j=                          S d}~ww xY w# |j=                          w xY w)a  
    Train monthly demand forecast model using Random Forest for a specific company.
    
    This task uses the monthly regression training pipeline with:
    - model_type: 'random_forest' (hardcoded)
    - train_all_models: False (single model mode)
    - Trains on all products and locations for the specified company
    
    Args:
        company_id: Company ID to train model for (required)
        n_trials: Number of Optuna optimization trials (default: 50)
    
    Returns:
        Dict with success status and message/error
    r   )get_db)CeleryTaskTrackerCeleryTaskStatusNz%[CELERY TASK] Starting task with ID: z for company_id: z"[CELERY TASK] Found task_tracker: z'[CELERY TASK] Updated status to STARTEDz:[CELERY TASK] WARNING: No task_tracker found for task_id: random_forestg?F)
company_id
model_typen_trials	test_sizetrain_all_models)Pathmodelscompany_z"_monthly_demand_forecast_model.pklTz?Monthly demand forecast model trained successfully for company RMSER2MAE)	test_rmsetest_r2test_mae)successmessager   r   metrics
model_pathzFailed to update task tracker: )r   errorr   zError training monthly model: )#src.utils.dbr   )src.smart_inventory.apps.inventory.modelsr   r   nextrequestidprintqueryfiltertask_idfirstSTARTEDstatusr   now
started_atcommittrain_monthly_modelevaluatepathlibr   __file__parentSUCCESScompleted_atfloatgetstrclose
ValueErrorFAILUREerror_message	Exception)selfr   r   r   r   r   dbtask_trackerr+   monthly_regressorX_trainX_testy_trainy_testtest_metricsr   project_rootr!   edb_errors                       U/var/www/html/hubwallet-dev/src/smart_inventory/tasks/monthly_demand_forecast_task.py#train_monthly_demand_forecast_modelrN      s   * $] 
fhBLllooG	1':KJ<
XY`xx 1299%%0

%' 	 	2<.AB"2":":L&.llnL#IIK;=NwiXY ?R!&"?
;7FGV )11&&A 	!H~,,33::AA!H,*Eg/hh
 "2":":L(0L%IIK XYcXde)$"<#3#3FA#>? !1!1$!:;!,"2"25!"<=
 j/
p 	
W  
	@!xx(9:AA%--@ %'  &6&>&>#,4LLN)-0V*		 	@3H:>??	@ V$
 	
6 	
-  
	@!xx(9:AA%--@ %'  &6&>&>#,4LLN)/McRSfX-V*		 	@3H:>??	@ 5c!fX>$
 	
 	
-
, 	
s   	F,H 	O4BJ.-K6.	K7K
K6
KK6 O4!O7 6O4B N$#O/$	O-O ;O/ OO/O4O7 /O44O7 7P	N)2   )r   intr   rP   returnr   )__doc__
__future__r   typingr   r   r   src.utils.celery_workerr   Dsrc.smart_inventory.core.monthly_prediction.train_monthly_regressionr   r2   taskrN        rM   <module>rZ      sd    # !  . l d!}~ ~~ ~ 
	~ ~rY   