o
    ó%]iæ  ã                   @   sv   d Z ddlmZ ddlmZmZ ddlZddlmZ ddlm	Z	 ddl
mZ ddlmZ e e¡ZG d	d
„ d
eƒZdS )zFeature engineering agenté    )ÚSession)ÚdatetimeÚ	timedeltaN)Ú	BaseAgent)ÚMatchRepository)ÚFeatureBuilder)ÚFeaturec                       s4   e Zd ZdZdef‡ fdd„Zdefdd„Z‡  ZS )ÚFeatureAgentzAgent for building featuresÚdbc                    s&   t ƒ  |d¡ t|ƒ| _t|ƒ| _d S )Nr	   )ÚsuperÚ__init__r   Ú
match_repor   Úfeature_builder)Úselfr
   ©Ú	__class__© úapp/agents/feature_agent.pyr      s   
zFeatureAgent.__init__Úreturnc              
   C   sj  |   ¡ }d}d}d}züt ¡ }|tdd }|tdd }|tdd }d}	| jj||dd}
| jj||	dd}tƒ }g }t|
ƒt|ƒ D ]}|j	|v rMqE| 
|j	¡ | |¡ qEt d	t|ƒ› d
t|
ƒ› dt|ƒ› d¡ |D ]g}|d7 }| j t¡ tj|j	k¡ ¡ }| j |¡}|r³tjj ¡ D ]}|dv ršq“t||ƒr¨t||t||ƒƒ q“t ¡ |_|d7 }n
| j 
|¡ |d7 }|d dkr×| j ¡  t d|› d|› d|› d¡ qp| j ¡  | j  !|¡}|rð||_"||_#| j ¡  | j$dd t d|› d|› d|› ¡ W dS  t%y4 } z!t&|ƒ}tj'd|› dd | j (¡  | j$d|d W Y d}~dS d}~ww )zRun feature engineeringr   é   )ÚdaysiÚ  NiÐ  )Ú	from_dateÚto_dateÚlimitiˆ  zBuilding features for z matches (upcoming=z, finished=ú)é   )ÚidÚmatch_idéd   z
Processed z features (created=z
, updated=T)ÚsuccesszFeatures done: created=z, processed=zFeature engineering failed: )Úexc_infoF)r   Úerror))Ú	start_runr   Únowr   r   Úget_upcomingÚget_finishedÚsetÚlistr   ÚaddÚappendÚloggerÚinfoÚlenr
   Úqueryr   Úfilterr   Úfirstr   Úbuild_features_for_matchÚ	__table__ÚcolumnsÚkeysÚhasattrÚsetattrÚgetattrÚutcnowÚcalculated_atÚcommitÚrun_repoÚ	get_by_idÚrecords_createdÚrecords_updatedÚ
finish_runÚ	ExceptionÚstrr!   Úrollback)r   Úrun_idÚ	processedÚcreatedÚupdatedr#   Úupcoming_fromÚupcoming_toÚfinished_fromÚfinished_toÚupcomingÚfinishedÚseenÚall_matchesÚmÚexistingÚfeatÚcolÚrunÚeÚ	error_msgr   r   r   rR      s€   ýý
*
€


€


€ûzFeatureAgent.run)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   ÚboolrR   Ú__classcell__r   r   r   r   r	      s    r	   )rX   Úsqlalchemy.ormr   r   r   ÚloggingÚapp.agents.baser   Ú)app.core.db.repositories.match_repositoryr   Úapp.ml.featuresr   Úapp.core.db.models.featurer   Ú	getLoggerrU   r*   r	   r   r   r   r   Ú<module>   s    
