U
    [Ei-                     @   s  d dl mZmZmZ d dlmZ d dlmZ d dlZd dl	m	Z	 d dl
Z
d dlmZ d dlmZ eejejed eeZeed	d
diid ejdZereedZndZejejedZdddddhZdZejedd eejd< eejd< dd Zdd Zdd Z ej!d d!gd"d#d$ Z"ej!d%d&gd"d'd( Z#ej!d)d&gd"d*d+ Z$ej!d,d&gd"d-d. Z%ed/krej&dd0d1d2 dS )3    )Flaskrequestjsonify)CORS)secure_filenameN)datetime)OpenAI)load_dotenvz.envz/api/*Zorigins*)Z	resourcesZOPENAI_API_KEY)Zapi_keyZuploadsZpngZjpgZjpegZgifZwebpi  P T)exist_okUPLOAD_FOLDERZMAX_CONTENT_LENGTHc                 C   s    d| ko|  ddd  tkS )z"Check if file extension is allowed.   )rsplitlowerALLOWED_EXTENSIONS)filename r   =/var/www/html/gamegenieapi.qlx.com/gamegenie/aatamagic/app.pyallowed_file%   s    r   c                 C   s   t sdS zd| dd d| dd d| dd d	| d
d d| dd d| dd d| d}t jjjddddd|dgddd}|jd jjW S  tk
r } zt	d|  W Y dS d}~X Y nX dS )z8Get game suggestions from OpenAI based on gathering dataNa  
        **TASK:** Act as an expert Game Suggestion Engine. Based on the user's provided context and constraints, generate exactly 3 unique game recommendations.

        For each game, you must output the following:
        1. Game Title
        2. Suitability Justification
        3. Required Props/Setup
        4. Instructions/Gameplay Summary

        ---
        USER CONTEXT

        A. Gathering & Culture
        - Gathering Type: gatheringTypezN/Az 
        - No. of Participants: participantsz
        - Age Range: ageRangez
        - Gender Mix: genderz
        - Cultural Context: culturalContextz

        B. Logistics & Constraints
        - Goal: High-Energy, Competitive, Fun
        - Time Constraint: 30-60 minutes
        - Properties Available: objectsz0

        C. Location
        - Visual Context: a=  

        ---
        OUTPUT FORMAT

        1. [Game Title #1]
        - Justification
        - Props
        - Instructions

        2. [Game Title #2]
        - Justification
        - Props
        - Instructions

        3. [Game Title #3]
        - Justification
        - Props
        - Instructions
        zgpt-4osystemzsYou are an expert Game Suggestion Engine. Generate game recommendations based on gathering context and constraints.)Zrolecontentusergffffff?i  )modelmessagesZtemperatureZ
max_tokensr   zError calling OpenAI API: )
openai_clientgetZchatZcompletionscreatechoicesmessager   	Exceptionprint)submission_dataZpicture_urlpromptresponseer   r   r    get_game_suggestions_from_openai)   sD    





