o
    si*                  	   @   s   d dl Z d dlZd dlZd dlZd dlmZ d dlZedZeej	 dZ
e je je je jedZdddd	d
ddddddddddddddddddddZd%ddZd%ddZd d! Zd&d#d$ZdS )'    N)datetimeava_advisorz$https://api.x.ai/v1/chat/completionszstrategies.jsonz:an analytical, professional, and cautious business advisorz]Focus on Business Objectives: Profit, Demand (Velocity), and Risk Management. Be Risk-Averse.z3Professional, objective, and concise (50-80 words).zAvoid "wishy-washy" language. Give a clear "Buy" or "Pass" recommendation based on the data. Highlight margins and "don't lose money" scenarios.zC"Pass. The 22% margin is too slim for the current rank volatility.")rolefocustonestyle_guideexamplez"an aggressive, high-volume flipperz9Focus on Velocity, turnover speed, and "get in, get out".z'Short, punchy, energetic (30-50 words).zIUse exclamation points for good deals. Be direct. Focus on speed of sale.z["Buy! Rank is dropping fast. Price is low. Grab 5 copies and flip them before the weekend."z/an educational mentor and book arbitrage expertzHFocus on teaching *why* a deal is good or bad, citing specific concepts.z-Verbose, patient, explanatory (80-100 words).zuExplain the "why". Connect data points (e.g., "U-shaped sales curve indicates seasonal demand"). Use a teaching tone.z"This is an interesting case. Notice the 'U-shaped' sales curve? That indicates seasonal textbook demand. Although the current price is low..."z)a quantitative analyst and data scientistzLFocus on statistical confidence, historical averages, and objective metrics.z2Dry, robotic, purely objective. Use bullet points.z^Present data in structured format. Focus on variance, confidence intervals, and probabilities.zjVelocity: High (Top 1%)
Price Variance: +/- 15%
Rec: Strong Buy based on 3-year historical support levels.)cfoflipper	professorquantc           
      C   sp  zt jtrttddd}t|}t|trg }t	g d}| r@| 
dd }| 
dd }d|v s;d|v r@|d	 |D ]6}t|trp|
d
d}| rY||v sY|dkro|d| d|
dd d|
dd  qB|d|  qBd|W  d   W S W d   W dS 1 sw   Y  W dS W dS  ty }	 ztd|	  W Y d}	~	dS d}	~	ww )z
    Loads strategies from strategies.json and formats them for the prompt.

    Args:
        deal_context (dict, optional): Context about the deal (e.g., category, seasonality) to filter strategies.
    rzutf-8)encoding)GeneralBuyingRiskDetailed_Seasonality TitletextbookSeasonalitycategoryr   z- [Category: z] IF triggerzN/Az THEN advicez- 
NzError loading strategies: )ospathexistsSTRATEGIES_FILEopenjsonload
isinstancelistsetgetloweradddictappendjoin	Exceptionloggererror)
deal_contextf
strategies	formattedrelevant_categoriesseasonalitytitlescate r8   2/var/www/agentarbitrage/keepa_deals/ava_advisor.pyload_strategies1   sB   



, r:   c           	      C   s  |r|nt d}|r*t|dkr|dd d |dd  nd}td|  n	td	 d
diS d| dd}tjdd}zHtdt  |j	t|| d}td|j
  |j}t|dkrstd|dd  d ntd|  |  | W W  d   S  tjy } z(td|jj
 d|jj  d|jj
 |jjdW  Y d}~W  d   S d}~w tjtjfy } z"td|  tt  d
t|iW  Y d}~W  d   S d}~ww 1 sw   Y  dS )z)
    Sends a request to the xAI API.
    	XAI_TOKEN
   N   z...z***zUsing XAI_TOKEN: zDXAI_TOKEN is not set in environment variables or passed as argument.r-   zXAI_TOKEN is not configured.zBearer zapplication/json)AuthorizationzContent-Typeg      N@)timeoutzSending request to xAI API: )headersr    zxAI Response Status Code: i  zxAI Response Body (truncated): zxAI Response Body: z#xAI API request failed with status z: zAPI request failed with status )r-   contentzxAI API request failed: )r   getenvlenr,   infor-   httpxClientXAI_API_URLpoststatus_codetextraise_for_statusr    HTTPStatusErrorresponseRequestErrorJSONDecodeError	traceback
