o
    jEi9"                     @   st   d dl Z d dlZd dlZd dlZddlmZ ddlmZ ee	Z
e Ze Zg dZdd Zddd	Zd
d ZdS )    N   )XaiTokenManager)XaiCache)Textbook (Summer)Textbook (Winter)High School AP Textbooks
Law SchoolNursing SchoolMedical SchoolCommunity College	GardeningGrilling/BBQ	ChristmasNew Year/FitnessTax PrepTravel	HalloweenThanksgivingRomance/Valentine's Day
Year-roundc                 C   s&  |s	t d dS d|  d| d| }t|}|r)t d| d|  d |S t s8t d|  d	 dS d
|  d| d| d|rJ|dkrJ|nd d|rU|dkrU|nd ddt d}t d|  d t d| d|  dddd|dgdddd}	d | d!d"}
z`t	j
d#d$O}|jd%|
|	d&}|  | }|d' d( d) d*  }|tv rt d+|  d,|  t|| |W  d-   W S t d.| d	 	 W d-   W dS 1 sw   Y  W d-S  t	jt	jtjttfy } zt d/|  d0|  W Y d-}~dS d-}~ww )1z]
    Queries the XAI API to classify seasonality, now with caching and token management.
    z9XAI API key is not provided. Skipping LLM classification.r   zseasonality:|z5XAI Cache HIT for seasonality. Found classification 'z' for title 'z'.z*XAI daily limit reached. Cannot classify 'z'. Defaulting to Year-round.z
    Based on the following book details and historical sales data, choose the single most likely sales season from the provided list.
    Respond with ONLY the name of the season from the list.

    **Book Details:**
    - **Title:** "z"
    - **Category:** "z"
    - **Publisher:** "zF"

    **Sales Data Insights:**
    - **Inferred Peak Price Month:** "-zN/Az*"
    - **Inferred Trough Price Month:** "z"

    **Season List:**
    z, z
    z"XAI Seasonality Request for ASIN 'z' (Cache MISS):z
  - Peak: z
, Trough: systemzYou are a book classification expert. Your task is to select the most appropriate seasonal category for a book from a given list.)rolecontentuserzgrok-4-fast-reasoningg?2   )messagesmodeltemperature
max_tokenszBearer zapplication/json)AuthorizationzContent-Typeg      >@)timeoutz$https://api.x.ai/v1/chat/completions)headersjsonchoicesr   messager   zLLM classified 'z' as: Nz)LLM returned an invalid classification: 'z"XAI API request failed for title 'z': )loggerwarning	xai_cachegetinfoxai_token_managerrequest_permissionjoinSEASON_CLASSIFICATIONShttpxClientpostraise_for_statusr$   stripsetHTTPStatusErrorRequestErrorJSONDecodeErrorKeyError
IndexErrorerror)titlecategories_submanufacturerpeak_season_strtrough_season_strapi_key	cache_keycached_resultpromptpayloadr#   clientresponsedata
llm_choicee rK   =/var/www/agentarbitrage/keepa_deals/seasonality_classifier.py_query_xai_for_seasonality   sn   


( rM   c                    s  | sd} |sd}|sd}|   }|  }|   g d}t fdd|D }	d|v r3d|v s1|	r3dS d|v s=d	|v s=|	rKd
|v rCdS d|v rIdS dS d|v sSd|v rUdS d|v s]d|v r_dS d|v sgd|v ridS d|v rodS d|v swd|v rydS d|v sd|v sd|v rdS d|v sd |v rd!|v rd"S d#|v sd$|v sd%|v sd&|v rd'|v rd(S d)|v rd*|v sd+|v rd,S d-|v sd-|v rd.S d/|v rd0S d1|v rd2S d3|v sd4|v rd5S td6|  d7 t| |||||}
|
S )8a<  
    Classifies a book's seasonality based on heuristics and an XAI model,
    now enriched with inferred sales data.

    Args:
        title (str): The title of the book.
        categories_sub (str): The sub-category string.
        manufacturer (str): The manufacturer/publisher.
        peak_season_str (str): The inferred month of peak prices (e.g., "Jan").
        trough_season_str (str): The inferred month of trough prices (e.g., "Jul").
        xai_api_key (str, optional): The API key for the XAI service.

    Returns:
        str: The classified season.
     )cengagezmcgraw-hillpearsonwiley	macmillansagec                 3   s    | ]}| v V  qd S NrK   ).0pub	mfr_lowerrK   rL   	<genexpr>   s    z'classify_seasonality.<locals>.<genexpr>apzhigh schoolr   college
universitysummerr   winterr   z
law schoolzbar examr   nursingnclexr	   zmedical schoolmcatr
   zcommunity colleger   	gardeningr   grillingbbqbarbecuer   	christmasholidaygiftr   znew yearfitnessdietz	self-help
resolutionr   taxprepguider   travelr   	halloweenr   thanksgivingr   	valentineromancer   z)Heuristics resulted in 'Year-round' for 'z/'. Querying XAI with sales data for refinement.)loweranyr'   r+   rM   )r<   r=   r>   r?   r@   xai_api_keytitle_lower	cat_lowertextbook_publishersis_textbook_publisher
llm_resultrK   rW   rL   classify_seasonalityg   s^   (r|   c                 C   sv   i 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ddddddddd }| | d S )!a{  
    Maps a detailed season classification from the 'Detailed_Seasonality' column
    to a specific selling period string for the 'Sells' column.

    Args:
        detailed_season (str): The detailed season name.

    Returns:
        str: A string representing the peak selling period (e.g., "Nov-Dec").
             Returns "All Year" if no specific period is applicable.
    r   z	Jul - Sepr   z	Jan - Febr   r   Octr	   z	Mar - Aprr
   z	Aug - Sepr   zSep - Oct & Jan - Febr   r   z	May - Junr   z	Nov - Decr   Janr   z	Jan - Aprr   z	May - Augr   z	Sep - Octr   Novr   Febr   zAll Year)r*   )detailed_season
period_maprK   rK   rL   get_sells_period   sH   	
r   rT   )rer0   r$   loggingr,   r   r)   r   	getLogger__name__r'   r/   rM   r|   r   rK   rK   rK   rL   <module>   s   

OP