o
    hGi#                     @   s~   d Z ddlZddlZddlZddlZddlmZ eeZ	e
ddZdZdededB fd	d
ZdedededefddZdS )zY
This module encapsulates all interactions with the Amazon Selling Partner API (SP-API).
    N)	urlencode
SP_API_URLz/https://sandbox.sellingpartnerapi-na.amazon.comATVPDKIKX0DERcondition_inputreturnc                 C   s   | sdS t |   }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di}||S )zW
    Maps internal condition strings or codes to Amazon SP-API conditionType enum.
    N1new_new2used_like_new3used_very_good4	used_good5used_acceptablenewzused - like newzused - very goodzused - goodzused - acceptablezlike newz	very goodgood
acceptablezcollectible - like newcollectible_like_newzcollectible - very goodcollectible_very_goodzcollectible - goodcollectible_goodzcollectible - acceptablecollectible_acceptable)strlowerstripget)r   smapping r   4/var/www/agentarbitrage/keepa_deals/amazon_sp_api.pymap_condition_to_sp_api   sR   	

r    itemsaccess_token	seller_idc                 C   s  t dt|  d| d i }|r|dd d nd}t d|  |d	d
d}t }|j| | D ]}td t	|t
rM|d }|d}	n|}d}	t|	}
||td}|
rm|
|d< t d| d|
  n	t d| d t d}t d| d|  z|j||d}|  | }|dg }t|}d}|r5d}|	rt|	 }d|v rd}nd|v rd}nd|v rd}nd|v rd}|rd| d| }nd| }|d  d!}t	|tr
|D ]}|d"p|d#pd$}|d%d&krd'|v r|} nqn+t	|t
r5|d(r5|d( D ]}|d%d&kr3d'|d#d$v r3|d# } nq||d)||< t d*| d+|  W q6 tjjy } zs|jj}t d,| d-|jj d.|  |jjd/krd0|v rd1|vrz%t d2 d3}|j||d}|jd4krt d5 n	t d6|j  W n ty } zt d7|  W Y d}~nd}~ww d8d9d)||< W Y d}~q6d}~w ty } zt jd:| d;| d<d= d8d9d)||< W Y d}~q6d}~ww t d> |S )?a+  
    Checks the restriction status for a list of items using the real Amazon SP-API.
    Uses only LWA Access Token (no AWS SigV4 required for private apps as of Oct 2023).

    Args:
        items: A list of ASIN strings OR a list of dicts {'asin': str, 'condition': str}.
        access_token: The OAuth access token for the SP-API.
        seller_id: The selling partner ID for the user.

    Returns:
        A dictionary where keys are ASINs and values are another dictionary
        with 'is_restricted' (bool) and 'approval_url' (str or None).
    z+Starting real SP-API restriction check for z items for seller .N   z...NonezUsing Access Token: zapplication/jsonz)AgentArbitrage/1.0 (Language=Python/3.12))zx-amz-access-tokenzContent-Typez
User-Agentg?asin	condition)r'   sellerIdmarketplaceIdsconditionTypezChecking restriction for ASIN z with conditionType: z (Generic check)z!/listings/2021-08-01/restrictionszRequesting URL: z with params: )paramsrestrictionsr   usedcollectiblerefurbishedzNhttps://sellercentral.amazon.com/hz/approvalrequest/restrictions/approve?asin=z&itemcondition=zBhttps://sellercentral.amazon.com/product-search/keywords/search?q=r   linksresourceuri verbGETapprovalactions)is_restrictedapproval_urlzASIN z: is_restricted=zSP-API error for ASIN z	: Status z, Body: i  zsellingpartnerapi-na.amazon.comsandboxzK403 Forbidden on Production. Attempting diagnostic check against Sandbox...zPhttps://sandbox.sellingpartnerapi-na.amazon.com/listings/2021-08-01/restrictions   a*  MISCONFIGURATION DETECTED: The SP-API Token is valid for Sandbox but rejected by Production (403). You are likely using Sandbox Credentials with the Production URL. Please update SP_API_CLIENT_ID and SP_API_CLIENT_SECRET in .env to your Production App credentials, and generate a new Refresh Token.z-Diagnostic Sandbox check also failed: Status zDiagnostic check failed: ERRORzUnexpected error checking ASIN z: T)exc_infoz"SP-API restriction check complete.)loggerinfolenrequestsSessionheadersupdatetimesleep
isinstancedictr   r    MARKETPLACE_ID_USSP_API_BASE_URL_NAraise_for_statusjsonboolr   r   list
exceptions	HTTPErrorresponsetexterrorstatus_codecriticalwarning	Exception)r!   r"   r#   resultstoken_prefixrE   sessionitemr'   r(   condition_typer,   urlrS   datar-   r9   r:   simple_condc_lowerr_linkslink_objurl_candidateactione
error_bodysandbox_urlsb_respdxr   r   r   check_restrictions;   s   




"
 "

rl   )__doc__rG   loggingosrC   urllib.parser   	getLogger__name__r@   getenvrL   rK   r   r    rP   rJ   rl   r   r   r   r   <module>   s   
'