format_excstr)	payloadapi_keyxai_api_key
masked_keyrA   clientrN   response_textr7   r8   r8   r9   query_xai_api[   sD   ,
"rZ   c              	   C   s\   | d u rdS zt | trt| dddd} d| dW S  ttfy-   t|  Y S w )N-$r   ,z,.2f)r"   rS   floatreplace
ValueError	TypeError)valuer8   r8   r9   format_currency   s   
rc   r	   c              
   C   sz  z|  dd}|  dp|  d}|  d}|  d}|  d}|  dd	}|  d
}	|  d}
|  d}|  dd}|  dd}t | td }t| d}d}|r[d| d}dg d|d  d| dt| dt| d| d| d| d| d| dt|	 d |
 d!| d"|d#  d$|d%  d&|d'  d(| d)|d*  d+}d,d-d.d/|d.gd0d1d2d3d4}t||d5}d6|v rtd7|d6   W d8S z|d9 d d: d; 	 }|W W S  t
tfy   td< td=|  Y W d>S w  ty< } ztd?|  tt  W Y d@}~dAS d@}~ww )BaK  
    Generates advice for a specific deal using xAI.

    Args:
        deal_data (dict): Dictionary containing deal details.
        mentor_type (str): The persona to adopt ('cfo', 'flipper', 'professor', 'quant').
        xai_api_key (str, optional): The API key to use.

    Returns:
        str: The generated advice text.
    r   zUnknown Title	Price_Now
Best_Price1yr_AvgSales_Rank_CurrentSales_Rank_365_days_avgr   UnknownProfitMarginPercent_DownTrendr   Sales_Rank_Drops_last_365_daysr   r	   )r.   zP
        **Your Learned Strategies (Use these to inform your advice):**
        z	
        z
        You are Ava, r   z. Your goal is to give advice to a user who is considering buying this book to resell.

        **Book Details:**
        *   **Title:** z$
        *   **Current Buy Price:** z'
        *   **1-Year Average Price:** z(
        *   **Percent Down from Avg:** z9% (Higher is better)
        *   **Current Sales Rank:** z: (Lower is better)
        *   **1-Year Avg Sales Rank:** z3
        *   **Sales Rank Drops (Last 365 Days):** z8 (More drops = more sales)
        *   **Seasonality:** z#
        *   **Estimated Profit:** z
        *   **Margin:** z%
        *   **Price Trend:** z>

        **Your Persona & Strategy:**
        *   **Focus:** r   z
        *   **Tone:** r   z
        *   **Style:** r   z
        *   **Context Aware:** Apply your learned strategies (below) to identify risks (e.g., prohibited items, restriction risks).

        z4

        **Example of your advice style:**
        r   z@

        **Write your advice for this specific book:**
        systemz;You are Ava, a helpful and expert book arbitrage assistant.)r   rB   userzgrok-4-fast-reasoningFg?   )messagesmodelstreamtemperature
max_tokens)rU   r-   zError generating advice: zQI'm having trouble analyzing this book right now. Please check the data yourself.choicesmessagerB   z#Unexpected response format from xAIzFull Result: z)I couldn't generate advice for this book.z"Exception in generate_ava_advice: Nz5An unexpected error occurred while generating advice.)r%   MENTOR_PERSONASr&   r:   r*   rc   rZ   r,   r-   stripKeyError
IndexErrorr+   rQ   rR   )	deal_datamentor_typerV   r4   current_priceavg_price_1yrsales_rank_currentsales_rank_365_avgr3   profitmarginpercent_downtrend	drops_365mentorstrategies_textstrategy_sectionpromptrT   resultr   r7   r8   r8   r9   generate_ava_advice   s   







	
!

r   )N)r	   N)r   r    loggingrF   r   rQ   	getLoggerr,   setLevelINFOrH   r   r*   dirnameabspath__file__r   ry   r:   rZ   rc   r   r8   r8   r8   r9   <module>   sN    
&

*,