
    +`j                         d dl Z d dlmZmZ d dlmZ d dlZd dlmZ h dZh dZ	dej                  ded	efd
ZddefdZd dlmZ 	 	 	 ddededededef
dZy)    N)datetime	timedelta)ZoneInfo)settings>   https://www.baypalmsresort.com/ https://www.thebayviewplaza.com/"https://www.plazabeachresorts.com/>   $ChcI9s-yofmNuolrGgsvZy8xdGs4Y3htbRAB&ChgIlOjmr4votcb-ARoLL2cvMXR5a3c1YmoQAQ$ChcIlpeClLW624ciGgsvZy8xdzExMnpxchAB&ChgI3vKYl56ruN6AARoLL2cvMXRobWc1aGwQAQ'ChkIxIOjhofkq5uOARoML2cvMTFyOTI3ZGc2EAEclientcheck_in_datecheck_out_datec                   K   | j                  ddd||dddddd	d
t        j                  d       d {   }|j                          |j	                         j                  dg       }|D cg c]  }|j                  d      t
        vrm|j                  d      t        v rV|j                  d      |j                  di       j                  d      xs! |j                  di       j                  d      d c}S 7 c c}w w)Nzhttps://serpapi.com/search.jsongoogle_hotelszst pete beach   r   usenz
google.comUSDtrue)engineqr   r   adultschildrenglhlgoogle_domaincurrencyno_cacheapi_key)params
propertieslinkproperty_tokennamerate_per_nightextracted_before_taxes_fees
total_rate)r'   price)getr   SERP_API_KEYraise_for_statusjsonEXCLUDED_COMPETITORS$ALLOWED_COMPETITORS_PROPERTIES_TOKEN)r   r   r   responser$   
competitors         =/var/www/html/ls-ibe-bot-apis/app/utils/competitors_prices.pyget_competitorsr5      s5    
 ZZ)% *,),,
    H" $$\26J %
 %J>>&!)==*..QaBb  gK  CK	 NN6*^^$4b9==>[\  d`j`n`no{}  aA  aE  aE  Fc  ad	
 % +*s"   2DC;8D-BC=8D=Ddaysc           
        K   t        d      }t        j                  |      j                         }t	        |       D cg c]A  }|t        |      z   j                  d      |t        |dz         z   j                  d      fC }}t        j                  d      4 d{   }|D cg c]  \  }}t        |||       }}}t        j                  |dd	i d{   }	ddd      d{    i }
t        |	      D ]4  \  \  }}}t        |t              rt        d
| d|        g |
|<   0||
|<   6 |
S c c}w 7 c c}}w 7 h7 Z# 1 d{  7  sw Y   jxY ww)z
    Fetch competitor prices for the next `days` check-in dates.

    Example:
        days=2 -> Today, Tomorrow
        days=30 -> Today through next 29 days
    zAmerica/New_York)r6   z%Y-%m-%d   g      N@)timeoutNreturn_exceptionsTz Failed to fetch competitors for z: )r   r   nowdateranger   strftimehttpxAsyncClientr5   asynciogatherzip
isinstance	Exceptionprint)r6   tztodayi
date_pairsr   check_in	check_outtasksresults
final_data_results                r4   get_competitors_pricesrR   =   sq     
$	%BLL!!#E t
 A YA&&00<YAE**44Z@	
      ..& (2
'1#) FHi8'1 	 

  FFF /. J!$Z!91vfi(4XJbIJ#%Jx #)Jx  ": 3 /

 G /...sr   <EAD8E D=!E$E	*D?E	EE	!E,E-AE?E	E	EEEE)deepcopyrN   competitorsagree_weightconflict_weight	floor_pctc                   K   t        |       }i }|j                         D ]b  \  }}g }	|D ]9  }
|
j                  d      }|	 t        |      }|dk  r)|	j                  |       ; |	sIt        |	      t        |	      z  ||<   d |s|S t        |j                               t        |      z  }|j                         D ]  \  }}t        |t              s|D ]  }|j                  d      }||vr|j                  d      +t        |d         }||   }||z  }||z  }|dk\  }d}|j                  d      t        |d         }||k\  }||k(  r|}n|}d|z
  |z  ||z  z   }t        |||z        }t        |d	      |d<   t        |d	      |d
<   t        |d	      |d<   t        |d      |d<   ||d<     |S # t        $ r Y w xY ww)u  
    Adjust predicted prices using competitor market trends.

    Instead of comparing raw competitor prices against our hotel's actual price
    (which is flawed — different hotels have different price tiers), this uses
    the competitor price *trend* relative to their own baseline to determine
    whether the market is moving up or down.

    Formula:
        1. Compute competitor avg per date and a baseline (mean of all dates).
        2. Market direction = competitor_avg[date] vs baseline_avg.
        3. Model direction  = predicted vs actual (our current price).
        4. When both signals agree → light blend (agree_weight).
           When they disagree → heavier blend (conflict_weight) pulls
           the model toward market-adjusted price.
        5. Market-adjusted price = model_price * competitor_trend_ratio
           (competitor_avg[date] / baseline_avg).

    Args:
        results:          {room_id: [{date, actual, predicted, ...}, ...]}
        competitors:      {date_str: [{name, price}, ...]}
        agree_weight:     Blend weight when model and market agree (default 0.15).
        conflict_weight:  Blend weight when they disagree (default 0.30).
        floor_pct:        Minimum ratio — adjusted price never drops below
                          floor_pct * model_price (default 0.85 = 85%).

    Returns:
        Same structure as results with updated predicted prices.
    r+   r   r<   	predictedg      ?Tactualr8   r   competitor_avgcompetitor_baseline   competitor_trendcompetitor_weight)rS   itemsr,   floatrE   appendsumlenvaluesrD   listmaxround)rN   rT   rU   rV   rW   outputr[   r<   hotelspriceshr+   baseline_avgroom_idrowsrowmodelmarkettrend_ratiomarket_adjusted	market_upmodel_upcurrentweightadjusteds                            r4   #adjust_predictions_with_competitorsrz   f   s2    J gF
 (*N#))+fAEE'NE}e zMM%    #&v;V#<N4 ) ,,  ~,,./#n2EEL
  $%C776?D>)ww{#+#k*+E#D)F !</K $k1O $s*IHwwx ,H. G+ 9$%( F
e+f.FFH 8UY%67H$Xq1C %*&!$4C !).|Q)?C%&&+K&;C"#'-C#$Y  (f MO  s0   ?GF8G)EG8	GGGG)r   )g333333?g333333?g333333?)rA   r   r   zoneinfor   r?   app.configs.settingsr   r0   r1   r@   strr5   intrR   copyrS   dictra   rz        r4   <module>r      s     (   ) ( $!!! !H$s $L  !~~~ ~ 	~
 ~r   