
    Zei}5                        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                  j!                  ej                  j#                  e      d              ee      Z eed	d
dii       ej*                  j-                  d      Zer
 ee      ZndZej                  j!                  ej                  j#                  e      d      Zh dZdZ ej8                  ed       eej:                  d<   eej:                  d<   d Zd Zd Z ejC                  d      d        Z"ejC                  d      d        Z#ejC                  ddg      d         Z$ejC                  d!d"g      d#        Z%ejC                  d$d"g      d%        Z&ejC                  d&d"g      d'        Z'ed(k(  rejQ                  dd)d*+       yy),    )Flaskrequestjsonify)CORS)secure_filenameN)datetime)OpenAI)load_dotenvz.envz/api/*origins*)	resourcesOPENAI_API_KEY)api_keyuploads>   gifjpgpngjpegwebpi  P T)exist_okUPLOAD_FOLDERMAX_CONTENT_LENGTHc                 `    d| v xr) | j                  dd      d   j                         t        v S )z"Check if file extension is allowed.   )rsplitlowerALLOWED_EXTENSIONS)filenames    =/var/www/html/gamegenieapi.qlx.com/gamegenie/aatamagic/app.pyallowed_filer!   %   s0    (?WxsA6q9??AEWWW    c                 F   t         sy	 d| j                  dd       d| j                  dd       d| j                  dd       d	| j                  d
d       d| j                  dd       d| j                  dd       d| j                  dd       d| j                  dd       d| d}t         j                  j                  j	                  ddddd|dgdd      }|j
                  d   j                  j                  S # t        $ r}t        d|        Y d}~yd}~ww xY w)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 specific, structured information:
                1.  **Game Title** (Must be engaging)
                2.  **Suitability Justification** (Explain how it matches the culture, goal, and age range.)
                3.  **Required Props/Setup** (List only the materials needed from the 'Properties Available' section or basic items.)
                4.  **Instructions/Gameplay Summary** (Brief, step-by-step summary of how to play.)

                ---
                ### **USER CONTEXT**

                **A. Gathering & Culture**
                -   **Gathering Type:** gatheringTypezN/Az.
                -   **No. of Participants:** participantsz$
                -   **Age Range:** ageRangez%
                -   **Gender Mix:** genderz4
                -   **Cultural/Regional Context:** culturalContextz\

                **B. Logistics & Constraints**
                -   **Goal/Desired Mood:** moodz*
                -   **Time Constraint:** timeConstraintz/
                -   **Properties Available:** objectsa  
                -   **Budget/Material Preference:** Basic household items and minimal props

                **C. Location**
                -   **Location Description:** Medium-sized living room with flexible seating
                -   **Visual Context:** aa  

                ---
                ### **OUTPUT FORMAT**

                Please ensure the final response is easy to read.
                Generate poster-style WhatsApp version.
                Please ensure the final response follows this exact structure for all 3 suggestions:

                **1. [Game Title #1]**
                * **Justification:** [Explanation]
                * **Props:** [List of props]
                * **Instructions:** [Summary of gameplay]

                **2. [Game Title #2]**
                * **Justification:** [Explanation]
                * **Props:** [List of props]
                * **Instructions:** [Summary of gameplay]

                **3. [Game Title #3]**
                * **Justification:** [Explanation]
                * **Props:** [List of props]
                * **Instructions:** [Summary of gameplay]zgpt-4osystemzsYou are an expert Game Suggestion Engine. Generate game recommendations based on gathering context and constraints.)rolecontentusergffffff?i  )modelmessagestemperature
max_tokensr   zError calling OpenAI API: )
openai_clientgetchatcompletionscreatechoicesmessager.   	Exceptionprint)submission_datapicture_urlpromptresponsees        r     get_game_suggestions_from_openairB   )   s   I) *9)<)<_e)T(U V..=.A.A.RW.X-Y Z$$3$7$7
E$J#K L%%4%8%85%I$J K44C4G4GHY[`4a3b c, -<,?,?,N+O P**9*=*=>NPU*V)W X//>/B/B9e/T.U V)
 *5 6:50=f !%%1188 %  U
 #%	  9 
  "**222 *1#./s   C5C? ?	D DD c                 $   i }g d}| j                  d      sd|d<   n| j                  d      |vrd|d<   	 t        | j                  dd            }|dk  rd|d<   g d	}| j                  d
      sd|d
<   n| j                  d
      |vrd|d
<   g d}| j                  d      sd|d<   n| j                  d      |vrd|d<   g d}| j                  d      sd|d<   |S | j                  d      |vrd|d<   |S # t        t        f$ r d|d<   Y w xY w)zValidate form data)	FamilyzChildhood FriendszKitty Parties	ReligiousNeighborhoodz
Co-workers
ClassmateszProfessional Associations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 integer)MaleFemaleBothr'   zGender is requiredzInvalid Gender value)z18-25z26-35z36-45z46-55z56-65z65+z66+r&   zAge Range is requiredzInvalid Age Range)zAmerican IndianAsianzAfrican AmericanzLatin AmericanzMiddle EasternzPacific IslanderWhiteIndianWesternEuropeanAfricanMixedOthersr(   z'Cultural / Regional Context is requiredz#Invalid Cultural / Regional Context)r5   int
ValueError	TypeError)dataerrorsgathering_typesr%   genders
age_rangescultural_contextss          r    validate_gathering_datar]   y   sR   FO 88O$">	/	"/	9":O488NA671%UF>"
 )G88H/x	(	7	*1x MJ88J4z	*	Z	/0z
 88%&$M ! M 
#	$,=	=$I ! MC 	" O!N~Os   %C8 8DDz/infoc                  r    t         j                         t        j                  t         j	                         dS )N)python_versionflask_versionos)platformr_   flask__version__r,    r"   r    inforf      s-     #113**oo r"   /c                       y)NzGameGenie API is runningre   re   r"   r    homeri      s    %r"   z/api/gatheringPOST)methodsc                  j   	 dt         j                  vrt        ddddid      dfS t         j                  d   } | j                  dk(  rt        ddddid      dfS t	        | j                        st        dddd	id      dfS | j
                  t        kD  rt        dd
ddid      dfS t         j                  j                         }t        |      }|rt        dd|d      dfS t        | j                        }t        j                         j                  d      }||z   }t        j                  j!                  t"        j$                  d   |      }| j'                  |       |j)                  d      t+        |j)                  d            |j)                  d      |j)                  d      |j)                  d      |d| |j)                  dd      t        j                         j-                         d	}t/        d       t1        |d|       }t        j                  j!                  t        j                  j3                  t4              d      }	 t7        |d      5 }	t9        j:                  ||	d       ddd       t/        |       |r||d<   nd|d<   t        j                  j!                  t        j                  j3                  t4              d       }g }t        j                  j?                  |      r+	 t7        |d!      5 }	t9        j@                  |	      }ddd       |jE                  |       	 t7        |d      5 }	t9        j:                  ||	d       ddd       t        d"d#|d$d%      d&fS # 1 sw Y   xY w# t<        $ r}
t/        d|
        Y d}