/
r,   c                 C   sH  i }ddddddddd	g	}|  d
s.d|d
< n|  d
|krDd|d
< z$t|  dd}|dkrfd|d< W n  ttfk
r   d|d< Y nX dddg}|  dsd|d< n|  d|krd|d< dddddddg}|  dsd|d< n|  d|krd |d< d!d"d#d$d%d&d'd(d)d*d+d,g}|  d-s,d.|d-< n|  d-|krDd/|d-< |S )0zValidate form dataZFamilyzChildhood FriendszKitty PartiesZ	ReligiousZNeighborhoodz
Co-workersZ
ClassmateszProfessional AssociationsZConventionsr   zGathering Type is requiredzInvalid Gathering Typer   r   z.No. Of Participants must be a positive integerz+No. Of Participants must be a valid integerZMaleZFemaleZBothr   zGender is requiredzInvalid Gender valuez18-25z26-35z36-45z46-55z56-65z65+z66+r   zAge Range is requiredzInvalid Age RangezNorth IndianzSouth IndianzEast IndianzWest IndianzNortheast IndianZWesternZAsianZEuropeanZAfricanzLatin AmericanzMiddle EasternZOthersr   z'Cultural / Regional Context is requiredz#Invalid Cultural / Regional Context)r"   int
ValueError	TypeError)dataerrorsZgathering_typesr   ZgendersZ
age_rangesZcultural_contextsr   r   r   validate_gathering_datau   sb          






         
r2   z/api/gatheringPOST)methodsc                  C   s  zpdt jkr(tddddiddfW S t jd } | jdkrVtddddiddfW S t| jsztdddd	iddfW S | jtkrtdd
ddiddfW S t j }t	|}|rtdd|ddfW S t
| j}t d}|| }tjtjd |}| | |dt|d|d|d|d|d| |ddt  d	}td t|d| }|r||d< nd|d< tjtjtd}g }	tj|rz$t|d}
t|
}	W 5 Q R X W n  tjt fk
r   g }	Y nX |	!| z*t|d}
tj"|	|
dd W 5 Q R X W n2 t k
r\ } ztd |  W 5 d}~X Y nX td!d"|d#d$fW S  t#k
r } z tdd%t$|d&d'f W Y S d}~X Y nX dS )(z Handle gathering form submissionpictureFzPicture file is required)successr%   r1   i   zNo file selectedz*Invalid file type. Only images are allowedz2Only image files are allowed (JPG, PNG, GIF, WebP)zFile size exceeds maximum limitzFile size must be less than 5MBzValidation failedz%Y%m%d_%H%M%S_r   r   r   r   r   r   z/api/uploads/r   )	r   r   r   r   r   r5   Z
pictureUrlr   ZsubmittedAtz(Fetching game suggestions from OpenAI...z"http://localhost:3000/api/uploads/ZgameSuggestionsNsubmissions.jsonrw   )indentz,Warning: Could not save submission to file: TzData submitted successfully)r6   r%   r0      z/An error occurred while processing your requestr6   r%   error  )%r   filesr   r   r   content_lengthMAX_FILE_SIZEformZto_dictr2   r   r   nowstrftimeospathjoinappconfigsaver"   r-   	isoformatr'   r,   dirname__file__existsopenjsonloadZJSONDecodeErrorIOErrorappenddumpr&   str)filer0   r1   r   	timestampfilepathr(   Zgame_suggestionssubmissions_filesubmissionsfr+   r   r   r   submit_gathering   s    












 r^   z/api/submissionsGETc               
   C   s   zrt jt jtd} t j| s:tdg dddfW S t| d}t	|}W 5 Q R X td|t
|ddfW S  tk
r } z tdd	t|d
df W Y S d}~X Y nX dS )zGet all submissionsr8   TzNo submissions yet)r6   r0   r%   r=   r9   )r6   r0   totalFz.An error occurred while retrieving submissionsr>   r@   N)rG   rH   rI   rN   rO   rP   r   rQ   rR   rS   lenr&   rW   )r[   r]   r\   r+   r   r   r   get_submissions  s6    rb   z/api/uploads/<filename>c              
   C   s   zRt jtjd t| }t j|r<ddlm} ||W S t	ddddfW S W n> t
k
r } z t	ddt|d	d
f W Y S d}~X Y nX dS )zServe uploaded filesr   r   )	send_fileFzFile not found)r6   r%   i  z+An error occurred while retrieving the filer>   r@   N)rG   rH   rI   rJ   rK   r   rP   flaskrc   r   r&   rW   )r   rZ   rc   r+   r   r   r   download_file7  s&    

re   z/api/healthc                   C   s   t dddddfS )zHealth check endpointTzAPI is runningZhealthy)r6   r%   statusr=   )r   r   r   r   r   health_checkK  s    rg   __main__	localhosti  )debughostport)'rd   r   r   r   Z
flask_corsr   Zwerkzeug.utilsr   rG   r   rR   Zopenair   Zdotenvr	   rH   rI   rN   rO   __name__rJ   environr"   Zopenai_api_keyr!   r   r   rC   makedirsrK   r   r,   r2   Zrouter^   rb   re   rg   runr   r   r   r   <module>   sB   

L7
m



