
    !+i                         d Z ddlZddl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  ej                  e      Z G d	 d
      Zy)zv
Hyper Forecast - Momentum Calculator
Calculates short-term trend adjustments based on recent performance vs expected
    N)datetime	timedelta)DictOptional)Session   )DataCollector)BaselineCalculatorc                   J    e Zd ZdZdefdZ	 	 ddededefdZ		 ddedefd	Z
y
)MomentumCalculatorz
    Calculates momentum multiplier based on recent sales vs expected
    If recent hours are performing above/below expectations, adjust future predictions
    dbc                 R    || _         t        |      | _        t        |      | _        y )N)r   r	   data_collectorr
   baseline_calc)selfr   s     X/var/www/hypershopcomercio.com.br/hyper-ai/app/services/forecast/multipliers/momentum.py__init__zMomentumCalculator.__init__   s#    +B//3    hours_lookbacksmoothing_factorreturnc           
         t        j                         }|j                  }|j                         }|dk  rdddi dS d}d}d}g }	t	        dt        |dz   |dz               D ]  }
||
z
  }| j                  j                  ||      }|d   }| j                  j                  ||      }|d   }|dkD  sP||z  }||z  }|dz  }|	j                  |d	d
|||dkD  r||z  ndd        |dk(  s|dk(  rddd|	dS ||z  }|dz
  }||z  }d|z   }t        dt        d|            }|dkD  rd|dz
  dz  dd| d
}d}n|dk  rdd|z
  dz  dd| d
}d}nd}d}t        dd|dz  z         }t        |d      t        |d      |||||||	d	S )aY  
        Calculate momentum multiplier based on last N hours performance
        
        Args:
            hours_lookback: How many recent hours to analyze
            smoothing_factor: How much to dampen the adjustment (0.5 = half the deviation)
        
        Returns:
            Dict with momentum multiplier and analysis details
                 ?g333333?u$   Dados insuficientes (início do dia))
multiplier
confidencereasondetailsr   revenuebaseline02dh)houractualexpectedratiou)   Sem baseline histórico para comparaçãogffffff?gffffff?g?zVendas d   z.1fu!   % acima do esperado nas últimas upgffffff?u"   % abaixo do esperado nas últimas downzVendas dentro do esperadoneutralg?g?g?   )	r   	raw_ratioactual_totalexpected_totalhours_analyzed	directionr   r   r   )r   nowr#   daterangeminr   get_hourly_salesr   calculate_baselineappendmaxround)r   r   r   r1   current_hourtodayr-   r.   r/   r   hour_offsetr#   r$   actual_revenuer    expected_revenuer,   	deviationsmoothed_deviationr   r   r0   r   s                          r   calculate_momentumz%MomentumCalculator.calculate_momentum   sU    llnxx
 !!!@	   C(:L1<L$MN 	K+-D ((99%FF#I.N ))<<T5IH'
3!#."22!##CjN, 0BRUVBV^.>>\_	  !	. Q.A"5!!E"	  !>1	 O	&)99--
 s445
 Q# 5s;;\]k\llmnFI$Y# 5s;;]^l]mmnoFI0F!I c^c%9:;
  
A.y!,(,,"$

 
	
r   days_lookbackc                     ddddS )z
        Calculate correction factor based on recent prediction errors
        If the model consistently over/under-predicts, apply a correction
        r   g        u*   Correção de erro não implementada ainda)correction_factor	avg_errorr    )r   rB   s     r   calculate_error_correctionz-MomentumCalculator.calculate_error_correction   s     "%B
 	
r   N)   g      ?)   )__name__
__module____qualname____doc__r   r   intfloatr   rA   rG   rF   r   r   r   r      s]    
47 4  "%e
e
  e
 
	e
R 

 

r   r   )rM   loggingr   r   typingr   r   sqlalchemy.ormr   r   r	   r    r
   	getLoggerrJ   loggerr   rF   r   r   <module>rU      s<     ( ! " * )			8	$B
 B
r   