~
d}
~
ww xY w# 1 sw Y   xY w# t8        jB                  t<        f$ r g }Y w xY w# 1 sw Y   yxY w# t<        $ r}
t/        d|
        Y d}
~
d}
~
ww xY w# tF        $ r$}
t        dd'tI        |
      d(      d)fcY d}
~
S d}
~
ww xY w)*z Handle gathering form submissionpictureFzPicture file is required)successr:   rX   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(   rm   
pictureUrlr+   submittedAtz(Fetching game suggestions from OpenAI...zhttp://localhost/uploads/ztemp.txtw   )indentNz,Warning: Could not save submission to file: gameSuggestionssubmissions.jsonrTzData submitted successfullydeepak)rn   r:   rW   kld   z/An error occurred while processing your requestrn   r:   error  )%r   filesr   r   r!   content_lengthMAX_FILE_SIZEformto_dictr]   r   r   nowstrftimera   pathjoinappconfigsaver5   rT   	isoformatr<   rB   dirname__file__openjsondumpIOErrorexistsloadJSONDecodeErrorappendr;   str)filerW   rX   r   	timestampfilepathr=   game_suggestions	temp_filefrA   submissions_filesubmissionss                r    submit_gatheringr      s    tGMM) 5$&@A  	  }}Y'==B -$&89  	  DMM* G$&Z[  	  . <$&GH  	  ||##%(. .   	  #4==1LLN++,<=	x'77<<

? ;XF		( "XXo6 89hhx(,#xx(9:)(4xx	2.#<<>335

 	89;'z2
 GGLL!:JG		Fi%		*Aa8 &
 	1AO-.15O-. 77<<(ACUV77>>*+!*C0A"&))A,K 1
 	?+	F&,		+q3 -
 4#	
 
  	? &% 	F@DEE	F  10(('2 ! ! -, 	F@DEE	F  HV
  	 	s   $P 4P 'P %P *;P &E-P N  M79N A:P <N4 N(N4 &P 8O! OO! %P 7N <N 	N%N P  N%%P (N1-N4 4OP OP OO! !	P*O=8P =PP 	P2P-'P2-P2z/api/submissionsGETc                     	 t         j                  j                  t         j                  j                  t              d      } t         j                  j                  |       st        dg dd      dfS t        | d      5 }t        j                  |      }ddd       t        dt        |      d      dfS # 1 sw Y   #xY w# t        $ r$}t        d	d
t        |      d      dfcY d}~S d}~ww xY w)zGet all submissionsrv   TzNo submissions yet)rn   rW   r:   rz   rw   N)rn   rW   totalFz.An error occurred while retrieving submissionsr{   r}   )ra   r   r   r   r   r   r   r   r   r   lenr;   r   )r   r   r   rA   s       r    get_submissionsr   7  s    77<<(ACUVww~~.//  	  "C(A))A,K ) %
  	 	 )(  GV
  	 	s<   A0C 3C ?B7!C 7C <C 	C0C+%C0+C0z/api/uploads/<filename>c                 R   	 t         j                  j                  t        j                  d   t        |             }t         j                  j                  |      rddlm}  ||      S t        ddd      dfS # t        $ r$}t        ddt        |      d	      d
fcY d}~S d}~ww xY w)zServe uploaded filesr   r   )	send_fileFzFile not found)rn   r:   i  z+An error occurred while retrieving the filer{   r}   N)ra   r   r   r   r   r   r   rc   r   r   r;   r   )r   r   r   rA   s       r    download_filer   T  s    77<<

? ;_X=VW77>>(#'X&& +     DV
  	 	s$   A&A9 )A9 9	B&B!B&!B&z/api/healthc                  $    t        dddd      dfS )zHealth check endpointTzAPI is runninghealthy)rn   r:   statusrz   )r   re   r"   r    health_checkr   h  s)     #  		 r"   __main__	localhosti  )debughostport))rc   r   r   r   
flask_corsr   werkzeug.utilsr   ra   r   r   openair	   dotenvr
   r   r   r   r   __name__r   environr5   openai_api_keyr4   r   r   r   makedirsr   r!   rB   r]   routerf   ri   r   r   r   r   runre   r"   r    <module>r      s   ) )  * 	     BGGLL2F; < Ho SYC 01 2  01>2MM RWW__X6	B:  MD )+

? #0

  XN`6p 7  3& & fX.v /vp w/ 08 $ug6 7& =5'* + zGG$[tG4 r"   