
    i@                        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                 Z   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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"#      }t        d$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:** a,  

                ---
                ### **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:
                suggestions[titlezb"Game Title 1","Justification":"Explanation","props":"Props","Instructions":"Summary of Game Play",]z
                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_tokenszOpenAI Response: {0}zError calling OpenAI API: )openai_clientgetchatcompletionscreateprintformatchoicesmessager3   	Exception)submission_datapicture_urlpromptresponsees        r     get_game_suggestions_from_openairH   )   s   q) *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 q  *L  !M  MN  OV  Wy  Nz  z{  |C  Df  {g  gh  h  i iE#p !%%1188 %  U
 #%	  9 
  	$++H56  *1#./s   C?D	 		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)r:   int
ValueError	TypeError)dataerrorsgathering_typesr%   genders
age_rangescultural_contextss          r    validate_gathering_datarc      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)platformre   flask__version__r1    r"   r    inforl      s-     #113**oo r"   /c                       y)NzGameGenie API is runningrk   rk   r"   r    homero      s    %r"   z/api/gatheringPOST)methodsc                     	 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/        d       t/        |       t        d d!|d"      d#fS # 1 sw Y   0xY w# t<        $ r}
t/        d|
        Y d}
~
Od}
~
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)successrA   r^   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(   rs   
pictureUrlr+   submittedAtz(Fetching game suggestions from OpenAI...zhttp://localhost/uploads/ztemp.txtw   )indentNz,Warning: Could not save submission to file: z$Game suggestions fetched from OpenAITzData submitted successfully)rt   rA   r]      z/An error occurred while processing your requestrt   rA   error  )%r   filesr   r   r!   content_lengthMAX_FILE_SIZEformto_dictrc   r   r   nowstrftimerg   pathjoinappconfigsaver:   rZ   	isoformatr>   rH   dirname__file__openjsondumpIOErrorexistsloadJSONDecodeErrorappendrB   str)filer]   r^   r   	timestampfilepathrC   game_suggestions	temp_filefrG   submissions_filesubmissionss                r    submit_gatheringr      s!   z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 & 	454$
  	 	 &% 	F@DEE	FV  HV
  	 	s}   $K 4K 'K %K *;K &E-K J4  J(9J4 &K (J1-J4 4	K=KK KK 	L!L :L L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 submissionszsubmissions.jsonTzNo submissions yet)rt   r]   rA   r{   rN)rt   r]   totalFz.An error occurred while retrieving submissionsr|   r~   )rg   r   r   r   r   r   r   r   r   r   lenrB   r   )r   r   r   rG   s       r    get_submissionsr   e  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)rt   rA   i  z+An error occurred while retrieving the filer|   r~   N)rg   r   r   r   r   r   r   ri   r   r   rB   r   )r   r   r   rG   s       r    download_filer     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)rt   rA   statusr{   )r   rk   r"   r    health_checkr     s)     #  		 r"   __main__	localhosti  )debughostport))ri   r   r   r   
flask_corsr   werkzeug.utilsr   rg   r   r   openair	   dotenvr
   r   r   r   r   __name__r   environr:   openai_api_keyr9   r   r   r   makedirsr   r!   rH   rc   routerl   ro   r   r   r   r   runrk   r"   r    <module>r      s   ) )  * 	     BGGLL2F; < Ho SYC 01 2  01>2MM RWW__X6	B:  MD )+

? #0

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